LLVM 24.0.0git
SIInstrInfo.cpp
Go to the documentation of this file.
1//===- SIInstrInfo.cpp - SI Instruction Information ----------------------===//
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/// SI Implementation of TargetInstrInfo.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SIInstrInfo.h"
15#include "AMDGPU.h"
16#include "AMDGPUInstrInfo.h"
17#include "AMDGPULaneMaskUtils.h"
18#include "AMDGPUMachineInstrs.h"
19#include "GCNHazardRecognizer.h"
20#include "GCNSubtarget.h"
23#include "llvm/ADT/STLExtras.h"
34#include "llvm/IR/IntrinsicsAMDGPU.h"
35#include "llvm/MC/MCContext.h"
38#include <tuple>
39
40using namespace llvm;
41
42#define DEBUG_TYPE "si-instr-info"
43
44#define GET_INSTRINFO_CTOR_DTOR
45#include "AMDGPUGenInstrInfo.inc"
46
47namespace llvm::AMDGPU {
48#define GET_ImageDimIntrinsicTable_IMPL
49#define GET_RsrcIntrinsics_IMPL
50#define GET_BufferIntrinsicsTable_IMPL
51#define GET_GFX1250BlockingCyclesTable_DECL
52#define GET_GFX1250BlockingCyclesTable_IMPL
53
58
59#include "AMDGPUGenSearchableTables.inc"
60} // namespace llvm::AMDGPU
61
63 : AMDGPUGenInstrInfo(ST, RI, AMDGPU::ADJCALLSTACKUP,
64 AMDGPU::ADJCALLSTACKDOWN),
65 RI(ST), ST(ST) {
66 SchedModel.init(&ST);
67}
68
69//===----------------------------------------------------------------------===//
70// TargetInstrInfo callbacks
71//===----------------------------------------------------------------------===//
72
73static unsigned getNumOperandsNoGlue(SDNode *Node) {
74 unsigned N = Node->getNumOperands();
75 while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
76 --N;
77 return N;
78}
79
80/// Returns true if both nodes have the same value for the given
81/// operand \p Op, or if both nodes do not have this operand.
83 AMDGPU::OpName OpName) {
84 unsigned Opc0 = N0->getMachineOpcode();
85 unsigned Opc1 = N1->getMachineOpcode();
86
87 int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
88 int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
89
90 if (Op0Idx == -1 && Op1Idx == -1)
91 return true;
92
93
94 if ((Op0Idx == -1 && Op1Idx != -1) ||
95 (Op1Idx == -1 && Op0Idx != -1))
96 return false;
97
98 // getNamedOperandIdx returns the index for the MachineInstr's operands,
99 // which includes the result as the first operand. We are indexing into the
100 // MachineSDNode's operands, so we need to skip the result operand to get
101 // the real index.
102 --Op0Idx;
103 --Op1Idx;
104
105 return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
106}
107
108static bool canRemat(const MachineInstr &MI) {
109
113 return true;
114
115 if (SIInstrInfo::isSMRD(MI)) {
116 return !MI.memoperands_empty() &&
117 llvm::all_of(MI.memoperands(), [](const MachineMemOperand *MMO) {
118 return MMO->isLoad() && MMO->isInvariant();
119 });
120 }
121
122 return false;
123}
124
125// Split relocation flags for 64-bit global-address materialization into the
126// flags for the lo and hi halves.
127static std::pair<unsigned, unsigned>
129 const unsigned Flags = SrcOp.getTargetFlags();
130
131 // Infer the relocation type from the existing flags on the global operand.
132 // The relocation type should have been determined earlier in the pipeline.
133 switch (Flags & SIInstrInfo::MO_MASK) {
136 // For 64-bit GOT-relative, use the 64-bit relocation.
137 const unsigned GotFlags =
138 (Flags & ~SIInstrInfo::MO_MASK) | SIInstrInfo::MO_GOTPCREL64;
139 return {GotFlags, GotFlags};
140 }
141 default:
142 break;
143 }
144
145 std::optional<unsigned> LoFlags =
147 std::optional<unsigned> HiFlags =
149 if (!LoFlags || !HiFlags)
150 llvm_unreachable("unknown relocation type for global address");
151 return {*LoFlags, *HiFlags};
152}
153
155 const MachineInstr &MI) const {
156
157 if (canRemat(MI)) {
158 // Normally VALU use of exec would block the rematerialization, but that
159 // is OK in this case to have an implicit exec read as all VALU do.
160 // We really want all of the generic logic for this except for this.
161
162 // Another potential implicit use is mode register. The core logic of
163 // the RA will not attempt rematerialization if mode is set anywhere
164 // in the function, otherwise it is safe since mode is not changed.
165
166 // There is difference to generic method which does not allow
167 // rematerialization if there are virtual register uses. We allow this,
168 // therefore this method includes SOP instructions as well.
169 if (!MI.hasImplicitDef() &&
170 MI.getNumImplicitOperands() == MI.getDesc().implicit_uses().size() &&
171 !MI.mayRaiseFPException())
172 return true;
173 }
174
175 // Everything below copied from TargetInstrInfo::isReMaterializableImpl. The
176 // only difference is that we allow operations that perform read-modify-write
177 // on sub-registers.
178
179 // Remat clients assume operand 0 is the defined register.
180 if (!MI.getNumOperands() || !MI.getOperand(0).isReg())
181 return false;
182 Register DefReg = MI.getOperand(0).getReg();
183
184 const MachineFunction &MF = *MI.getMF();
185
186 // A load from a fixed stack slot can be rematerialized. This may be
187 // redundant with subsequent checks, but it's target-independent,
188 // simple, and a common case.
189 int FrameIdx = 0;
190 if (isLoadFromStackSlot(MI, FrameIdx) &&
192 return true;
193
194 // Avoid instructions obviously unsafe for remat.
195 if (MI.isNotDuplicable() || MI.mayStore() || MI.mayRaiseFPException() ||
196 MI.hasUnmodeledSideEffects())
197 return false;
198
199 // Don't remat inline asm. We have no idea how expensive it is
200 // even if it's side effect free.
201 if (MI.isInlineAsm())
202 return false;
203
204 // Avoid instructions which load from potentially varying memory.
205 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad())
206 return false;
207
208 const MachineRegisterInfo &MRI = MF.getRegInfo();
209
210 // If any of the registers accessed are non-constant, conservatively assume
211 // the instruction is not rematerializable.
212 for (const MachineOperand &MO : MI.operands()) {
213 if (!MO.isReg())
214 continue;
215 Register Reg = MO.getReg();
216 if (Reg == 0)
217 continue;
218
219 // Check for a well-behaved physical register.
220 if (Reg.isPhysical()) {
221 if (MO.isUse()) {
222 // If the physreg has no defs anywhere, it's just an ambient register
223 // and we can freely move its uses. Alternatively, if it's allocatable,
224 // it could get allocated to something with a def during allocation.
225 if (!MRI.isConstantPhysReg(Reg))
226 return false;
227 } else {
228 // A physreg def. We can't remat it.
229 return false;
230 }
231 continue;
232 }
233
234 // Only allow one virtual-register def. There may be multiple defs of the
235 // same virtual register, though.
236 if (MO.isDef() && Reg != DefReg)
237 return false;
238 }
239
240 return true;
241}
242
244 switch (Opcode) {
245 // v_subrev_u16 (gfx9)
246 case AMDGPU::V_SUBREV_U16_e32:
247 case AMDGPU::V_SUBREV_U16_e64:
248 // v_subrev_u32 (gfx9) / v_subrev_nc_u32 (gfx10+)
249 case AMDGPU::V_SUBREV_U32_e32:
250 case AMDGPU::V_SUBREV_U32_e64:
251 // v_subrev_co_u32
252 case AMDGPU::V_SUBREV_CO_U32_e32:
253 case AMDGPU::V_SUBREV_CO_U32_e64:
254 // v_subbrev_u32 (gfx9) / v_subrev_co_ci_u32 (gfx10+)
255 case AMDGPU::V_SUBBREV_U32_e32:
256 case AMDGPU::V_SUBBREV_U32_e64:
257 return true;
258 // REV shift opcodes worked this way before GFX11, verified on hardware
259 case AMDGPU::V_ASHRREV_I16_e32:
260 case AMDGPU::V_ASHRREV_I16_e64:
261 case AMDGPU::V_ASHRREV_I32_e32:
262 case AMDGPU::V_ASHRREV_I32_e64:
263 case AMDGPU::V_ASHRREV_I64_e64:
264 case AMDGPU::V_LSHLREV_B16_e32:
265 case AMDGPU::V_LSHLREV_B16_e64:
266 case AMDGPU::V_LSHLREV_B32_e32:
267 case AMDGPU::V_LSHLREV_B32_e64:
268 case AMDGPU::V_LSHLREV_B64_e64:
269 case AMDGPU::V_LSHRREV_B16_e32:
270 case AMDGPU::V_LSHRREV_B16_e64:
271 case AMDGPU::V_LSHRREV_B32_e32:
272 case AMDGPU::V_LSHRREV_B32_e64:
273 case AMDGPU::V_LSHRREV_B64_e64:
274 return !ST.hasGFX11Insts();
275 default:
276 return false;
277 }
278}
279
280// Returns true if the result of a VALU instruction depends on exec.
281bool SIInstrInfo::resultDependsOnExec(const MachineInstr &MI) const {
282 assert(isVALU(MI, /*AllowLDSDMA=*/true));
283
284 // If it is convergent it depends on EXEC.
285 if (MI.isConvergent())
286 return true;
287
288 // If it defines an SGPR it depends on EXEC, unless it's dead.
289 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
290 for (const MachineOperand &Def : MI.defs()) {
291 if (Def.isDead())
292 continue;
293
294 Register Reg = Def.getReg();
295 if (Reg && RI.isSGPRReg(MRI, Reg))
296 return true;
297 }
298
299 return false;
300}
301
302bool SIInstrInfo::isIgnorableUse(const MachineInstr &MI, unsigned OpIdx) const {
303 const MachineOperand &MO = MI.getOperand(OpIdx);
304 // Any implicit use of exec by VALU is not a real register read.
305 return MO.getReg() == AMDGPU::EXEC && MO.isImplicit() &&
306 isVALU(MI, /*AllowLDSDMA=*/true) && !resultDependsOnExec(MI);
307}
308
310 MachineBasicBlock *SuccToSinkTo,
311 MachineCycleInfo *CI) const {
312 // Allow sinking if MI edits lane mask (divergent i1 in sgpr).
313 if (MI.getOpcode() == AMDGPU::SI_IF_BREAK)
314 return true;
315
316 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
317 // Check if sinking of MI would create temporal divergent use.
318 for (auto Op : MI.uses()) {
319 if (Op.isReg() && Op.getReg().isVirtual() &&
320 RI.isSGPRClass(MRI.getRegClass(Op.getReg()))) {
321 MachineInstr *SgprDef = MRI.getVRegDef(Op.getReg());
322 if (!SgprDef)
323 continue;
324
325 // SgprDef defined inside cycle
326 CycleRef FromCycle = CI->getCycle(SgprDef->getParent());
327 if (!FromCycle)
328 continue;
329
330 CycleRef ToCycle = CI->getCycle(SuccToSinkTo);
331 // Check if there is a FromCycle that contains SgprDef's basic block but
332 // does not contain SuccToSinkTo and also has divergent exit condition.
333 while (FromCycle && !(ToCycle && CI->contains(FromCycle, ToCycle))) {
335 CI->getExitingBlocks(FromCycle, ExitingBlocks);
336
337 // FromCycle has divergent exit condition.
338 for (MachineBasicBlock *ExitingBlock : ExitingBlocks) {
339 if (hasDivergentBranch(ExitingBlock))
340 return false;
341 }
342
343 FromCycle = CI->getParentCycle(FromCycle);
344 }
345 }
346 }
347
348 return true;
349}
350
352 int64_t &Offset0,
353 int64_t &Offset1) const {
354 if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
355 return false;
356
357 unsigned Opc0 = Load0->getMachineOpcode();
358 unsigned Opc1 = Load1->getMachineOpcode();
359
360 // Make sure both are actually loads.
361 if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
362 return false;
363
364 // A mayLoad instruction without a def is not a load. Likely a prefetch.
365 if (!get(Opc0).getNumDefs() || !get(Opc1).getNumDefs())
366 return false;
367
368 if (isDS(Opc0) && isDS(Opc1)) {
369
370 // FIXME: Handle this case:
371 if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
372 return false;
373
374 // Check base reg.
375 if (Load0->getOperand(0) != Load1->getOperand(0))
376 return false;
377
378 // Skip read2 / write2 variants for simplicity.
379 // TODO: We should report true if the used offsets are adjacent (excluded
380 // st64 versions).
381 int Offset0Idx = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
382 int Offset1Idx = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
383 if (Offset0Idx == -1 || Offset1Idx == -1)
384 return false;
385
386 // XXX - be careful of dataless loads
387 // getNamedOperandIdx returns the index for MachineInstrs. Since they
388 // include the output in the operand list, but SDNodes don't, we need to
389 // subtract the index by one.
390 Offset0Idx -= get(Opc0).NumDefs;
391 Offset1Idx -= get(Opc1).NumDefs;
392 Offset0 = Load0->getConstantOperandVal(Offset0Idx);
393 Offset1 = Load1->getConstantOperandVal(Offset1Idx);
394 return true;
395 }
396
397 if (isSMRD(Opc0) && isSMRD(Opc1)) {
398 // Skip time and cache invalidation instructions.
399 if (!AMDGPU::hasNamedOperand(Opc0, AMDGPU::OpName::sbase) ||
400 !AMDGPU::hasNamedOperand(Opc1, AMDGPU::OpName::sbase))
401 return false;
402
403 unsigned NumOps = getNumOperandsNoGlue(Load0);
404 if (NumOps != getNumOperandsNoGlue(Load1))
405 return false;
406
407 // Check base reg.
408 if (Load0->getOperand(0) != Load1->getOperand(0))
409 return false;
410
411 // Match register offsets, if both register and immediate offsets present.
412 assert(NumOps == 4 || NumOps == 5);
413 if (NumOps == 5 && Load0->getOperand(1) != Load1->getOperand(1))
414 return false;
415
416 const ConstantSDNode *Load0Offset =
418 const ConstantSDNode *Load1Offset =
420
421 if (!Load0Offset || !Load1Offset)
422 return false;
423
424 Offset0 = Load0Offset->getZExtValue();
425 Offset1 = Load1Offset->getZExtValue();
426 return true;
427 }
428
429 // MUBUF and MTBUF can access the same addresses.
430 if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
431
432 // MUBUF and MTBUF have vaddr at different indices.
433 if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
434 !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
435 !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
436 return false;
437
438 int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
439 int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
440
441 if (OffIdx0 == -1 || OffIdx1 == -1)
442 return false;
443
444 // getNamedOperandIdx returns the index for MachineInstrs. Since they
445 // include the output in the operand list, but SDNodes don't, we need to
446 // subtract the index by one.
447 OffIdx0 -= get(Opc0).NumDefs;
448 OffIdx1 -= get(Opc1).NumDefs;
449
450 SDValue Off0 = Load0->getOperand(OffIdx0);
451 SDValue Off1 = Load1->getOperand(OffIdx1);
452
453 // The offset might be a FrameIndexSDNode.
454 if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
455 return false;
456
457 Offset0 = Off0->getAsZExtVal();
458 Offset1 = Off1->getAsZExtVal();
459 return true;
460 }
461
462 return false;
463}
464
465static bool isStride64(unsigned Opc) {
466 switch (Opc) {
467 case AMDGPU::DS_READ2ST64_B32:
468 case AMDGPU::DS_READ2ST64_B64:
469 case AMDGPU::DS_WRITE2ST64_B32:
470 case AMDGPU::DS_WRITE2ST64_B64:
471 return true;
472 default:
473 return false;
474 }
475}
476
479 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const {
480 if (!LdSt.mayLoadOrStore())
481 return false;
482
483 unsigned Opc = LdSt.getOpcode();
484 OffsetIsScalable = false;
485 const MachineOperand *BaseOp, *OffsetOp;
486 int DataOpIdx;
487
488 if (isDS(LdSt)) {
489 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::addr);
490 OffsetOp = getNamedOperand(LdSt, AMDGPU::OpName::offset);
491 if (OffsetOp) {
492 // Normal, single offset LDS instruction.
493 if (!BaseOp) {
494 // DS_CONSUME/DS_APPEND use M0 for the base address.
495 // TODO: find the implicit use operand for M0 and use that as BaseOp?
496 return false;
497 }
498 BaseOps.push_back(BaseOp);
499 Offset = OffsetOp->getImm();
500 // Get appropriate operand, and compute width accordingly.
501 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
502 if (DataOpIdx == -1)
503 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
504 if (Opc == AMDGPU::DS_ATOMIC_ASYNC_BARRIER_ARRIVE_B64)
505 Width = LocationSize::precise(64);
506 else
507 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
508 } else {
509 // The 2 offset instructions use offset0 and offset1 instead. We can treat
510 // these as a load with a single offset if the 2 offsets are consecutive.
511 // We will use this for some partially aligned loads.
512 const MachineOperand *Offset0Op =
513 getNamedOperand(LdSt, AMDGPU::OpName::offset0);
514 const MachineOperand *Offset1Op =
515 getNamedOperand(LdSt, AMDGPU::OpName::offset1);
516
517 unsigned Offset0 = Offset0Op->getImm() & 0xff;
518 unsigned Offset1 = Offset1Op->getImm() & 0xff;
519 if (Offset0 + 1 != Offset1)
520 return false;
521
522 // Each of these offsets is in element sized units, so we need to convert
523 // to bytes of the individual reads.
524
525 unsigned EltSize;
526 if (LdSt.mayLoad())
527 EltSize = RI.getRegSizeInBits(*getOpRegClass(LdSt, 0)) / 16;
528 else {
529 assert(LdSt.mayStore());
530 int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
531 EltSize = RI.getRegSizeInBits(*getOpRegClass(LdSt, Data0Idx)) / 8;
532 }
533
534 if (isStride64(Opc))
535 EltSize *= 64;
536
537 BaseOps.push_back(BaseOp);
538 Offset = EltSize * Offset0;
539 // Get appropriate operand(s), and compute width accordingly.
540 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
541 if (DataOpIdx == -1) {
542 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
543 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
544 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data1);
545 Width = LocationSize::precise(
546 Width.getValue() + TypeSize::getFixed(getOpSize(LdSt, DataOpIdx)));
547 } else {
548 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
549 }
550 }
551 return true;
552 }
553
554 if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
555 const MachineOperand *RSrc = getNamedOperand(LdSt, AMDGPU::OpName::srsrc);
556 if (!RSrc) // e.g. BUFFER_WBINVL1_VOL
557 return false;
558 BaseOps.push_back(RSrc);
559 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
560 if (BaseOp && !BaseOp->isFI())
561 BaseOps.push_back(BaseOp);
562 const MachineOperand *OffsetImm =
563 getNamedOperand(LdSt, AMDGPU::OpName::offset);
564 Offset = OffsetImm->getImm();
565 const MachineOperand *SOffset =
566 getNamedOperand(LdSt, AMDGPU::OpName::soffset);
567 if (SOffset) {
568 if (SOffset->isReg())
569 BaseOps.push_back(SOffset);
570 else
571 Offset += SOffset->getImm();
572 }
573 // Get appropriate operand, and compute width accordingly.
574 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
575 if (DataOpIdx == -1)
576 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
577 if (DataOpIdx == -1) // LDS DMA
578 return false;
579 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
580 return true;
581 }
582
583 if (isImage(LdSt)) {
584 auto RsrcOpName =
585 isMIMG(LdSt) ? AMDGPU::OpName::srsrc : AMDGPU::OpName::rsrc;
586 int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opc, RsrcOpName);
587 BaseOps.push_back(&LdSt.getOperand(SRsrcIdx));
588 int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
589 if (VAddr0Idx >= 0) {
590 // GFX10 possible NSA encoding.
591 for (int I = VAddr0Idx; I < SRsrcIdx; ++I)
592 BaseOps.push_back(&LdSt.getOperand(I));
593 } else {
594 BaseOps.push_back(getNamedOperand(LdSt, AMDGPU::OpName::vaddr));
595 }
596 Offset = 0;
597 // Get appropriate operand, and compute width accordingly.
598 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
599 if (DataOpIdx == -1)
600 return false; // no return sampler
601 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
602 return true;
603 }
604
605 if (isSMRD(LdSt)) {
606 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::sbase);
607 if (!BaseOp) // e.g. S_MEMTIME
608 return false;
609 BaseOps.push_back(BaseOp);
610 OffsetOp = getNamedOperand(LdSt, AMDGPU::OpName::offset);
611 Offset = OffsetOp ? OffsetOp->getImm() : 0;
612 // Get appropriate operand, and compute width accordingly.
613 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::sdst);
614 if (DataOpIdx == -1)
615 return false;
616 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
617 return true;
618 }
619
620 if (isFLAT(LdSt)) {
621 // Instructions have either vaddr or saddr or both or none.
622 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
623 if (BaseOp)
624 BaseOps.push_back(BaseOp);
625 BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::saddr);
626 if (BaseOp)
627 BaseOps.push_back(BaseOp);
628 Offset = getNamedOperand(LdSt, AMDGPU::OpName::offset)->getImm();
629 // Get appropriate operand, and compute width accordingly.
630 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
631 if (DataOpIdx == -1)
632 DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
633 if (DataOpIdx == -1) // LDS DMA
634 return false;
635 Width = LocationSize::precise(getOpSize(LdSt, DataOpIdx));
636 return true;
637 }
638
639 if (auto *LdStIdx = dyn_cast<AMDGPUMI::VLoadStoreIdxInst>(&LdSt)) {
640 // The movrel form's index is whatever M0 holds, which can change between
641 // accesses, so it has no base operand to report.
642 if (!LdStIdx->isGPRIdx())
643 return false;
644 BaseOp = &LdStIdx->getIdxOp();
645 OffsetOp = &LdStIdx->getOffsetOp();
646 if (!BaseOp->getReg().isVirtual())
647 return false;
648
649 BaseOps.push_back(BaseOp);
650 Offset = OffsetOp->getImm() * 4; // Offset has units of dwords.
651 Width = LocationSize::precise(LdStIdx->getBitWidth() / 8);
652 return true;
653 }
654
655 return false;
656}
657
658static bool memOpsHaveSameBasePtr(const MachineInstr &MI1,
660 const MachineInstr &MI2,
662 // Only examine the first "base" operand of each instruction, on the
663 // assumption that it represents the real base address of the memory access.
664 // Other operands are typically offsets or indices from this base address.
665 if (BaseOps1.front()->isIdenticalTo(*BaseOps2.front()))
666 return true;
667
668 if (!MI1.hasOneMemOperand() || !MI2.hasOneMemOperand())
669 return false;
670
671 auto *MO1 = *MI1.memoperands_begin();
672 auto *MO2 = *MI2.memoperands_begin();
673 if (MO1->getAddrSpace() != MO2->getAddrSpace())
674 return false;
675
676 const auto *Base1 = MO1->getValue();
677 const auto *Base2 = MO2->getValue();
678 if (!Base1 || !Base2)
679 return false;
680 Base1 = getUnderlyingObject(Base1);
681 Base2 = getUnderlyingObject(Base2);
682
683 if (isa<UndefValue>(Base1) || isa<UndefValue>(Base2))
684 return false;
685
686 return Base1 == Base2;
687}
688
691 ArrayRef<const MachineOperand *> BaseOps2) const {
692 // Accesses without base operands (e.g. scratch addressed only by an
693 // immediate offset) share the same implicit base.
694 if (BaseOps1.empty() || BaseOps2.empty())
695 return BaseOps1.empty() && BaseOps2.empty();
696 return memOpsHaveSameBasePtr(*BaseOps1.front()->getParent(), BaseOps1,
697 *BaseOps2.front()->getParent(), BaseOps2);
698}
699
701 int64_t Offset1, bool OffsetIsScalable1,
703 int64_t Offset2, bool OffsetIsScalable2,
704 unsigned ClusterSize,
705 unsigned NumBytes) const {
706 // If the mem ops (to be clustered) do not have the same base ptr, then they
707 // should not be clustered
708 if (!memOpsHaveSameBase(BaseOps1, BaseOps2))
709 return false;
710
711 // Both lists are empty or neither is, so BaseOps1 alone decides whether
712 // there is an instruction to read the budget from.
713 assert(BaseOps1.empty() == BaseOps2.empty());
714 unsigned MaxMemoryClusterDWords = DefaultMemoryClusterDWordsLimit;
715 if (!BaseOps1.empty()) {
716 const MachineFunction *MF = BaseOps1.front()->getParent()->getMF();
717 MaxMemoryClusterDWords =
718 MF->getInfo<SIMachineFunctionInfo>()->getMaxMemoryClusterDWords();
719 }
720
721 // In order to avoid register pressure, on an average, the number of DWORDS
722 // loaded together by all clustered mem ops should not exceed
723 // MaxMemoryClusterDWords. This is an empirical value based on certain
724 // observations and performance related experiments.
725 // The good thing about this heuristic is - it avoids clustering of too many
726 // sub-word loads, and also avoids clustering of wide loads. Below is the
727 // brief summary of how the heuristic behaves for various `LoadSize` when
728 // MaxMemoryClusterDWords is 8.
729 //
730 // (1) 1 <= LoadSize <= 4: cluster at max 8 mem ops
731 // (2) 5 <= LoadSize <= 8: cluster at max 4 mem ops
732 // (3) 9 <= LoadSize <= 12: cluster at max 2 mem ops
733 // (4) 13 <= LoadSize <= 16: cluster at max 2 mem ops
734 // (5) LoadSize >= 17: do not cluster
735 const unsigned LoadSize = NumBytes / ClusterSize;
736 const unsigned NumDWords = ((LoadSize + 3) / 4) * ClusterSize;
737 return NumDWords <= MaxMemoryClusterDWords;
738}
739
740// FIXME: This behaves strangely. If, for example, you have 32 load + stores,
741// the first 16 loads will be interleaved with the stores, and the next 16 will
742// be clustered as expected. It should really split into 2 16 store batches.
743//
744// Loads are clustered until this returns false, rather than trying to schedule
745// groups of stores. This also means we have to deal with saying different
746// address space loads should be clustered, and ones which might cause bank
747// conflicts.
748//
749// This might be deprecated so it might not be worth that much effort to fix.
751 int64_t Offset0, int64_t Offset1,
752 unsigned NumLoads) const {
753 assert(Offset1 > Offset0 &&
754 "Second offset should be larger than first offset!");
755 // If we have less than 16 loads in a row, and the offsets are within 64
756 // bytes, then schedule together.
757
758 // A cacheline is 64 bytes (for global memory).
759 return (NumLoads <= 16 && (Offset1 - Offset0) < 64);
760}
761
764 const DebugLoc &DL, MCRegister DestReg,
765 MCRegister SrcReg, bool KillSrc,
766 const char *Msg = "illegal VGPR to SGPR copy") {
767 MachineFunction *MF = MBB.getParent();
768
771
772 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_ILLEGAL_COPY), DestReg)
773 .addReg(SrcReg, getKillRegState(KillSrc));
774}
775
776/// Handle copying from SGPR to AGPR, or from AGPR to AGPR on GFX908. It is not
777/// possible to have a direct copy in these cases on GFX908, so an intermediate
778/// VGPR copy is required.
781 const DebugLoc &DL, MCRegister DestReg,
782 MCRegister SrcReg, bool KillSrc,
783 RegScavenger &RS, bool RegsOverlap,
784 Register ImpUseSuperReg = Register()) {
785 assert((TII.getSubtarget().hasMAIInsts() &&
786 !TII.getSubtarget().hasGFX90AInsts()) &&
787 "Expected GFX908 subtarget.");
788
789 assert((AMDGPU::SReg_32RegClass.contains(SrcReg) ||
790 AMDGPU::AGPR_32RegClass.contains(SrcReg)) &&
791 "Source register of the copy should be either an SGPR or an AGPR.");
792
793 assert(AMDGPU::AGPR_32RegClass.contains(DestReg) &&
794 "Destination register of the copy should be an AGPR.");
795
796 const SIRegisterInfo &RI = TII.getRegisterInfo();
797
798 // First try to find defining accvgpr_write to avoid temporary registers.
799 // In the case of copies of overlapping AGPRs, we conservatively do not
800 // reuse previous accvgpr_writes. Otherwise, we may incorrectly pick up
801 // an accvgpr_write used for this same copy due to implicit-defs
802 if (!RegsOverlap) {
803 for (auto Def = MI, E = MBB.begin(); Def != E; ) {
804 --Def;
805
806 if (!Def->modifiesRegister(SrcReg, &RI))
807 continue;
808
809 if (Def->getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64 ||
810 Def->getOperand(0).getReg() != SrcReg)
811 break;
812
813 MachineOperand &DefOp = Def->getOperand(1);
814 assert(DefOp.isReg() || DefOp.isImm());
815
816 if (DefOp.isReg()) {
817 bool SafeToPropagate = true;
818 // Check that register source operand is not clobbered before MI.
819 // Immediate operands are always safe to propagate.
820 for (auto I = Def; I != MI && SafeToPropagate; ++I)
821 if (I->modifiesRegister(DefOp.getReg(), &RI))
822 SafeToPropagate = false;
823
824 if (!SafeToPropagate)
825 break;
826
827 for (auto I = Def; I != MI; ++I)
828 I->clearRegisterKills(DefOp.getReg(), &RI);
829 }
830
831 MachineInstrBuilder Builder =
832 BuildMI(MBB, MI, DL, TII.get(AMDGPU::V_ACCVGPR_WRITE_B32_e64),
833 DestReg)
834 .add(DefOp);
835
836 if (ImpUseSuperReg) {
837 Builder.addReg(ImpUseSuperReg,
839 }
840
841 return;
842 }
843 }
844
845 RS.enterBasicBlockEnd(MBB);
846 RS.backward(std::next(MI));
847
848 // Ideally we want to have three registers for a long reg_sequence copy
849 // to hide 2 waitstates between v_mov_b32 and accvgpr_write.
850 unsigned MaxVGPRs = RI.getRegPressureLimit(&AMDGPU::VGPR_32RegClass,
851 *MBB.getParent());
852
853 // Registers in the sequence are allocated contiguously so we can just
854 // use register number to pick one of three round-robin temps.
855 unsigned RegNo = (DestReg - AMDGPU::AGPR0) % 3;
856 Register Tmp =
857 MBB.getParent()->getInfo<SIMachineFunctionInfo>()->getVGPRForAGPRCopy();
858 assert(MBB.getParent()->getRegInfo().isReserved(Tmp) &&
859 "VGPR used for an intermediate copy should have been reserved.");
860
861 // Only loop through if there are any free registers left. We don't want to
862 // spill.
863 while (RegNo--) {
864 Register Tmp2 = RS.scavengeRegisterBackwards(AMDGPU::VGPR_32RegClass, MI,
865 /* RestoreAfter */ false, 0,
866 /* AllowSpill */ false);
867 if (!Tmp2 || RI.getHWRegIndex(Tmp2) >= MaxVGPRs)
868 break;
869 Tmp = Tmp2;
870 RS.setRegUsed(Tmp);
871 }
872
873 // Insert copy to temporary VGPR.
874 unsigned TmpCopyOp = AMDGPU::V_MOV_B32_e32;
875 if (AMDGPU::AGPR_32RegClass.contains(SrcReg)) {
876 TmpCopyOp = AMDGPU::V_ACCVGPR_READ_B32_e64;
877 } else {
878 assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
879 }
880
881 MachineInstrBuilder UseBuilder = BuildMI(MBB, MI, DL, TII.get(TmpCopyOp), Tmp)
882 .addReg(SrcReg, getKillRegState(KillSrc));
883 if (ImpUseSuperReg) {
884 UseBuilder.addReg(ImpUseSuperReg,
886 }
887
888 BuildMI(MBB, MI, DL, TII.get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
889 .addReg(Tmp, RegState::Kill);
890}
891
894 MCRegister DestReg, MCRegister SrcReg, bool KillSrc,
895 const TargetRegisterClass *RC, bool Forward) {
896 const SIRegisterInfo &RI = TII.getRegisterInfo();
897 ArrayRef<int16_t> BaseIndices = RI.getRegSplitParts(RC, 4);
899 MachineInstr *FirstMI = nullptr, *LastMI = nullptr;
900
901 for (unsigned Idx = 0; Idx < BaseIndices.size(); ++Idx) {
902 int16_t SubIdx = BaseIndices[Idx];
903 Register DestSubReg = RI.getSubReg(DestReg, SubIdx);
904 Register SrcSubReg = RI.getSubReg(SrcReg, SubIdx);
905 assert(DestSubReg && SrcSubReg && "Failed to find subregs!");
906 unsigned Opcode = AMDGPU::S_MOV_B32;
907
908 // Is SGPR aligned? If so try to combine with next.
909 bool AlignedDest = ((DestSubReg - AMDGPU::SGPR0) % 2) == 0;
910 bool AlignedSrc = ((SrcSubReg - AMDGPU::SGPR0) % 2) == 0;
911 if (AlignedDest && AlignedSrc && (Idx + 1 < BaseIndices.size())) {
912 // Can use SGPR64 copy
913 unsigned Channel = RI.getChannelFromSubReg(SubIdx);
914 SubIdx = RI.getSubRegFromChannel(Channel, 2);
915 DestSubReg = RI.getSubReg(DestReg, SubIdx);
916 SrcSubReg = RI.getSubReg(SrcReg, SubIdx);
917 assert(DestSubReg && SrcSubReg && "Failed to find subregs!");
918 Opcode = AMDGPU::S_MOV_B64;
919 Idx++;
920 }
921
922 LastMI = BuildMI(MBB, I, DL, TII.get(Opcode), DestSubReg)
923 .addReg(SrcSubReg)
924 .addReg(SrcReg, RegState::Implicit);
925
926 if (!FirstMI)
927 FirstMI = LastMI;
928
929 if (!Forward)
930 I--;
931 }
932
933 assert(FirstMI && LastMI);
934 if (!Forward)
935 std::swap(FirstMI, LastMI);
936
937 if (KillSrc)
938 LastMI->addRegisterKilled(SrcReg, &RI);
939}
940
943 const DebugLoc &DL, Register DestReg,
944 Register SrcReg, bool KillSrc, bool RenamableDest,
945 bool RenamableSrc) const {
946 const TargetRegisterClass *RC = RI.getPhysRegBaseClass(DestReg);
947 unsigned Size = RI.getRegSizeInBits(*RC);
948 const TargetRegisterClass *SrcRC = RI.getPhysRegBaseClass(SrcReg);
949 unsigned SrcSize = RI.getRegSizeInBits(*SrcRC);
950
951 // The rest of copyPhysReg assumes Src and Dst size are the same size.
952 // TODO-GFX11_16BIT If all true 16 bit instruction patterns are completed can
953 // we remove fix_16_bit_physreg_copies and this code block?
954 if (ST.getCLOpts().fix_16_bit_physreg_copies) {
955 if (((Size == 16) != (SrcSize == 16))) {
956 // Non-VGPR Src and Dst will later be expanded back to 32 bits.
957 assert(ST.useRealTrue16Insts());
958 Register &RegToFix = (Size == 32) ? DestReg : SrcReg;
959 MCRegister SubReg = RI.getSubReg(RegToFix, AMDGPU::lo16);
960 RegToFix = SubReg;
961
962 if (DestReg == SrcReg) {
963 // Identity copy. Insert empty bundle since ExpandPostRA expects an
964 // instruction here.
965 BuildMI(MBB, MI, DL, get(AMDGPU::BUNDLE));
966 return;
967 }
968 RC = RI.getPhysRegBaseClass(DestReg);
969 Size = RI.getRegSizeInBits(*RC);
970 SrcRC = RI.getPhysRegBaseClass(SrcReg);
971 SrcSize = RI.getRegSizeInBits(*SrcRC);
972 }
973 }
974
975 if (RC == &AMDGPU::VGPR_32RegClass) {
976 assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
977 AMDGPU::SReg_32RegClass.contains(SrcReg) ||
978 AMDGPU::AGPR_32RegClass.contains(SrcReg));
979 unsigned Opc = AMDGPU::AGPR_32RegClass.contains(SrcReg) ?
980 AMDGPU::V_ACCVGPR_READ_B32_e64 : AMDGPU::V_MOV_B32_e32;
981 BuildMI(MBB, MI, DL, get(Opc), DestReg)
982 .addReg(SrcReg, getKillRegState(KillSrc));
983 return;
984 }
985
986 if (RC == &AMDGPU::SReg_32_XM0RegClass ||
987 RC == &AMDGPU::SReg_32RegClass) {
988 if (SrcReg == AMDGPU::SCC) {
989 BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B32), DestReg)
990 .addImm(1)
991 .addImm(0);
992 return;
993 }
994
995 if (!AMDGPU::SReg_32RegClass.contains(SrcReg)) {
996 if (DestReg == AMDGPU::VCC_LO) {
997 // FIXME: Hack until VReg_1 removed.
998 assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
999 BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
1000 .addImm(0)
1001 .addReg(SrcReg, getKillRegState(KillSrc));
1002 return;
1003 }
1004
1005 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
1006 return;
1007 }
1008
1009 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
1010 .addReg(SrcReg, getKillRegState(KillSrc));
1011 return;
1012 }
1013
1014 if (RC == &AMDGPU::SReg_64RegClass) {
1015 if (SrcReg == AMDGPU::SCC) {
1016 BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B64), DestReg)
1017 .addImm(1)
1018 .addImm(0);
1019 return;
1020 }
1021
1022 if (!AMDGPU::SReg_64_EncodableRegClass.contains(SrcReg)) {
1023 if (DestReg == AMDGPU::VCC) {
1024 // FIXME: Hack until VReg_1 removed.
1025 assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
1026 BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
1027 .addImm(0)
1028 .addReg(SrcReg, getKillRegState(KillSrc));
1029 return;
1030 }
1031
1032 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
1033 return;
1034 }
1035
1036 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
1037 .addReg(SrcReg, getKillRegState(KillSrc));
1038 return;
1039 }
1040
1041 if (DestReg == AMDGPU::SCC) {
1042 // Copying 64-bit or 32-bit sources to SCC barely makes sense,
1043 // but SelectionDAG emits such copies for i1 sources.
1044 if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
1045 // This copy can only be produced by patterns
1046 // with explicit SCC, which are known to be enabled
1047 // only for subtargets with S_CMP_LG_U64 present.
1048 assert(ST.hasScalarCompareEq64());
1049 BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U64))
1050 .addReg(SrcReg, getKillRegState(KillSrc))
1051 .addImm(0);
1052 } else {
1053 assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
1054 BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32))
1055 .addReg(SrcReg, getKillRegState(KillSrc))
1056 .addImm(0);
1057 }
1058
1059 return;
1060 }
1061
1062 if (RC == &AMDGPU::AGPR_32RegClass) {
1063 if (AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
1064 (ST.hasGFX90AInsts() && AMDGPU::SReg_32RegClass.contains(SrcReg))) {
1065 BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
1066 .addReg(SrcReg, getKillRegState(KillSrc));
1067 return;
1068 }
1069
1070 if (AMDGPU::AGPR_32RegClass.contains(SrcReg) && ST.hasGFX90AInsts()) {
1071 BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_MOV_B32), DestReg)
1072 .addReg(SrcReg, getKillRegState(KillSrc));
1073 return;
1074 }
1075
1076 // FIXME: Pass should maintain scavenger to avoid scan through the block on
1077 // every AGPR spill.
1078 RegScavenger RS;
1079 const bool Overlap = RI.regsOverlap(SrcReg, DestReg);
1080 indirectCopyToAGPR(*this, MBB, MI, DL, DestReg, SrcReg, KillSrc, RS, Overlap);
1081 return;
1082 }
1083
1084 if (Size == 16) {
1085 assert(AMDGPU::VGPR_16RegClass.contains(SrcReg) ||
1086 AMDGPU::SReg_LO16RegClass.contains(SrcReg) ||
1087 AMDGPU::AGPR_LO16RegClass.contains(SrcReg));
1088
1089 bool IsSGPRDst = AMDGPU::SReg_LO16RegClass.contains(DestReg);
1090 bool IsSGPRSrc = AMDGPU::SReg_LO16RegClass.contains(SrcReg);
1091 bool IsAGPRDst = AMDGPU::AGPR_LO16RegClass.contains(DestReg);
1092 bool IsAGPRSrc = AMDGPU::AGPR_LO16RegClass.contains(SrcReg);
1093 bool DstLow = !AMDGPU::isHi16Reg(DestReg, RI);
1094 bool SrcLow = !AMDGPU::isHi16Reg(SrcReg, RI);
1095 MCRegister NewDestReg = RI.get32BitRegister(DestReg);
1096 MCRegister NewSrcReg = RI.get32BitRegister(SrcReg);
1097
1098 if (IsSGPRDst) {
1099 if (!IsSGPRSrc) {
1100 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
1101 return;
1102 }
1103
1104 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), NewDestReg)
1105 .addReg(NewSrcReg, getKillRegState(KillSrc));
1106 return;
1107 }
1108
1109 if (IsAGPRDst || IsAGPRSrc) {
1110 if (!DstLow || !SrcLow) {
1111 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc,
1112 "Cannot use hi16 subreg with an AGPR!");
1113 }
1114
1115 copyPhysReg(MBB, MI, DL, NewDestReg, NewSrcReg, KillSrc);
1116 return;
1117 }
1118
1119 if (ST.useRealTrue16Insts()) {
1120 if (IsSGPRSrc) {
1121 assert(SrcLow);
1122 SrcReg = NewSrcReg;
1123 }
1124 // Use the smaller instruction encoding if possible.
1125 if (AMDGPU::VGPR_16_Lo128RegClass.contains(DestReg) &&
1126 (IsSGPRSrc || AMDGPU::VGPR_16_Lo128RegClass.contains(SrcReg))) {
1127 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B16_t16_e32), DestReg)
1128 .addReg(SrcReg);
1129 } else {
1130 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B16_t16_e64), DestReg)
1131 .addImm(0) // src0_modifiers
1132 .addReg(SrcReg)
1133 .addImm(0); // op_sel
1134 }
1135 return;
1136 }
1137
1138 if (IsSGPRSrc && !ST.hasSDWAScalar()) {
1139 if (!DstLow || !SrcLow) {
1140 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc,
1141 "Cannot use hi16 subreg on VI!");
1142 }
1143
1144 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), NewDestReg)
1145 .addReg(NewSrcReg, getKillRegState(KillSrc));
1146 return;
1147 }
1148
1149 auto MIB = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_sdwa), NewDestReg)
1150 .addImm(0) // src0_modifiers
1151 .addReg(NewSrcReg)
1152 .addImm(0) // clamp
1159 // First implicit operand is $exec.
1160 MIB->tieOperands(0, MIB->getNumOperands() - 1);
1161 return;
1162 }
1163
1164 // Returns true if Dst and Src are in Opc's HwMode-resolved destination and
1165 // source operand classes.
1166 auto CanCopyWith = [&](unsigned Opc, MCRegister Dst, MCRegister Src,
1167 unsigned SrcOp = 1) {
1168 const MCInstrDesc &Desc = get(Opc);
1169 const TargetRegisterClass *DstOpRC = getRegClass(Desc, 0);
1170 const TargetRegisterClass *SrcOpRC = getRegClass(Desc, SrcOp);
1171 return DstOpRC && SrcOpRC && DstOpRC->contains(Dst) &&
1172 SrcOpRC->contains(Src);
1173 };
1174
1175 if (RC == RI.getVGPR64Class() && (SrcRC == RC || RI.isSGPRClass(SrcRC))) {
1176 if (ST.hasVMovB64Inst() &&
1177 CanCopyWith(AMDGPU::V_MOV_B64_e32, DestReg, SrcReg)) {
1178 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_e32), DestReg)
1179 .addReg(SrcReg, getKillRegState(KillSrc));
1180 return;
1181 }
1182 if (ST.hasPkMovB32() &&
1183 CanCopyWith(AMDGPU::V_PK_MOV_B32, DestReg, SrcReg, /*SrcOp=*/2)) {
1184 BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), DestReg)
1186 .addReg(SrcReg)
1188 .addReg(SrcReg)
1189 .addImm(0) // op_sel_lo
1190 .addImm(0) // op_sel_hi
1191 .addImm(0) // neg_lo
1192 .addImm(0) // neg_hi
1193 .addImm(0) // clamp
1194 .addReg(SrcReg, getKillRegState(KillSrc) | RegState::Implicit);
1195 return;
1196 }
1197 }
1198
1199 const bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
1200 if (RI.isSGPRClass(RC)) {
1201 if (!RI.isSGPRClass(SrcRC)) {
1202 reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
1203 return;
1204 }
1205 const bool CanKillSuperReg = KillSrc && !RI.regsOverlap(SrcReg, DestReg);
1206 expandSGPRCopy(*this, MBB, MI, DL, DestReg, SrcReg, CanKillSuperReg, RC,
1207 Forward);
1208 return;
1209 }
1210
1211 unsigned Opcode = AMDGPU::V_MOV_B32_e32;
1212 unsigned WideOpcode = AMDGPU::INSTRUCTION_LIST_END;
1213 if (RI.isAGPRClass(RC)) {
1214 if (ST.hasGFX90AInsts() && RI.isAGPRClass(SrcRC))
1215 Opcode = AMDGPU::V_ACCVGPR_MOV_B32;
1216 else if (RI.hasVGPRs(SrcRC) ||
1217 (ST.hasGFX90AInsts() && RI.isSGPRClass(SrcRC)))
1218 Opcode = AMDGPU::V_ACCVGPR_WRITE_B32_e64;
1219 else
1220 Opcode = AMDGPU::INSTRUCTION_LIST_END;
1221 } else if (RI.hasVGPRs(RC) && RI.isAGPRClass(SrcRC)) {
1222 Opcode = AMDGPU::V_ACCVGPR_READ_B32_e64;
1223 } else if (RI.isVGPRClass(RC)) {
1224 if (ST.hasVMovB64Inst())
1225 WideOpcode = AMDGPU::V_MOV_B64_e32;
1226 else if (ST.hasPkMovB32())
1227 WideOpcode = AMDGPU::V_PK_MOV_B32;
1228 }
1229
1230 const TargetRegisterClass *WideDstRC{}, *WideSrcRC{};
1231 if (WideOpcode != AMDGPU::INSTRUCTION_LIST_END) {
1232 const MCInstrDesc &Desc = get(WideOpcode);
1233 unsigned SrcOp = WideOpcode == AMDGPU::V_PK_MOV_B32 ? 2 : 1;
1234 WideDstRC = getRegClass(Desc, 0);
1235 WideSrcRC = getRegClass(Desc, SrcOp);
1236 }
1237
1238 // If there is an overlap, we can't kill the super-register on the last
1239 // instruction, since it will also kill the components made live by this def.
1240 const bool Overlap = RI.regsOverlap(SrcReg, DestReg);
1241 const bool CanKillSuperReg = KillSrc && !Overlap;
1242
1243 // For the cases where we need an intermediate instruction/temporary register
1244 // (destination is an AGPR), we need a scavenger.
1245 //
1246 // FIXME: The pass should maintain this for us so we don't have to re-scan the
1247 // whole block for every handled copy.
1248 std::unique_ptr<RegScavenger> RS;
1249 if (Opcode == AMDGPU::INSTRUCTION_LIST_END)
1250 RS = std::make_unique<RegScavenger>();
1251
1252 ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RC, 4);
1253
1254 for (unsigned Idx{}; Idx < SubIndices.size();) {
1255 unsigned NumRegs = 1;
1256 unsigned ThisOpcode = Opcode;
1257 unsigned SubIdx =
1258 Forward ? SubIndices[Idx] : SubIndices[SubIndices.size() - Idx - 1];
1259
1260 if (WideDstRC && WideSrcRC && Idx + 1 < SubIndices.size()) {
1261 unsigned Channel = RI.getChannelFromSubReg(SubIdx);
1262 if (!Forward)
1263 --Channel;
1264
1265 unsigned WideSubIdx = RI.getSubRegFromChannel(Channel, 2);
1266 Register WideDst = RI.getSubReg(DestReg, WideSubIdx);
1267 Register WideSrc = RI.getSubReg(SrcReg, WideSubIdx);
1268
1269 if (WideDst && WideSrc && WideDstRC->contains(WideDst) &&
1270 WideSrcRC->contains(WideSrc)) {
1271 SubIdx = WideSubIdx;
1272 NumRegs = 2;
1273 ThisOpcode = WideOpcode;
1274 }
1275 }
1276
1277 Register DestSubReg = RI.getSubReg(DestReg, SubIdx);
1278 Register SrcSubReg = RI.getSubReg(SrcReg, SubIdx);
1279 assert(DestSubReg && SrcSubReg && "Failed to find subregs!");
1280
1281 Idx += NumRegs;
1282 bool UseKill = CanKillSuperReg && Idx == SubIndices.size();
1283
1284 if (ThisOpcode == AMDGPU::INSTRUCTION_LIST_END) {
1285 Register ImpUseSuper = SrcReg;
1286 indirectCopyToAGPR(*this, MBB, MI, DL, DestSubReg, SrcSubReg, UseKill,
1287 *RS, Overlap, ImpUseSuper);
1288 } else if (ThisOpcode == AMDGPU::V_PK_MOV_B32) {
1289 BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), DestSubReg)
1291 .addReg(SrcSubReg)
1293 .addReg(SrcSubReg)
1294 .addImm(0) // op_sel_lo
1295 .addImm(0) // op_sel_hi
1296 .addImm(0) // neg_lo
1297 .addImm(0) // neg_hi
1298 .addImm(0) // clamp
1299 .addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
1300 } else {
1301 MachineInstrBuilder Builder =
1302 BuildMI(MBB, MI, DL, get(ThisOpcode), DestSubReg).addReg(SrcSubReg);
1303
1304 Builder.addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
1305 }
1306 }
1307}
1308
1309int SIInstrInfo::commuteOpcode(unsigned Opcode) const {
1310 int32_t NewOpc;
1311
1312 // Try to map original to commuted opcode
1313 NewOpc = AMDGPU::getCommuteRev(Opcode);
1314 if (NewOpc != -1)
1315 // Check if the commuted (REV) opcode exists on the target.
1316 return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
1317
1318 // Try to map commuted to original opcode
1319 NewOpc = AMDGPU::getCommuteOrig(Opcode);
1320 if (NewOpc != -1)
1321 // Check if the original (non-REV) opcode exists on the target.
1322 return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
1323
1324 return Opcode;
1325}
1326
1328 const Register Reg,
1329 int64_t &ImmVal) const {
1330 switch (MI.getOpcode()) {
1331 case AMDGPU::V_MOV_B32_e32:
1332 case AMDGPU::S_MOV_B32:
1333 case AMDGPU::S_MOVK_I32:
1334 case AMDGPU::S_MOV_B64:
1335 case AMDGPU::V_MOV_B64_e32:
1336 case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
1337 case AMDGPU::AV_MOV_B32_IMM_PSEUDO:
1338 case AMDGPU::AV_MOV_B64_IMM_PSEUDO:
1339 case AMDGPU::S_MOV_B64_IMM_PSEUDO:
1340 case AMDGPU::V_MOV_B64_PSEUDO:
1341 case AMDGPU::V_MOV_B16_t16_e32: {
1342 const MachineOperand &Src0 = MI.getOperand(1);
1343 if (Src0.isImm()) {
1344 ImmVal = Src0.getImm();
1345 return MI.getOperand(0).getReg() == Reg;
1346 }
1347
1348 return false;
1349 }
1350 case AMDGPU::V_MOV_B16_t16_e64: {
1351 const MachineOperand &Src0 = MI.getOperand(2);
1352 if (Src0.isImm() && !MI.getOperand(1).getImm()) {
1353 ImmVal = Src0.getImm();
1354 return MI.getOperand(0).getReg() == Reg;
1355 }
1356
1357 return false;
1358 }
1359 case AMDGPU::S_BREV_B32:
1360 case AMDGPU::V_BFREV_B32_e32:
1361 case AMDGPU::V_BFREV_B32_e64: {
1362 const MachineOperand &Src0 = MI.getOperand(1);
1363 if (Src0.isImm()) {
1364 ImmVal = static_cast<int64_t>(reverseBits<int32_t>(Src0.getImm()));
1365 return MI.getOperand(0).getReg() == Reg;
1366 }
1367
1368 return false;
1369 }
1370 case AMDGPU::S_NOT_B32:
1371 case AMDGPU::V_NOT_B32_e32:
1372 case AMDGPU::V_NOT_B32_e64: {
1373 const MachineOperand &Src0 = MI.getOperand(1);
1374 if (Src0.isImm()) {
1375 ImmVal = static_cast<int64_t>(~static_cast<int32_t>(Src0.getImm()));
1376 return MI.getOperand(0).getReg() == Reg;
1377 }
1378
1379 return false;
1380 }
1381 default:
1382 return false;
1383 }
1384}
1385
1386std::optional<int64_t>
1388 const MachineOperand &Op,
1389 MachineInstr **DefMI) const {
1390 if (DefMI)
1391 *DefMI = nullptr;
1392
1393 if (Op.isImm())
1394 return Op.getImm();
1395
1396 if (!Op.isReg() || !Op.getReg().isVirtual())
1397 return std::nullopt;
1398 MachineInstr *Def = MRI.getUniqueVRegDef(Op.getReg());
1399 if (Def && Def->isMoveImmediate()) {
1400 const MachineOperand &ImmSrc = Def->getOperand(1);
1401 if (ImmSrc.isImm()) {
1402 if (DefMI)
1403 *DefMI = Def;
1404 return extractSubregFromImm(ImmSrc.getImm(), Op.getSubReg());
1405 }
1406 }
1407
1408 return std::nullopt;
1409}
1410
1411std::optional<int64_t>
1417
1419
1420 if (RI.isAGPRClass(DstRC))
1421 return AMDGPU::COPY;
1422 if (RI.getRegSizeInBits(*DstRC) == 16) {
1423 // Assume hi bits are unneeded. Only _e64 true16 instructions are legal
1424 // before RA.
1425 return RI.isSGPRClass(DstRC) ? AMDGPU::COPY : AMDGPU::V_MOV_B16_t16_e64;
1426 }
1427 if (RI.getRegSizeInBits(*DstRC) == 32)
1428 return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1429 if (RI.getRegSizeInBits(*DstRC) == 64 && RI.isSGPRClass(DstRC))
1430 return AMDGPU::S_MOV_B64;
1431 if (RI.getRegSizeInBits(*DstRC) == 64 && !RI.isSGPRClass(DstRC))
1432 return AMDGPU::V_MOV_B64_PSEUDO;
1433 return AMDGPU::COPY;
1434}
1435
1436const MCInstrDesc &
1438 bool IsIndirectSrc) const {
1439 if (IsIndirectSrc) {
1440 if (VecSize <= 32) // 4 bytes
1441 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V1);
1442 if (VecSize <= 64) // 8 bytes
1443 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V2);
1444 if (VecSize <= 96) // 12 bytes
1445 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V3);
1446 if (VecSize <= 128) // 16 bytes
1447 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V4);
1448 if (VecSize <= 160) // 20 bytes
1449 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V5);
1450 if (VecSize <= 192) // 24 bytes
1451 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V6);
1452 if (VecSize <= 224) // 28 bytes
1453 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V7);
1454 if (VecSize <= 256) // 32 bytes
1455 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V8);
1456 if (VecSize <= 288) // 36 bytes
1457 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V9);
1458 if (VecSize <= 320) // 40 bytes
1459 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V10);
1460 if (VecSize <= 352) // 44 bytes
1461 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V11);
1462 if (VecSize <= 384) // 48 bytes
1463 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V12);
1464 if (VecSize <= 512) // 64 bytes
1465 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V16);
1466 if (VecSize <= 1024) // 128 bytes
1467 return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V32);
1468
1469 llvm_unreachable("unsupported size for IndirectRegReadGPRIDX pseudos");
1470 }
1471
1472 if (VecSize <= 32) // 4 bytes
1473 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V1);
1474 if (VecSize <= 64) // 8 bytes
1475 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V2);
1476 if (VecSize <= 96) // 12 bytes
1477 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V3);
1478 if (VecSize <= 128) // 16 bytes
1479 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V4);
1480 if (VecSize <= 160) // 20 bytes
1481 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V5);
1482 if (VecSize <= 192) // 24 bytes
1483 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V6);
1484 if (VecSize <= 224) // 28 bytes
1485 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V7);
1486 if (VecSize <= 256) // 32 bytes
1487 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V8);
1488 if (VecSize <= 288) // 36 bytes
1489 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V9);
1490 if (VecSize <= 320) // 40 bytes
1491 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V10);
1492 if (VecSize <= 352) // 44 bytes
1493 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V11);
1494 if (VecSize <= 384) // 48 bytes
1495 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V12);
1496 if (VecSize <= 512) // 64 bytes
1497 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V16);
1498 if (VecSize <= 1024) // 128 bytes
1499 return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V32);
1500
1501 llvm_unreachable("unsupported size for IndirectRegWriteGPRIDX pseudos");
1502}
1503
1504static unsigned getIndirectVGPRWriteMovRelPseudoOpc(unsigned VecSize) {
1505 if (VecSize <= 32) // 4 bytes
1506 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V1;
1507 if (VecSize <= 64) // 8 bytes
1508 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V2;
1509 if (VecSize <= 96) // 12 bytes
1510 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V3;
1511 if (VecSize <= 128) // 16 bytes
1512 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V4;
1513 if (VecSize <= 160) // 20 bytes
1514 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V5;
1515 if (VecSize <= 192) // 24 bytes
1516 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V6;
1517 if (VecSize <= 224) // 28 bytes
1518 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V7;
1519 if (VecSize <= 256) // 32 bytes
1520 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V8;
1521 if (VecSize <= 288) // 36 bytes
1522 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V9;
1523 if (VecSize <= 320) // 40 bytes
1524 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V10;
1525 if (VecSize <= 352) // 44 bytes
1526 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V11;
1527 if (VecSize <= 384) // 48 bytes
1528 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V12;
1529 if (VecSize <= 512) // 64 bytes
1530 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V16;
1531 if (VecSize <= 1024) // 128 bytes
1532 return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V32;
1533
1534 llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1535}
1536
1537static unsigned getIndirectSGPRWriteMovRelPseudo32(unsigned VecSize) {
1538 if (VecSize <= 32) // 4 bytes
1539 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V1;
1540 if (VecSize <= 64) // 8 bytes
1541 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V2;
1542 if (VecSize <= 96) // 12 bytes
1543 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V3;
1544 if (VecSize <= 128) // 16 bytes
1545 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V4;
1546 if (VecSize <= 160) // 20 bytes
1547 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V5;
1548 if (VecSize <= 192) // 24 bytes
1549 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V6;
1550 if (VecSize <= 224) // 28 bytes
1551 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V7;
1552 if (VecSize <= 256) // 32 bytes
1553 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V8;
1554 if (VecSize <= 288) // 36 bytes
1555 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V9;
1556 if (VecSize <= 320) // 40 bytes
1557 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V10;
1558 if (VecSize <= 352) // 44 bytes
1559 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V11;
1560 if (VecSize <= 384) // 48 bytes
1561 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V12;
1562 if (VecSize <= 512) // 64 bytes
1563 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V16;
1564 if (VecSize <= 1024) // 128 bytes
1565 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V32;
1566
1567 llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1568}
1569
1570static unsigned getIndirectSGPRWriteMovRelPseudo64(unsigned VecSize) {
1571 if (VecSize <= 64) // 8 bytes
1572 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V1;
1573 if (VecSize <= 128) // 16 bytes
1574 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V2;
1575 if (VecSize <= 256) // 32 bytes
1576 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V4;
1577 if (VecSize <= 512) // 64 bytes
1578 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V8;
1579 if (VecSize <= 1024) // 128 bytes
1580 return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V16;
1581
1582 llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1583}
1584
1585const MCInstrDesc &
1586SIInstrInfo::getIndirectRegWriteMovRelPseudo(unsigned VecSize, unsigned EltSize,
1587 bool IsSGPR) const {
1588 if (IsSGPR) {
1589 switch (EltSize) {
1590 case 32:
1591 return get(getIndirectSGPRWriteMovRelPseudo32(VecSize));
1592 case 64:
1593 return get(getIndirectSGPRWriteMovRelPseudo64(VecSize));
1594 default:
1595 llvm_unreachable("invalid reg indexing elt size");
1596 }
1597 }
1598
1599 assert(EltSize == 32 && "invalid reg indexing elt size");
1601}
1602
1603static unsigned getSGPRSpillSaveOpcode(unsigned Size, bool NeedsCFI) {
1604 switch (Size) {
1605 case 4:
1606 return NeedsCFI ? AMDGPU::SI_SPILL_S32_CFI_SAVE : AMDGPU::SI_SPILL_S32_SAVE;
1607 case 8:
1608 return NeedsCFI ? AMDGPU::SI_SPILL_S64_CFI_SAVE : AMDGPU::SI_SPILL_S64_SAVE;
1609 case 12:
1610 return NeedsCFI ? AMDGPU::SI_SPILL_S96_CFI_SAVE : AMDGPU::SI_SPILL_S96_SAVE;
1611 case 16:
1612 return NeedsCFI ? AMDGPU::SI_SPILL_S128_CFI_SAVE
1613 : AMDGPU::SI_SPILL_S128_SAVE;
1614 case 20:
1615 return NeedsCFI ? AMDGPU::SI_SPILL_S160_CFI_SAVE
1616 : AMDGPU::SI_SPILL_S160_SAVE;
1617 case 24:
1618 return NeedsCFI ? AMDGPU::SI_SPILL_S192_CFI_SAVE
1619 : AMDGPU::SI_SPILL_S192_SAVE;
1620 case 28:
1621 return NeedsCFI ? AMDGPU::SI_SPILL_S224_CFI_SAVE
1622 : AMDGPU::SI_SPILL_S224_SAVE;
1623 case 32:
1624 return AMDGPU::SI_SPILL_S256_SAVE;
1625 case 36:
1626 return AMDGPU::SI_SPILL_S288_SAVE;
1627 case 40:
1628 return AMDGPU::SI_SPILL_S320_SAVE;
1629 case 44:
1630 return AMDGPU::SI_SPILL_S352_SAVE;
1631 case 48:
1632 return AMDGPU::SI_SPILL_S384_SAVE;
1633 case 64:
1634 return NeedsCFI ? AMDGPU::SI_SPILL_S512_CFI_SAVE
1635 : AMDGPU::SI_SPILL_S512_SAVE;
1636 case 128:
1637 return NeedsCFI ? AMDGPU::SI_SPILL_S1024_CFI_SAVE
1638 : AMDGPU::SI_SPILL_S1024_SAVE;
1639 default:
1640 llvm_unreachable("unknown register size");
1641 }
1642}
1643
1644static unsigned getVGPRSpillSaveOpcode(unsigned Size, bool NeedsCFI) {
1645 switch (Size) {
1646 case 2:
1647 return AMDGPU::SI_SPILL_V16_SAVE;
1648 case 4:
1649 return NeedsCFI ? AMDGPU::SI_SPILL_V32_CFI_SAVE : AMDGPU::SI_SPILL_V32_SAVE;
1650 case 8:
1651 return NeedsCFI ? AMDGPU::SI_SPILL_V64_CFI_SAVE : AMDGPU::SI_SPILL_V64_SAVE;
1652 case 12:
1653 return NeedsCFI ? AMDGPU::SI_SPILL_V96_CFI_SAVE : AMDGPU::SI_SPILL_V96_SAVE;
1654 case 16:
1655 return NeedsCFI ? AMDGPU::SI_SPILL_V128_CFI_SAVE
1656 : AMDGPU::SI_SPILL_V128_SAVE;
1657 case 20:
1658 return NeedsCFI ? AMDGPU::SI_SPILL_V160_CFI_SAVE
1659 : AMDGPU::SI_SPILL_V160_SAVE;
1660 case 24:
1661 return NeedsCFI ? AMDGPU::SI_SPILL_V192_CFI_SAVE
1662 : AMDGPU::SI_SPILL_V192_SAVE;
1663 case 28:
1664 return NeedsCFI ? AMDGPU::SI_SPILL_V224_CFI_SAVE
1665 : AMDGPU::SI_SPILL_V224_SAVE;
1666 case 32:
1667 return NeedsCFI ? AMDGPU::SI_SPILL_V256_CFI_SAVE
1668 : AMDGPU::SI_SPILL_V256_SAVE;
1669 case 36:
1670 return NeedsCFI ? AMDGPU::SI_SPILL_V288_CFI_SAVE
1671 : AMDGPU::SI_SPILL_V288_SAVE;
1672 case 40:
1673 return NeedsCFI ? AMDGPU::SI_SPILL_V320_CFI_SAVE
1674 : AMDGPU::SI_SPILL_V320_SAVE;
1675 case 44:
1676 return NeedsCFI ? AMDGPU::SI_SPILL_V352_CFI_SAVE
1677 : AMDGPU::SI_SPILL_V352_SAVE;
1678 case 48:
1679 return NeedsCFI ? AMDGPU::SI_SPILL_V384_CFI_SAVE
1680 : AMDGPU::SI_SPILL_V384_SAVE;
1681 case 64:
1682 return NeedsCFI ? AMDGPU::SI_SPILL_V512_CFI_SAVE
1683 : AMDGPU::SI_SPILL_V512_SAVE;
1684 case 128:
1685 return NeedsCFI ? AMDGPU::SI_SPILL_V1024_CFI_SAVE
1686 : AMDGPU::SI_SPILL_V1024_SAVE;
1687 default:
1688 llvm_unreachable("unknown register size");
1689 }
1690}
1691
1692static unsigned getAVSpillSaveOpcode(unsigned Size, bool NeedsCFI) {
1693 switch (Size) {
1694 case 4:
1695 return NeedsCFI ? AMDGPU::SI_SPILL_AV32_CFI_SAVE
1696 : AMDGPU::SI_SPILL_AV32_SAVE;
1697 case 8:
1698 return NeedsCFI ? AMDGPU::SI_SPILL_AV64_CFI_SAVE
1699 : AMDGPU::SI_SPILL_AV64_SAVE;
1700 case 12:
1701 return NeedsCFI ? AMDGPU::SI_SPILL_AV96_CFI_SAVE
1702 : AMDGPU::SI_SPILL_AV96_SAVE;
1703 case 16:
1704 return NeedsCFI ? AMDGPU::SI_SPILL_AV128_CFI_SAVE
1705 : AMDGPU::SI_SPILL_AV128_SAVE;
1706 case 20:
1707 return NeedsCFI ? AMDGPU::SI_SPILL_AV160_CFI_SAVE
1708 : AMDGPU::SI_SPILL_AV160_SAVE;
1709 case 24:
1710 return NeedsCFI ? AMDGPU::SI_SPILL_AV192_CFI_SAVE
1711 : AMDGPU::SI_SPILL_AV192_SAVE;
1712 case 28:
1713 return NeedsCFI ? AMDGPU::SI_SPILL_AV224_CFI_SAVE
1714 : AMDGPU::SI_SPILL_AV224_SAVE;
1715 case 32:
1716 return NeedsCFI ? AMDGPU::SI_SPILL_AV256_CFI_SAVE
1717 : AMDGPU::SI_SPILL_AV256_SAVE;
1718 case 36:
1719 return AMDGPU::SI_SPILL_AV288_SAVE;
1720 case 40:
1721 return AMDGPU::SI_SPILL_AV320_SAVE;
1722 case 44:
1723 return AMDGPU::SI_SPILL_AV352_SAVE;
1724 case 48:
1725 return AMDGPU::SI_SPILL_AV384_SAVE;
1726 case 64:
1727 return NeedsCFI ? AMDGPU::SI_SPILL_AV512_CFI_SAVE
1728 : AMDGPU::SI_SPILL_AV512_SAVE;
1729 case 128:
1730 return NeedsCFI ? AMDGPU::SI_SPILL_AV1024_CFI_SAVE
1731 : AMDGPU::SI_SPILL_AV1024_SAVE;
1732 default:
1733 llvm_unreachable("unknown register size");
1734 }
1735}
1736
1737static unsigned getWWMRegSpillSaveOpcode(unsigned Size,
1738 bool IsVectorSuperClass) {
1739 // Currently, there is only 32-bit WWM register spills needed.
1740 if (Size != 4)
1741 llvm_unreachable("unknown wwm register spill size");
1742
1743 if (IsVectorSuperClass)
1744 return AMDGPU::SI_SPILL_WWM_AV32_SAVE;
1745
1746 return AMDGPU::SI_SPILL_WWM_V32_SAVE;
1747}
1748
1750 Register Reg, const TargetRegisterClass *RC, unsigned Size,
1751 const SIMachineFunctionInfo &MFI, bool NeedsCFI) const {
1752 bool IsVectorSuperClass = RI.isVectorSuperClass(RC);
1753
1754 // Choose the right opcode if spilling a WWM register.
1756 return getWWMRegSpillSaveOpcode(Size, IsVectorSuperClass);
1757
1758 // TODO: Check if AGPRs are available
1759 if (ST.hasMAIInsts())
1760 return getAVSpillSaveOpcode(Size, NeedsCFI);
1761
1762 return getVGPRSpillSaveOpcode(Size, NeedsCFI);
1763}
1764
1765void SIInstrInfo::storeRegToStackSlotImpl(
1767 bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
1768 MachineInstr::MIFlag Flags, bool NeedsCFI) const {
1769 MachineFunction *MF = MBB.getParent();
1771 MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1772 const DebugLoc &DL = MBB.findDebugLoc(MI);
1773
1774 MachinePointerInfo PtrInfo
1775 = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1777 PtrInfo, MachineMemOperand::MOStore, FrameInfo.getObjectSize(FrameIndex),
1778 FrameInfo.getObjectAlign(FrameIndex));
1779 unsigned SpillSize = RI.getSpillSize(*RC);
1780
1782 if (RI.isSGPRClass(RC)) {
1783 if (FrameInfo.getStackID(FrameIndex) == TargetStackID::SGPRSpill)
1784 MFI->setHasSpilledSGPRs();
1785 assert(SrcReg != AMDGPU::M0 && "m0 should not be spilled");
1786 assert(SrcReg != AMDGPU::EXEC_LO && SrcReg != AMDGPU::EXEC_HI &&
1787 SrcReg != AMDGPU::EXEC && "exec should not be spilled");
1788
1789 // We are only allowed to create one new instruction when spilling
1790 // registers, so we need to use pseudo instruction for spilling SGPRs.
1791 const MCInstrDesc &OpDesc =
1792 get(getSGPRSpillSaveOpcode(SpillSize, NeedsCFI));
1793
1794 // The SGPR spill/restore instructions only work on number sgprs, so we need
1795 // to make sure we are using the correct register class.
1796 if (SrcReg.isVirtual() && SpillSize == 4) {
1797 MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
1798 }
1799
1800 BuildMI(MBB, MI, DL, OpDesc)
1801 .addReg(SrcReg, getKillRegState(isKill)) // data
1802 .addFrameIndex(FrameIndex) // addr
1803 .addMemOperand(MMO)
1805
1806 return;
1807 }
1808
1809 unsigned Opcode = getVectorRegSpillSaveOpcode(VReg ? VReg : SrcReg, RC,
1810 SpillSize, *MFI, NeedsCFI);
1811 MFI->setHasSpilledVGPRs();
1812
1813 BuildMI(MBB, MI, DL, get(Opcode))
1814 .addReg(SrcReg, getKillRegState(isKill)) // data
1815 .addFrameIndex(FrameIndex) // addr
1816 .addReg(MFI->getStackPtrOffsetReg()) // scratch_offset
1817 .addImm(0) // offset
1818 .addMemOperand(MMO);
1819}
1820
1823 bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
1824 MachineInstr::MIFlag Flags) const {
1825 storeRegToStackSlotImpl(MBB, MI, SrcReg, isKill, FrameIndex, RC, VReg, Flags,
1826 false);
1827}
1828
1831 Register SrcReg, bool isKill,
1832 int FrameIndex,
1833 const TargetRegisterClass *RC) const {
1834 storeRegToStackSlotImpl(MBB, MI, SrcReg, isKill, FrameIndex, RC, Register(),
1835 MachineInstr::NoFlags, true);
1836}
1837
1838static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
1839 switch (Size) {
1840 case 4:
1841 return AMDGPU::SI_SPILL_S32_RESTORE;
1842 case 8:
1843 return AMDGPU::SI_SPILL_S64_RESTORE;
1844 case 12:
1845 return AMDGPU::SI_SPILL_S96_RESTORE;
1846 case 16:
1847 return AMDGPU::SI_SPILL_S128_RESTORE;
1848 case 20:
1849 return AMDGPU::SI_SPILL_S160_RESTORE;
1850 case 24:
1851 return AMDGPU::SI_SPILL_S192_RESTORE;
1852 case 28:
1853 return AMDGPU::SI_SPILL_S224_RESTORE;
1854 case 32:
1855 return AMDGPU::SI_SPILL_S256_RESTORE;
1856 case 36:
1857 return AMDGPU::SI_SPILL_S288_RESTORE;
1858 case 40:
1859 return AMDGPU::SI_SPILL_S320_RESTORE;
1860 case 44:
1861 return AMDGPU::SI_SPILL_S352_RESTORE;
1862 case 48:
1863 return AMDGPU::SI_SPILL_S384_RESTORE;
1864 case 64:
1865 return AMDGPU::SI_SPILL_S512_RESTORE;
1866 case 128:
1867 return AMDGPU::SI_SPILL_S1024_RESTORE;
1868 default:
1869 llvm_unreachable("unknown register size");
1870 }
1871}
1872
1873static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
1874 switch (Size) {
1875 case 2:
1876 return AMDGPU::SI_SPILL_V16_RESTORE;
1877 case 4:
1878 return AMDGPU::SI_SPILL_V32_RESTORE;
1879 case 8:
1880 return AMDGPU::SI_SPILL_V64_RESTORE;
1881 case 12:
1882 return AMDGPU::SI_SPILL_V96_RESTORE;
1883 case 16:
1884 return AMDGPU::SI_SPILL_V128_RESTORE;
1885 case 20:
1886 return AMDGPU::SI_SPILL_V160_RESTORE;
1887 case 24:
1888 return AMDGPU::SI_SPILL_V192_RESTORE;
1889 case 28:
1890 return AMDGPU::SI_SPILL_V224_RESTORE;
1891 case 32:
1892 return AMDGPU::SI_SPILL_V256_RESTORE;
1893 case 36:
1894 return AMDGPU::SI_SPILL_V288_RESTORE;
1895 case 40:
1896 return AMDGPU::SI_SPILL_V320_RESTORE;
1897 case 44:
1898 return AMDGPU::SI_SPILL_V352_RESTORE;
1899 case 48:
1900 return AMDGPU::SI_SPILL_V384_RESTORE;
1901 case 64:
1902 return AMDGPU::SI_SPILL_V512_RESTORE;
1903 case 128:
1904 return AMDGPU::SI_SPILL_V1024_RESTORE;
1905 default:
1906 llvm_unreachable("unknown register size");
1907 }
1908}
1909
1910static unsigned getAVSpillRestoreOpcode(unsigned Size) {
1911 switch (Size) {
1912 case 4:
1913 return AMDGPU::SI_SPILL_AV32_RESTORE;
1914 case 8:
1915 return AMDGPU::SI_SPILL_AV64_RESTORE;
1916 case 12:
1917 return AMDGPU::SI_SPILL_AV96_RESTORE;
1918 case 16:
1919 return AMDGPU::SI_SPILL_AV128_RESTORE;
1920 case 20:
1921 return AMDGPU::SI_SPILL_AV160_RESTORE;
1922 case 24:
1923 return AMDGPU::SI_SPILL_AV192_RESTORE;
1924 case 28:
1925 return AMDGPU::SI_SPILL_AV224_RESTORE;
1926 case 32:
1927 return AMDGPU::SI_SPILL_AV256_RESTORE;
1928 case 36:
1929 return AMDGPU::SI_SPILL_AV288_RESTORE;
1930 case 40:
1931 return AMDGPU::SI_SPILL_AV320_RESTORE;
1932 case 44:
1933 return AMDGPU::SI_SPILL_AV352_RESTORE;
1934 case 48:
1935 return AMDGPU::SI_SPILL_AV384_RESTORE;
1936 case 64:
1937 return AMDGPU::SI_SPILL_AV512_RESTORE;
1938 case 128:
1939 return AMDGPU::SI_SPILL_AV1024_RESTORE;
1940 default:
1941 llvm_unreachable("unknown register size");
1942 }
1943}
1944
1945static unsigned getWWMRegSpillRestoreOpcode(unsigned Size,
1946 bool IsVectorSuperClass) {
1947 // Currently, there is only 32-bit WWM register spills needed.
1948 if (Size != 4)
1949 llvm_unreachable("unknown wwm register spill size");
1950
1951 if (IsVectorSuperClass) // TODO: Always use this if there are AGPRs
1952 return AMDGPU::SI_SPILL_WWM_AV32_RESTORE;
1953
1954 return AMDGPU::SI_SPILL_WWM_V32_RESTORE;
1955}
1956
1958 Register Reg, const TargetRegisterClass *RC, unsigned Size,
1959 const SIMachineFunctionInfo &MFI) const {
1960 bool IsVectorSuperClass = RI.isVectorSuperClass(RC);
1961
1962 // Choose the right opcode if restoring a WWM register.
1964 return getWWMRegSpillRestoreOpcode(Size, IsVectorSuperClass);
1965
1966 // TODO: Check if AGPRs are available
1967 if (ST.hasMAIInsts())
1969
1970 assert(!RI.isAGPRClass(RC));
1972}
1973
1976 Register DestReg, int FrameIndex,
1977 const TargetRegisterClass *RC,
1978 Register VReg, unsigned SubReg,
1979 MachineInstr::MIFlag Flags) const {
1980 MachineFunction *MF = MBB.getParent();
1982 MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1983 const DebugLoc &DL = MBB.findDebugLoc(MI);
1984 unsigned SpillSize = RI.getSpillSize(*RC);
1985
1986 MachinePointerInfo PtrInfo
1987 = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1988
1990 PtrInfo, MachineMemOperand::MOLoad, FrameInfo.getObjectSize(FrameIndex),
1991 FrameInfo.getObjectAlign(FrameIndex));
1992
1993 if (RI.isSGPRClass(RC)) {
1994 if (FrameInfo.getStackID(FrameIndex) == TargetStackID::SGPRSpill)
1995 MFI->setHasSpilledSGPRs();
1996 assert(DestReg != AMDGPU::M0 && "m0 should not be reloaded into");
1997 assert(DestReg != AMDGPU::EXEC_LO && DestReg != AMDGPU::EXEC_HI &&
1998 DestReg != AMDGPU::EXEC && "exec should not be spilled");
1999
2000 // FIXME: Maybe this should not include a memoperand because it will be
2001 // lowered to non-memory instructions.
2002 const MCInstrDesc &OpDesc = get(getSGPRSpillRestoreOpcode(SpillSize));
2003 if (DestReg.isVirtual() && SpillSize == 4) {
2005 MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
2006 }
2007
2008 BuildMI(MBB, MI, DL, OpDesc, DestReg)
2009 .addFrameIndex(FrameIndex) // addr
2010 .addMemOperand(MMO)
2012
2013 return;
2014 }
2015
2016 unsigned Opcode = getVectorRegSpillRestoreOpcode(VReg ? VReg : DestReg, RC,
2017 SpillSize, *MFI);
2018 BuildMI(MBB, MI, DL, get(Opcode), DestReg)
2019 .addFrameIndex(FrameIndex) // vaddr
2020 .addReg(MFI->getStackPtrOffsetReg()) // scratch_offset
2021 .addImm(0) // offset
2022 .addMemOperand(MMO);
2023}
2024
2029
2032 unsigned Quantity) const {
2033 DebugLoc DL = MBB.findDebugLoc(MI);
2034 unsigned MaxSNopCount = 1u << ST.getSNopBits();
2035 while (Quantity > 0) {
2036 unsigned Arg = std::min(Quantity, MaxSNopCount);
2037 Quantity -= Arg;
2038 BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP)).addImm(Arg - 1);
2039 }
2040}
2041
2045 const DebugLoc &DL) const {
2046 MachineFunction *MF = MBB.getParent();
2047 constexpr unsigned DoorbellIDMask = 0x3ff;
2048 constexpr unsigned ECQueueWaveAbort = 0x400;
2049
2050 MachineBasicBlock *TrapBB = &MBB;
2051 MachineBasicBlock *HaltLoopBB = MF->CreateMachineBasicBlock();
2052
2053 if (!MBB.succ_empty() ||
2055 /*SkipPseudoOp=*/false) != MBB.end()) {
2056 MBB.splitAt(MI, /*UpdateLiveIns=*/false);
2057 TrapBB = MF->CreateMachineBasicBlock();
2058 BuildMI(MBB, MI, DL, get(AMDGPU::S_CBRANCH_EXECNZ)).addMBB(TrapBB);
2059 MF->push_back(TrapBB);
2060 MBB.addSuccessor(TrapBB);
2061 }
2062 // Start with a `s_trap 2`, if we're in PRIV=1 and we need the workaround this
2063 // will be a nop.
2064 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_TRAP))
2065 .addImm(static_cast<unsigned>(GCNSubtarget::TrapID::LLVMAMDHSATrap));
2066 Register DoorbellReg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
2067 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_SENDMSG_RTN_B32),
2068 DoorbellReg)
2070 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_MOV_B32), AMDGPU::TTMP2)
2071 .addUse(AMDGPU::M0);
2072 Register DoorbellRegMasked =
2073 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
2074 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_AND_B32), DoorbellRegMasked)
2075 .addUse(DoorbellReg)
2076 .addImm(DoorbellIDMask)
2077 .setOperandDead(3); // implicit-def $scc
2078 Register SetWaveAbortBit =
2079 MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
2080 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_OR_B32), SetWaveAbortBit)
2081 .addUse(DoorbellRegMasked)
2082 .addImm(ECQueueWaveAbort)
2083 .setOperandDead(3); // implicit-def $scc
2084 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2085 .addUse(SetWaveAbortBit);
2086 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_SENDMSG))
2088 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2089 .addUse(AMDGPU::TTMP2);
2090 BuildMI(*TrapBB, TrapBB->end(), DL, get(AMDGPU::S_BRANCH)).addMBB(HaltLoopBB);
2091 TrapBB->addSuccessor(HaltLoopBB);
2092
2093 BuildMI(*HaltLoopBB, HaltLoopBB->end(), DL, get(AMDGPU::S_SETHALT)).addImm(5);
2094 BuildMI(*HaltLoopBB, HaltLoopBB->end(), DL, get(AMDGPU::S_BRANCH))
2095 .addMBB(HaltLoopBB);
2096 MF->push_back(HaltLoopBB);
2097 HaltLoopBB->addSuccessor(HaltLoopBB);
2098
2099 return MBB.getNextNode();
2100}
2101
2103 switch (MI.getOpcode()) {
2104 default:
2105 if (MI.isMetaInstruction())
2106 return 0;
2107 return 1; // FIXME: Do wait states equal cycles?
2108
2109 case AMDGPU::S_NOP:
2110 return MI.getOperand(0).getImm() + 1;
2111 // SI_RETURN_TO_EPILOG is a fallthrough to code outside of the function. The
2112 // hazard, even if one exist, won't really be visible. Should we handle it?
2113 }
2114}
2115
2116// Expand a VGPR "as memory" access into one indexed move per dword.
2119 MachineBasicBlock &MBB = *MI.getParent();
2120 MachineFunction &MF = *MBB.getParent();
2121 const DebugLoc &DL = MI.getDebugLoc();
2122 const SIRegisterInfo &RI = TII.getRegisterInfo();
2123 const bool IsStore = LdSt.mayStore();
2124
2125 Register Data = LdSt.getDataOp().getReg();
2126 unsigned Offset = LdSt.getOffsetOp().getImm();
2127 unsigned NumDwords = LdSt.getBitWidth() / 32;
2128
2129 const bool UseGPRIdxMode = LdSt.isGPRIdx();
2130 assert(UseGPRIdxMode == TII.getSubtarget().useVGPRIndexMode());
2131
2132 MachineInstr *SetOn = nullptr;
2133 if (UseGPRIdxMode) {
2134 SetOn = BuildMI(MBB, MI, DL, TII.get(AMDGPU::S_SET_GPR_IDX_ON))
2135 .add(LdSt.getIdxOp())
2138 }
2139
2140 unsigned Opcode;
2141 if (UseGPRIdxMode) {
2142 Opcode = IsStore ? AMDGPU::V_MOV_B32_indirect_write
2143 : AMDGPU::V_MOV_B32_indirect_read;
2144 } else {
2145 Opcode =
2146 IsStore ? AMDGPU::V_MOVRELD_B32_as_mem : AMDGPU::V_MOVRELS_B32_as_mem;
2147 }
2148
2149 // A move touches its base plus the run-time index, which no operand can name,
2150 // so the base is undef and the liveness of those registers is not expressed.
2151 const RegState DataFlags = IsStore
2152 ? getUndefRegState(LdSt.getDataOp().isUndef())
2154 for (unsigned i = 0; i < NumDwords; ++i) {
2155 Register Base = AMDGPU::VGPR_32RegClass.getRegister(Offset + i);
2156 Register Sub = Data;
2157 if (NumDwords != 1)
2158 Sub = RI.getSubReg(Data, RI.getSubRegFromChannel(i));
2159
2161 if (IsStore) {
2162 Move = BuildMI(MBB, MI, DL, TII.get(Opcode))
2164 .addReg(Sub, DataFlags);
2165 // As in copyPhysReg, the implicit use of the whole tuple keeps a partly
2166 // undefined value a valid operand.
2167 if (NumDwords != 1)
2168 Move.addReg(Data, RegState::Implicit | DataFlags);
2169 } else {
2170 Move = BuildMI(MBB, MI, DL, TII.get(Opcode), Sub)
2172 }
2173 // Each mode switch defines M0, which keeps the index-mode moves in order. A
2174 // movrel move only reads M0, so it is a load or store, ordered by the
2175 // memory operand of the dword it moves.
2176 if (!UseGPRIdxMode) {
2177 for (const MachineMemOperand *MMO : MI.memoperands())
2178 Move.addMemOperand(MF.getMachineMemOperand(MMO, 4 * i, 4));
2179 }
2180 }
2181
2182 // Bundled so the post-RA scheduler keeps everything else out of the mode
2183 // switch.
2184 if (SetOn) {
2185 MachineInstr *SetOff =
2186 BuildMI(MBB, MI, DL, TII.get(AMDGPU::S_SET_GPR_IDX_OFF));
2187 finalizeBundle(MBB, SetOn->getIterator(), std::next(SetOff->getIterator()));
2188 }
2189
2190 MI.eraseFromParent();
2191}
2192
2195 expandLoadStoreIdx(*this, MI);
2196 return true;
2197 }
2198
2199 MachineBasicBlock &MBB = *MI.getParent();
2200 DebugLoc DL = MBB.findDebugLoc(MI);
2202
2203 switch (MI.getOpcode()) {
2204 default: return TargetInstrInfo::expandPostRAPseudo(MI);
2205 case AMDGPU::S_MOV_B64_term:
2206 // This is only a terminator to get the correct spill code placement during
2207 // register allocation.
2208 MI.setDesc(get(AMDGPU::S_MOV_B64));
2209 break;
2210
2211 case AMDGPU::S_MOV_B32_term:
2212 // This is only a terminator to get the correct spill code placement during
2213 // register allocation.
2214 MI.setDesc(get(AMDGPU::S_MOV_B32));
2215 break;
2216
2217 case AMDGPU::S_XOR_B64_term:
2218 // This is only a terminator to get the correct spill code placement during
2219 // register allocation.
2220 MI.setDesc(get(AMDGPU::S_XOR_B64));
2221 break;
2222
2223 case AMDGPU::S_XOR_B32_term:
2224 // This is only a terminator to get the correct spill code placement during
2225 // register allocation.
2226 MI.setDesc(get(AMDGPU::S_XOR_B32));
2227 break;
2228 case AMDGPU::S_OR_B64_term:
2229 // This is only a terminator to get the correct spill code placement during
2230 // register allocation.
2231 MI.setDesc(get(AMDGPU::S_OR_B64));
2232 break;
2233 case AMDGPU::S_OR_B32_term:
2234 // This is only a terminator to get the correct spill code placement during
2235 // register allocation.
2236 MI.setDesc(get(AMDGPU::S_OR_B32));
2237 break;
2238
2239 case AMDGPU::S_ANDN2_B64_term:
2240 // This is only a terminator to get the correct spill code placement during
2241 // register allocation.
2242 MI.setDesc(get(AMDGPU::S_ANDN2_B64));
2243 break;
2244
2245 case AMDGPU::S_ANDN2_B32_term:
2246 // This is only a terminator to get the correct spill code placement during
2247 // register allocation.
2248 MI.setDesc(get(AMDGPU::S_ANDN2_B32));
2249 break;
2250
2251 case AMDGPU::S_AND_B64_term:
2252 // This is only a terminator to get the correct spill code placement during
2253 // register allocation.
2254 MI.setDesc(get(AMDGPU::S_AND_B64));
2255 break;
2256
2257 case AMDGPU::S_AND_B32_term:
2258 // This is only a terminator to get the correct spill code placement during
2259 // register allocation.
2260 MI.setDesc(get(AMDGPU::S_AND_B32));
2261 break;
2262
2263 case AMDGPU::S_AND_SAVEEXEC_B64_term:
2264 // This is only a terminator to get the correct spill code placement during
2265 // register allocation.
2266 MI.setDesc(get(AMDGPU::S_AND_SAVEEXEC_B64));
2267 break;
2268
2269 case AMDGPU::S_AND_SAVEEXEC_B32_term:
2270 // This is only a terminator to get the correct spill code placement during
2271 // register allocation.
2272 MI.setDesc(get(AMDGPU::S_AND_SAVEEXEC_B32));
2273 break;
2274
2275 case AMDGPU::V_CMPX_EQ_U32_nosdst_e32_term:
2276 MI.setDesc(get(AMDGPU::V_CMPX_EQ_U32_nosdst_e32));
2277 break;
2278 case AMDGPU::V_CMPX_EQ_U64_nosdst_e32_term:
2279 MI.setDesc(get(AMDGPU::V_CMPX_EQ_U64_nosdst_e32));
2280 break;
2281
2282 case AMDGPU::SI_SPILL_S32_TO_VGPR:
2283 MI.setDesc(get(AMDGPU::V_WRITELANE_B32));
2284 break;
2285
2286 case AMDGPU::SI_RESTORE_S32_FROM_VGPR:
2287 MI.setDesc(get(AMDGPU::V_READLANE_B32));
2288 break;
2289 case AMDGPU::AV_MOV_B32_IMM_PSEUDO: {
2290 Register Dst = MI.getOperand(0).getReg();
2291 bool IsAGPR = SIRegisterInfo::isAGPRClass(RI.getPhysRegBaseClass(Dst));
2292 MI.setDesc(
2293 get(IsAGPR ? AMDGPU::V_ACCVGPR_WRITE_B32_e64 : AMDGPU::V_MOV_B32_e32));
2294 break;
2295 }
2296 case AMDGPU::AV_MOV_B64_IMM_PSEUDO: {
2297 Register Dst = MI.getOperand(0).getReg();
2298 if (SIRegisterInfo::isAGPRClass(RI.getPhysRegBaseClass(Dst))) {
2299 int64_t Imm = MI.getOperand(1).getImm();
2300
2301 Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
2302 Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
2303 BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DstLo)
2305 BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DstHi)
2306 .addImm(SignExtend64<32>(Imm >> 32));
2307 MI.eraseFromParent();
2308 break;
2309 }
2310
2311 [[fallthrough]];
2312 }
2313 case AMDGPU::V_MOV_B64_PSEUDO: {
2314 Register Dst = MI.getOperand(0).getReg();
2315 Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
2316 Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
2317
2318 const MCInstrDesc &Mov64Desc = get(AMDGPU::V_MOV_B64_e32);
2319 const TargetRegisterClass *Mov64RC = getRegClass(Mov64Desc, /*OpNum=*/0);
2320
2321 const MachineOperand &SrcOp = MI.getOperand(1);
2322 // FIXME: Will this work for 64-bit floating point immediates?
2323 assert(!SrcOp.isFPImm());
2324 if (ST.hasVMovB64Inst() && Mov64RC->contains(Dst)) {
2325 MI.setDesc(Mov64Desc);
2326 if (SrcOp.isReg() || isInlineConstant(MI, 1) ||
2327 (SrcOp.isImm() &&
2328 (isUInt<32>(SrcOp.getImm()) || ST.has64BitLiterals())) ||
2329 (SrcOp.isGlobal() && ST.has64BitLiterals()))
2330 break;
2331 }
2332 if (SrcOp.isGlobal()) {
2333 // The address is unknown until link time, so the PK_MOV inline-constant
2334 // shortcut cannot apply.
2335 const GlobalValue *GV = SrcOp.getGlobal();
2336 int64_t Offset = SrcOp.getOffset();
2337 auto [LoFlags, HiFlags] = splitGlobalAddressRelocFlags(SrcOp);
2338
2339 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
2340 .addGlobalAddress(GV, Offset, LoFlags);
2341 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
2342 .addGlobalAddress(GV, Offset, HiFlags);
2343 } else if (SrcOp.isImm()) {
2344 APInt Imm(64, SrcOp.getImm());
2345 APInt Lo(32, Imm.getLoBits(32).getZExtValue());
2346 APInt Hi(32, Imm.getHiBits(32).getZExtValue());
2347 const MCInstrDesc &PkMovDesc = get(AMDGPU::V_PK_MOV_B32);
2348 const TargetRegisterClass *PkMovRC = getRegClass(PkMovDesc, /*OpNum=*/0);
2349
2350 if (ST.hasPkMovB32() && Lo == Hi && isInlineConstant(Lo) &&
2351 PkMovRC->contains(Dst)) {
2352 BuildMI(MBB, MI, DL, PkMovDesc, Dst)
2354 .addImm(Lo.getSExtValue())
2356 .addImm(Lo.getSExtValue())
2357 .addImm(0) // op_sel_lo
2358 .addImm(0) // op_sel_hi
2359 .addImm(0) // neg_lo
2360 .addImm(0) // neg_hi
2361 .addImm(0); // clamp
2362 } else {
2363 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
2364 .addImm(Lo.getSExtValue());
2365 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
2366 .addImm(Hi.getSExtValue());
2367 }
2368 } else {
2369 assert(SrcOp.isReg());
2370 if (ST.hasPkMovB32() &&
2371 !RI.isAGPR(MBB.getParent()->getRegInfo(), SrcOp.getReg())) {
2372 BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), Dst)
2373 .addImm(SISrcMods::OP_SEL_1) // src0_mod
2374 .addReg(SrcOp.getReg())
2376 .addReg(SrcOp.getReg())
2377 .addImm(0) // op_sel_lo
2378 .addImm(0) // op_sel_hi
2379 .addImm(0) // neg_lo
2380 .addImm(0) // neg_hi
2381 .addImm(0); // clamp
2382 } else {
2383 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
2384 .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0));
2385 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
2386 .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1));
2387 }
2388 }
2389 MI.eraseFromParent();
2390 break;
2391 }
2392 case AMDGPU::V_MOV_B64_DPP_PSEUDO: {
2394 break;
2395 }
2396 case AMDGPU::S_MOV_B64_IMM_PSEUDO: {
2397 const MachineOperand &SrcOp = MI.getOperand(1);
2398 assert(!SrcOp.isFPImm());
2399
2400 if (ST.has64BitLiterals()) {
2401 MI.setDesc(get(AMDGPU::S_MOV_B64));
2402 break;
2403 }
2404
2405 if (SrcOp.isGlobal()) {
2406 Register Dst = MI.getOperand(0).getReg();
2407 Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
2408 Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
2409 const GlobalValue *GV = SrcOp.getGlobal();
2410 int64_t Offset = SrcOp.getOffset();
2411 auto [LoFlags, HiFlags] = splitGlobalAddressRelocFlags(SrcOp);
2412
2413 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DstLo)
2414 .addGlobalAddress(GV, Offset, LoFlags);
2415 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DstHi)
2416 .addGlobalAddress(GV, Offset, HiFlags);
2417 MI.eraseFromParent();
2418 break;
2419 }
2420
2421 // SrcOp is immediate
2422 APInt Imm(64, SrcOp.getImm());
2423 if (Imm.isIntN(32) || isInlineConstant(Imm)) {
2424 MI.setDesc(get(AMDGPU::S_MOV_B64));
2425 break;
2426 }
2427
2428 Register Dst = MI.getOperand(0).getReg();
2429 Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
2430 Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
2431
2432 APInt Lo(32, Imm.getLoBits(32).getZExtValue());
2433 APInt Hi(32, Imm.getHiBits(32).getZExtValue());
2434 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DstLo)
2435 .addImm(Lo.getSExtValue());
2436 BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DstHi)
2437 .addImm(Hi.getSExtValue());
2438 MI.eraseFromParent();
2439 break;
2440 }
2441 case AMDGPU::V_SET_INACTIVE_B32: {
2442 // Lower V_SET_INACTIVE_B32 to V_CNDMASK_B32.
2443 Register DstReg = MI.getOperand(0).getReg();
2444 BuildMI(MBB, MI, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
2445 .add(MI.getOperand(3))
2446 .add(MI.getOperand(4))
2447 .add(MI.getOperand(1))
2448 .add(MI.getOperand(2))
2449 .add(MI.getOperand(5));
2450 MI.eraseFromParent();
2451 break;
2452 }
2453 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V1:
2454 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V2:
2455 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V3:
2456 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V4:
2457 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V5:
2458 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V6:
2459 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V7:
2460 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V8:
2461 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V9:
2462 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V10:
2463 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V11:
2464 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V12:
2465 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V16:
2466 case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V32:
2467 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V1:
2468 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V2:
2469 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V3:
2470 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V4:
2471 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V5:
2472 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V6:
2473 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V7:
2474 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V8:
2475 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V9:
2476 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V10:
2477 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V11:
2478 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V12:
2479 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V16:
2480 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V32:
2481 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V1:
2482 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V2:
2483 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V4:
2484 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V8:
2485 case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V16: {
2486 const TargetRegisterClass *EltRC = getOpRegClass(MI, 2);
2487
2488 unsigned Opc;
2489 if (RI.hasVGPRs(EltRC)) {
2490 Opc = AMDGPU::V_MOVRELD_B32_e32;
2491 } else {
2492 Opc = RI.getRegSizeInBits(*EltRC) == 64 ? AMDGPU::S_MOVRELD_B64
2493 : AMDGPU::S_MOVRELD_B32;
2494 }
2495
2496 const MCInstrDesc &OpDesc = get(Opc);
2497 Register VecReg = MI.getOperand(0).getReg();
2498 bool IsUndef = MI.getOperand(1).isUndef();
2499 unsigned SubReg = MI.getOperand(3).getImm();
2500 assert(VecReg == MI.getOperand(1).getReg());
2501
2503 BuildMI(MBB, MI, DL, OpDesc)
2504 .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
2505 .add(MI.getOperand(2))
2507 .addReg(VecReg, RegState::Implicit | getUndefRegState(IsUndef));
2508
2509 const int ImpDefIdx =
2510 OpDesc.getNumOperands() + OpDesc.implicit_uses().size();
2511 const int ImpUseIdx = ImpDefIdx + 1;
2512 MIB->tieOperands(ImpDefIdx, ImpUseIdx);
2513 MI.eraseFromParent();
2514 break;
2515 }
2516 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V1:
2517 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V2:
2518 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V3:
2519 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V4:
2520 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V5:
2521 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V6:
2522 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V7:
2523 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V8:
2524 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V9:
2525 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V10:
2526 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V11:
2527 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V12:
2528 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V16:
2529 case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V32: {
2530 assert(ST.useVGPRIndexMode());
2531 Register VecReg = MI.getOperand(0).getReg();
2532 bool IsUndef = MI.getOperand(1).isUndef();
2533 MachineOperand &Idx = MI.getOperand(3);
2534 Register SubReg = MI.getOperand(4).getImm();
2535
2536 MachineInstr *SetOn = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_ON))
2537 .add(Idx)
2539 SetOn->getOperand(3).setIsUndef();
2540
2541 const MCInstrDesc &OpDesc = get(AMDGPU::V_MOV_B32_indirect_write);
2543 BuildMI(MBB, MI, DL, OpDesc)
2544 .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
2545 .add(MI.getOperand(2))
2547 .addReg(VecReg, RegState::Implicit | getUndefRegState(IsUndef));
2548
2549 const int ImpDefIdx =
2550 OpDesc.getNumOperands() + OpDesc.implicit_uses().size();
2551 const int ImpUseIdx = ImpDefIdx + 1;
2552 MIB->tieOperands(ImpDefIdx, ImpUseIdx);
2553
2554 MachineInstr *SetOff = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_OFF));
2555
2556 finalizeBundle(MBB, SetOn->getIterator(), std::next(SetOff->getIterator()));
2557
2558 MI.eraseFromParent();
2559 break;
2560 }
2561 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V1:
2562 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V2:
2563 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V3:
2564 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V4:
2565 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V5:
2566 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V6:
2567 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V7:
2568 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V8:
2569 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V9:
2570 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V10:
2571 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V11:
2572 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V12:
2573 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V16:
2574 case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V32: {
2575 assert(ST.useVGPRIndexMode());
2576 Register Dst = MI.getOperand(0).getReg();
2577 Register VecReg = MI.getOperand(1).getReg();
2578 bool IsUndef = MI.getOperand(1).isUndef();
2579 Register SubReg = MI.getOperand(3).getImm();
2580
2581 MachineInstr *SetOn = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_ON))
2582 .add(MI.getOperand(2))
2584 SetOn->getOperand(3).setIsUndef();
2585
2586 BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_indirect_read))
2587 .addDef(Dst)
2588 .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
2589 .addReg(VecReg, RegState::Implicit | getUndefRegState(IsUndef));
2590
2591 MachineInstr *SetOff = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_OFF));
2592
2593 finalizeBundle(MBB, SetOn->getIterator(), std::next(SetOff->getIterator()));
2594
2595 MI.eraseFromParent();
2596 break;
2597 }
2598 case AMDGPU::SI_PC_ADD_REL_OFFSET: {
2599 MachineFunction &MF = *MBB.getParent();
2600 Register Reg = MI.getOperand(0).getReg();
2601 Register RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
2602 Register RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
2603 MachineOperand OpLo = MI.getOperand(1);
2604 MachineOperand OpHi = MI.getOperand(2);
2605
2606 // Create a bundle so these instructions won't be re-ordered by the
2607 // post-RA scheduler.
2608 MIBundleBuilder Bundler(MBB, MI);
2609 Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
2610
2611 // What we want here is an offset from the value returned by s_getpc (which
2612 // is the address of the s_add_u32 instruction) to the global variable, but
2613 // since the encoding of $symbol starts 4 bytes after the start of the
2614 // s_add_u32 instruction, we end up with an offset that is 4 bytes too
2615 // small. This requires us to add 4 to the global variable offset in order
2616 // to compute the correct address. Similarly for the s_addc_u32 instruction,
2617 // the encoding of $symbol starts 12 bytes after the start of the s_add_u32
2618 // instruction.
2619
2620 int64_t Adjust = 0;
2621 if (ST.hasGetPCZeroExtension()) {
2622 // Fix up hardware that does not sign-extend the 48-bit PC value by
2623 // inserting: s_sext_i32_i16 reghi, reghi
2624 Bundler.append(
2625 BuildMI(MF, DL, get(AMDGPU::S_SEXT_I32_I16), RegHi).addReg(RegHi));
2626 Adjust += 4;
2627 }
2628
2629 if (OpLo.isGlobal())
2630 OpLo.setOffset(OpLo.getOffset() + Adjust + 4);
2631 Bundler.append(
2632 BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo).addReg(RegLo).add(OpLo));
2633
2634 if (OpHi.isGlobal())
2635 OpHi.setOffset(OpHi.getOffset() + Adjust + 12);
2636 Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
2637 .addReg(RegHi)
2638 .add(OpHi));
2639
2640 finalizeBundle(MBB, Bundler.begin());
2641
2642 MI.eraseFromParent();
2643 break;
2644 }
2645 case AMDGPU::SI_PC_ADD_REL_OFFSET64: {
2646 MachineFunction &MF = *MBB.getParent();
2647 Register Reg = MI.getOperand(0).getReg();
2648 MachineOperand Op = MI.getOperand(1);
2649
2650 // Create a bundle so these instructions won't be re-ordered by the
2651 // post-RA scheduler.
2652 MIBundleBuilder Bundler(MBB, MI);
2653 Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
2654 if (Op.isGlobal())
2655 Op.setOffset(Op.getOffset() + 4);
2656 Bundler.append(
2657 BuildMI(MF, DL, get(AMDGPU::S_ADD_U64), Reg).addReg(Reg).add(Op));
2658
2659 finalizeBundle(MBB, Bundler.begin());
2660
2661 MI.eraseFromParent();
2662 break;
2663 }
2664 case AMDGPU::ENTER_STRICT_WWM: {
2665 // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
2666 // Whole Wave Mode is entered.
2667 MI.setDesc(get(LMC.OrSaveExecOpc));
2668 break;
2669 }
2670 case AMDGPU::ENTER_STRICT_WQM: {
2671 // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
2672 // STRICT_WQM is entered.
2673 BuildMI(MBB, MI, DL, get(LMC.MovOpc), MI.getOperand(0).getReg())
2674 .addReg(LMC.ExecReg);
2675 BuildMI(MBB, MI, DL, get(LMC.WQMOpc), LMC.ExecReg).addReg(LMC.ExecReg);
2676
2677 MI.eraseFromParent();
2678 break;
2679 }
2680 case AMDGPU::EXIT_STRICT_WWM:
2681 case AMDGPU::EXIT_STRICT_WQM: {
2682 // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
2683 // WWM/STICT_WQM is exited.
2684 MI.setDesc(get(LMC.MovOpc));
2685 break;
2686 }
2687 case AMDGPU::SI_RETURN: {
2688 const MachineFunction *MF = MBB.getParent();
2689 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
2690 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2691 // Hiding the return address use with SI_RETURN may lead to extra kills in
2692 // the function and missing live-ins. We are fine in practice because callee
2693 // saved register handling ensures the register value is restored before
2694 // RET, but we need the undef flag here to appease the MachineVerifier
2695 // liveness checks.
2697 BuildMI(MBB, MI, DL, get(AMDGPU::S_SETPC_B64_return))
2698 .addReg(TRI->getReturnAddressReg(*MF), RegState::Undef);
2699
2700 MIB.copyImplicitOps(MI);
2701 MI.eraseFromParent();
2702 break;
2703 }
2704
2705 case AMDGPU::S_MUL_U64_U32_PSEUDO:
2706 case AMDGPU::S_MUL_I64_I32_PSEUDO:
2707 MI.setDesc(get(AMDGPU::S_MUL_U64));
2708 break;
2709
2710 case AMDGPU::S_GETPC_B64_pseudo:
2711 MI.setDesc(get(AMDGPU::S_GETPC_B64));
2712 if (ST.hasGetPCZeroExtension()) {
2713 Register Dst = MI.getOperand(0).getReg();
2714 Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
2715 // Fix up hardware that does not sign-extend the 48-bit PC value by
2716 // inserting: s_sext_i32_i16 dsthi, dsthi
2717 BuildMI(MBB, std::next(MI.getIterator()), DL, get(AMDGPU::S_SEXT_I32_I16),
2718 DstHi)
2719 .addReg(DstHi);
2720 }
2721 break;
2722
2723 case AMDGPU::V_MAX_BF16_PSEUDO_e64: {
2724 assert(ST.hasBF16PackedInsts());
2725 MI.setDesc(get(AMDGPU::V_PK_MAX_NUM_BF16));
2726 MI.addOperand(MachineOperand::CreateImm(0)); // op_sel
2727 MI.addOperand(MachineOperand::CreateImm(0)); // neg_lo
2728 MI.addOperand(MachineOperand::CreateImm(0)); // neg_hi
2729 auto Op0 = getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
2730 Op0->setImm(Op0->getImm() | SISrcMods::OP_SEL_1);
2731 auto Op1 = getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
2732 Op1->setImm(Op1->getImm() | SISrcMods::OP_SEL_1);
2733 break;
2734 }
2735
2736 case AMDGPU::GET_STACK_BASE:
2737 // The stack starts at offset 0 unless we need to reserve some space at the
2738 // bottom.
2739 if (ST.getFrameLowering()->mayReserveScratchForCWSR(*MBB.getParent())) {
2740 // When CWSR is used in dynamic VGPR mode, the trap handler needs to save
2741 // some of the VGPRs. The size of the required scratch space has already
2742 // been computed by prolog epilog insertion.
2743 const SIMachineFunctionInfo *MFI =
2744 MBB.getParent()->getInfo<SIMachineFunctionInfo>();
2745 unsigned VGPRSize = MFI->getScratchReservedForDynamicVGPRs();
2746 Register DestReg = MI.getOperand(0).getReg();
2747 BuildMI(MBB, MI, DL, get(AMDGPU::S_GETREG_B32), DestReg)
2750 // The MicroEngine ID is 0 for the graphics queue, and 1 or 2 for compute
2751 // (3 is unused, so we ignore it). Unfortunately, S_GETREG doesn't set
2752 // SCC, so we need to check for 0 manually.
2753 BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32)).addImm(0).addReg(DestReg);
2754 // Change the implicif-def of SCC to an explicit use (but first remove
2755 // the dead flag if present).
2756 MI.getOperand(MI.getNumExplicitOperands()).setIsDead(false);
2757 MI.getOperand(MI.getNumExplicitOperands()).setIsUse();
2758 MI.setDesc(get(AMDGPU::S_CMOVK_I32));
2759 MI.addOperand(MachineOperand::CreateImm(VGPRSize));
2760 } else {
2761 MI.setDesc(get(AMDGPU::S_MOV_B32));
2762 MI.addOperand(MachineOperand::CreateImm(0));
2763 MI.removeOperand(
2764 MI.getNumExplicitOperands()); // Drop implicit def of SCC.
2765 }
2766 break;
2767 }
2768
2769 return true;
2770}
2771
2774 unsigned SubIdx, const MachineInstr &Orig,
2775 LaneBitmask UsedLanes) const {
2776
2777 // Try shrinking the instruction to remat only the part needed for current
2778 // context.
2779 // TODO: Handle more cases.
2780 unsigned Opcode = Orig.getOpcode();
2781 switch (Opcode) {
2782 case AMDGPU::S_MOV_B64:
2783 case AMDGPU::S_MOV_B64_IMM_PSEUDO: {
2784 if (SubIdx != 0)
2785 break;
2786
2787 if (!Orig.getOperand(1).isImm())
2788 break;
2789
2790 // Shrink S_MOV_B64 to S_MOV_B32 when UsedLanes indicates only a single
2791 // 32-bit lane of the 64-bit value is live at the rematerialization point.
2792 if (UsedLanes.all())
2793 break;
2794
2795 // Determine which half of the 64-bit immediate corresponds to the use.
2796 unsigned OrigSubReg = Orig.getOperand(0).getSubReg();
2797 unsigned LoSubReg = RI.composeSubRegIndices(OrigSubReg, AMDGPU::sub0);
2798 unsigned HiSubReg = RI.composeSubRegIndices(OrigSubReg, AMDGPU::sub1);
2799
2800 bool NeedLo = (UsedLanes & RI.getSubRegIndexLaneMask(LoSubReg)).any();
2801 bool NeedHi = (UsedLanes & RI.getSubRegIndexLaneMask(HiSubReg)).any();
2802
2803 if (NeedLo && NeedHi)
2804 break;
2805
2806 int64_t Imm64 = Orig.getOperand(1).getImm();
2807 int32_t Imm32 = NeedLo ? Lo_32(Imm64) : Hi_32(Imm64);
2808
2809 unsigned UseSubReg = NeedLo ? LoSubReg : HiSubReg;
2810
2811 // Emit S_MOV_B32 defining just the needed 32-bit subreg of DestReg.
2812 BuildMI(MBB, I, Orig.getDebugLoc(), get(AMDGPU::S_MOV_B32))
2813 .addReg(DestReg, RegState::Define | RegState::Undef, UseSubReg)
2814 .addImm(Imm32);
2815 return;
2816 }
2817
2818 case AMDGPU::S_LOAD_DWORDX16_IMM:
2819 case AMDGPU::S_LOAD_DWORDX8_IMM: {
2820 if (SubIdx != 0 || UsedLanes.all())
2821 break;
2822
2823 if (I == MBB.end())
2824 break;
2825
2826 if (I->isBundled())
2827 break;
2828
2829 MachineFunction *MF = MBB.getParent();
2831 assert(MRI.use_nodbg_empty(DestReg) && "DestReg should have no users yet.");
2832
2833 // Look for a single use of the register at the insertion point that is also
2834 // a subreg.
2835 Register RegToFind = Orig.getOperand(0).getReg();
2836 MachineOperand *UseMO = MRI.getOneNonDBGUse(RegToFind);
2837 if (!UseMO ||
2838 UseMO != I->findRegisterUseOperand(RegToFind, /*TRI=*/nullptr) ||
2839 UseMO->getSubReg() == AMDGPU::NoSubRegister)
2840 break;
2841
2842 unsigned Offset = RI.getSubRegIdxOffset(UseMO->getSubReg());
2843 unsigned SubregSize = RI.getSubRegIdxSize(UseMO->getSubReg());
2844
2845 unsigned NewOpcode = -1;
2846 if (SubregSize == 256)
2847 NewOpcode = AMDGPU::S_LOAD_DWORDX8_IMM;
2848 else if (SubregSize == 128)
2849 NewOpcode = AMDGPU::S_LOAD_DWORDX4_IMM;
2850 else
2851 break;
2852
2853 const MCInstrDesc &TID = get(NewOpcode);
2854 const TargetRegisterClass *NewRC =
2855 RI.getAllocatableClass(getRegClass(TID, 0));
2856 MRI.setRegClass(DestReg, NewRC);
2857
2858 UseMO->setReg(DestReg);
2859 UseMO->setSubReg(AMDGPU::NoSubRegister);
2860
2861 // Use a smaller load with the desired size, possibly with updated offset.
2862 MachineInstr *MI = MF->CloneMachineInstr(&Orig);
2863 MI->setDesc(TID);
2864 MI->getOperand(0).setReg(DestReg);
2865 MI->getOperand(0).setSubReg(AMDGPU::NoSubRegister);
2866 if (Offset) {
2867 MachineOperand *OffsetMO = getNamedOperand(*MI, AMDGPU::OpName::offset);
2868 int64_t FinalOffset = OffsetMO->getImm() + Offset / 8;
2869 OffsetMO->setImm(FinalOffset);
2870 }
2872 for (const MachineMemOperand *MemOp : Orig.memoperands())
2873 NewMMOs.push_back(MF->getMachineMemOperand(MemOp, MemOp->getPointerInfo(),
2874 SubregSize / 8));
2875 MI->setMemRefs(*MF, NewMMOs);
2876
2877 MBB.insert(I, MI);
2878 return;
2879 }
2880
2881 default:
2882 break;
2883 }
2884
2885 TargetInstrInfo::reMaterialize(MBB, I, DestReg, SubIdx, Orig, UsedLanes);
2886}
2887
2888std::pair<MachineInstr*, MachineInstr*>
2890 assert (MI.getOpcode() == AMDGPU::V_MOV_B64_DPP_PSEUDO);
2891
2892 if (ST.hasVMovB64Inst() && ST.hasFeature(AMDGPU::FeatureDPALU_DPP) &&
2894 ST, getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl)->getImm())) {
2895 MI.setDesc(get(AMDGPU::V_MOV_B64_dpp));
2896 return std::pair(&MI, nullptr);
2897 }
2898
2899 MachineBasicBlock &MBB = *MI.getParent();
2900 DebugLoc DL = MBB.findDebugLoc(MI);
2901 MachineFunction *MF = MBB.getParent();
2903 Register Dst = MI.getOperand(0).getReg();
2904 unsigned Part = 0;
2905 MachineInstr *Split[2];
2906
2907 for (auto Sub : { AMDGPU::sub0, AMDGPU::sub1 }) {
2908 auto MovDPP = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_dpp));
2909 if (Dst.isPhysical()) {
2910 MovDPP.addDef(RI.getSubReg(Dst, Sub));
2911 } else {
2912 assert(MRI.isSSA());
2913 auto Tmp = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2914 MovDPP.addDef(Tmp);
2915 }
2916
2917 for (unsigned I = 1; I <= 2; ++I) { // old and src operands.
2918 const MachineOperand &SrcOp = MI.getOperand(I);
2919 assert(!SrcOp.isFPImm());
2920 if (SrcOp.isImm()) {
2921 APInt Imm(64, SrcOp.getImm());
2922 Imm.ashrInPlace(Part * 32);
2923 MovDPP.addImm(Imm.getLoBits(32).getZExtValue());
2924 } else {
2925 assert(SrcOp.isReg());
2926 Register Src = SrcOp.getReg();
2927 if (Src.isPhysical())
2928 MovDPP.addReg(RI.getSubReg(Src, Sub));
2929 else
2930 MovDPP.addReg(Src, getUndefRegState(SrcOp.isUndef()), Sub);
2931 }
2932 }
2933
2934 for (const MachineOperand &MO : llvm::drop_begin(MI.explicit_operands(), 3))
2935 MovDPP.addImm(MO.getImm());
2936
2937 Split[Part] = MovDPP;
2938 ++Part;
2939 }
2940
2941 if (Dst.isVirtual())
2942 BuildMI(MBB, MI, DL, get(AMDGPU::REG_SEQUENCE), Dst)
2943 .addReg(Split[0]->getOperand(0).getReg())
2944 .addImm(AMDGPU::sub0)
2945 .addReg(Split[1]->getOperand(0).getReg())
2946 .addImm(AMDGPU::sub1);
2947
2948 MI.eraseFromParent();
2949 return std::pair(Split[0], Split[1]);
2950}
2951
2952std::optional<DestSourcePair>
2954 if (MI.getOpcode() == AMDGPU::WWM_COPY)
2955 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
2956
2957 return std::nullopt;
2958}
2959
2961 AMDGPU::OpName Src0OpName,
2962 MachineOperand &Src1,
2963 AMDGPU::OpName Src1OpName) const {
2964 MachineOperand *Src0Mods = getNamedOperand(MI, Src0OpName);
2965 if (!Src0Mods)
2966 return false;
2967
2968 MachineOperand *Src1Mods = getNamedOperand(MI, Src1OpName);
2969 assert(Src1Mods &&
2970 "All commutable instructions have both src0 and src1 modifiers");
2971
2972 int Src0ModsVal = Src0Mods->getImm();
2973 int Src1ModsVal = Src1Mods->getImm();
2974
2975 Src1Mods->setImm(Src0ModsVal);
2976 Src0Mods->setImm(Src1ModsVal);
2977 return true;
2978}
2979
2981 MachineOperand &RegOp,
2982 MachineOperand &NonRegOp) {
2983 Register Reg = RegOp.getReg();
2984 unsigned SubReg = RegOp.getSubReg();
2985 bool IsKill = RegOp.isKill();
2986 bool IsDead = RegOp.isDead();
2987 bool IsUndef = RegOp.isUndef();
2988 bool IsDebug = RegOp.isDebug();
2989
2990 if (NonRegOp.isImm())
2991 RegOp.ChangeToImmediate(NonRegOp.getImm());
2992 else if (NonRegOp.isFI())
2993 RegOp.ChangeToFrameIndex(NonRegOp.getIndex());
2994 else if (NonRegOp.isGlobal()) {
2995 RegOp.ChangeToGA(NonRegOp.getGlobal(), NonRegOp.getOffset(),
2996 NonRegOp.getTargetFlags());
2997 } else
2998 return nullptr;
2999
3000 // Make sure we don't reinterpret a subreg index in the target flags.
3001 RegOp.setTargetFlags(NonRegOp.getTargetFlags());
3002
3003 NonRegOp.ChangeToRegister(Reg, false, false, IsKill, IsDead, IsUndef, IsDebug);
3004 NonRegOp.setSubReg(SubReg);
3005
3006 return &MI;
3007}
3008
3010 MachineOperand &NonRegOp1,
3011 MachineOperand &NonRegOp2) {
3012 unsigned TargetFlags = NonRegOp1.getTargetFlags();
3013 int64_t NonRegVal = NonRegOp1.getImm();
3014
3015 NonRegOp1.setImm(NonRegOp2.getImm());
3016 NonRegOp2.setImm(NonRegVal);
3017 NonRegOp1.setTargetFlags(NonRegOp2.getTargetFlags());
3018 NonRegOp2.setTargetFlags(TargetFlags);
3019 return &MI;
3020}
3021
3022// GFX950 v_pk_{add,mul}_f32 must not have opsel[1:0] == 2'b10, i.e. OP_SEL_0 on
3023// src1 but not on src0, and v_pk_fma_f32 must not have OP_SEL_0 on src1 or
3024// src2.
3026 bool CheckSwappedSrc = false) {
3027 unsigned Opc = MI.getOpcode();
3028 if (!TII.getSubtarget().hasPkF32InvalidOpSel() ||
3029 (Opc != AMDGPU::V_PK_ADD_F32 && Opc != AMDGPU::V_PK_MUL_F32 &&
3030 Opc != AMDGPU::V_PK_FMA_F32))
3031 return true;
3032
3033 auto Mods = [&](AMDGPU::OpName Name) {
3034 const MachineOperand *Op = TII.getNamedOperand(MI, Name);
3035 return Op ? static_cast<unsigned>(Op->getImm()) : 0u;
3036 };
3037 unsigned Src0Mods = Mods(AMDGPU::OpName::src0_modifiers);
3038 unsigned Src1Mods = Mods(AMDGPU::OpName::src1_modifiers);
3039 unsigned Src2Mods = Mods(AMDGPU::OpName::src2_modifiers);
3040
3041 if (CheckSwappedSrc)
3042 std::swap(Src0Mods, Src1Mods);
3043
3044 if (Opc == AMDGPU::V_PK_FMA_F32)
3045 return !((Src1Mods | Src2Mods) & SISrcMods::OP_SEL_0);
3046 return (Src0Mods & SISrcMods::OP_SEL_0) || !(Src1Mods & SISrcMods::OP_SEL_0);
3047}
3048
3049bool SIInstrInfo::isLegalToSwap(const MachineInstr &MI, unsigned OpIdx0,
3050 unsigned OpIdx1) const {
3051 const MCInstrDesc &InstDesc = MI.getDesc();
3052 const MCOperandInfo &OpInfo0 = InstDesc.operands()[OpIdx0];
3053 const MCOperandInfo &OpInfo1 = InstDesc.operands()[OpIdx1];
3054
3055 unsigned Opc = MI.getOpcode();
3056 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3057 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
3058
3059 // Swapping src0 and src1 swaps their modifiers; refuse a swap that would
3060 // leave an invalid GFX950 packed FP32 op_sel.
3061 bool IsSrc01Swap = ((int)OpIdx0 == Src0Idx && (int)OpIdx1 == Src1Idx) ||
3062 ((int)OpIdx0 == Src1Idx && (int)OpIdx1 == Src0Idx);
3063 if (IsSrc01Swap && !isLegalPkF32OpSel(*this, MI, true))
3064 return false;
3065
3066 const MachineOperand &MO0 = MI.getOperand(OpIdx0);
3067 const MachineOperand &MO1 = MI.getOperand(OpIdx1);
3068
3069 // Swap doesn't breach constant bus or literal limits, but it may move a
3070 // constant out of src0. Allow that for immediates where the destination
3071 // operand can hold them, e.g. VOP3 sources on targets with VOP3 literal
3072 // support. Other non-register operands stay in src0.
3073 if (isVALU(MI, /*AllowLDSDMA=*/false)) {
3074 if ((int)OpIdx0 == Src0Idx && !MO0.isReg() &&
3075 (!MO0.isImm() || !isImmOperandLegal(MI, OpIdx1, MO0)))
3076 return false;
3077 if ((int)OpIdx1 == Src0Idx && !MO1.isReg() &&
3078 (!MO1.isImm() || !isImmOperandLegal(MI, OpIdx0, MO1)))
3079 return false;
3080 }
3081
3082 if ((int)OpIdx1 != Src0Idx && MO0.isReg()) {
3083 if (OpInfo1.RegClass == -1)
3084 return OpInfo1.OperandType == MCOI::OPERAND_UNKNOWN;
3085 return isLegalRegOperand(MI, OpIdx1, MO0) &&
3086 (!MO1.isReg() || isLegalRegOperand(MI, OpIdx0, MO1));
3087 }
3088 if ((int)OpIdx0 != Src0Idx && MO1.isReg()) {
3089 if (OpInfo0.RegClass == -1)
3090 return OpInfo0.OperandType == MCOI::OPERAND_UNKNOWN;
3091 return (!MO0.isReg() || isLegalRegOperand(MI, OpIdx1, MO0)) &&
3092 isLegalRegOperand(MI, OpIdx0, MO1);
3093 }
3094
3095 // No need to check 64-bit literals since swapping does not bring new
3096 // 64-bit literals into current instruction to fold to 32-bit
3097
3098 return isImmOperandLegal(MI, OpIdx1, MO0);
3099}
3100
3102 if (!isDPP(MI))
3103 return false;
3104 const MachineOperand *DppCtrl = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
3105 return !DppCtrl || DppCtrl->getImm() != AMDGPU::DPP::QUAD_PERM_ID;
3106}
3107
3109 unsigned Src0Idx,
3110 unsigned Src1Idx) const {
3111 assert(!NewMI && "this should never be used");
3112
3114 return nullptr;
3115
3116 unsigned Opc = MI.getOpcode();
3117 int CommutedOpcode = commuteOpcode(Opc);
3118 if (CommutedOpcode == -1)
3119 return nullptr;
3120
3121 if (Src0Idx > Src1Idx)
3122 std::swap(Src0Idx, Src1Idx);
3123
3124 assert(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) ==
3125 static_cast<int>(Src0Idx) &&
3126 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) ==
3127 static_cast<int>(Src1Idx) &&
3128 "inconsistency with findCommutedOpIndices");
3129
3130 if (!isLegalToSwap(MI, Src0Idx, Src1Idx))
3131 return nullptr;
3132
3133 MachineInstr *CommutedMI = nullptr;
3134 MachineOperand &Src0 = MI.getOperand(Src0Idx);
3135 MachineOperand &Src1 = MI.getOperand(Src1Idx);
3136 if (Src0.isReg() && Src1.isReg()) {
3137 // Be sure to copy the source modifiers to the right place.
3138 CommutedMI =
3139 TargetInstrInfo::commuteInstructionImpl(MI, NewMI, Src0Idx, Src1Idx);
3140 } else if (Src0.isReg() && !Src1.isReg()) {
3141 CommutedMI = swapRegAndNonRegOperand(MI, Src0, Src1);
3142 } else if (!Src0.isReg() && Src1.isReg()) {
3143 CommutedMI = swapRegAndNonRegOperand(MI, Src1, Src0);
3144 } else if (Src0.isImm() && Src1.isImm()) {
3145 CommutedMI = swapImmOperands(MI, Src0, Src1);
3146 } else {
3147 // FIXME: Found two non registers to commute. This does happen.
3148 return nullptr;
3149 }
3150
3151 if (CommutedMI) {
3152 swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_modifiers,
3153 Src1, AMDGPU::OpName::src1_modifiers);
3154
3155 swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_sel, Src1,
3156 AMDGPU::OpName::src1_sel);
3157
3158 CommutedMI->setDesc(get(CommutedOpcode));
3159 }
3160
3161 return CommutedMI;
3162}
3163
3164// This needs to be implemented because the source modifiers may be inserted
3165// between the true commutable operands, and the base
3166// TargetInstrInfo::commuteInstruction uses it.
3168 unsigned &SrcOpIdx0,
3169 unsigned &SrcOpIdx1) const {
3171 return false;
3172
3173 return findCommutedOpIndices(MI.getDesc(), SrcOpIdx0, SrcOpIdx1);
3174}
3175
3177 unsigned &SrcOpIdx0,
3178 unsigned &SrcOpIdx1) const {
3179 if (!Desc.isCommutable())
3180 return false;
3181
3182 unsigned Opc = Desc.getOpcode();
3183 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3184 if (Src0Idx == -1)
3185 return false;
3186
3187 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
3188 if (Src1Idx == -1)
3189 return false;
3190
3191 return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
3192}
3193
3195 int64_t BrOffset) const {
3196 // BranchRelaxation should never have to check s_setpc_b64 or s_add_pc_i64
3197 // because its dest block is unanalyzable.
3198 assert(isSOPP(BranchOp) || isSOPK(BranchOp));
3199
3200 // Convert to dwords.
3201 BrOffset /= 4;
3202
3203 // The branch instructions do PC += signext(SIMM16 * 4) + 4, so the offset is
3204 // from the next instruction.
3205 BrOffset -= 1;
3206
3207 return isIntN(ST.getCLOpts().s_branch_bits, BrOffset);
3208}
3209
3212 return MI.getOperand(0).getMBB();
3213}
3214
3216 for (const MachineInstr &MI : MBB->terminators()) {
3217 if (MI.getOpcode() == AMDGPU::SI_IF || MI.getOpcode() == AMDGPU::SI_ELSE ||
3218 MI.getOpcode() == AMDGPU::SI_LOOP ||
3219 MI.getOpcode() == AMDGPU::SI_WATERFALL_LOOP)
3220 return true;
3221 }
3222 return false;
3223}
3224
3226 MachineBasicBlock &DestBB,
3227 MachineBasicBlock &RestoreBB,
3228 const DebugLoc &DL, int64_t BrOffset,
3229 RegScavenger *RS) const {
3230 assert(MBB.empty() &&
3231 "new block should be inserted for expanding unconditional branch");
3232 assert(MBB.pred_size() == 1);
3233 assert(RestoreBB.empty() &&
3234 "restore block should be inserted for restoring clobbered registers");
3235
3236 MachineFunction *MF = MBB.getParent();
3239 auto I = MBB.end();
3240 auto &MCCtx = MF->getContext();
3241
3242 if (ST.useAddPCI64Inst()) {
3243 MCSymbol *Offset =
3244 MCCtx.createTempSymbol("offset", /*AlwaysAddSuffix=*/true);
3245 auto AddPC = BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_PC_I64))
3247 MCSymbol *PostAddPCLabel =
3248 MCCtx.createTempSymbol("post_addpc", /*AlwaysAddSuffix=*/true);
3249 AddPC->setPostInstrSymbol(*MF, PostAddPCLabel);
3250 auto *OffsetExpr = MCBinaryExpr::createSub(
3251 MCSymbolRefExpr::create(DestBB.getSymbol(), MCCtx),
3252 MCSymbolRefExpr::create(PostAddPCLabel, MCCtx), MCCtx);
3253 Offset->setVariableValue(OffsetExpr);
3254 return;
3255 }
3256
3257 assert(RS && "RegScavenger required for long branching");
3258
3259 // FIXME: Virtual register workaround for RegScavenger not working with empty
3260 // blocks.
3261 Register PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3262
3263 // Note: as this is used after hazard recognizer we need to apply some hazard
3264 // workarounds directly.
3265 const bool FlushSGPRWrites = (ST.isWave64() && ST.hasVALUMaskWriteHazard()) ||
3266 ST.hasVALUReadSGPRHazard();
3267 auto ApplyHazardWorkarounds = [this, &MBB, &I, &DL, FlushSGPRWrites]() {
3268 if (FlushSGPRWrites)
3269 BuildMI(MBB, I, DL, get(AMDGPU::S_WAITCNT_DEPCTR))
3271 };
3272
3273 // We need to compute the offset relative to the instruction immediately after
3274 // s_getpc_b64. Insert pc arithmetic code before last terminator.
3275 MachineInstr *GetPC = BuildMI(MBB, I, DL, get(AMDGPU::S_GETPC_B64), PCReg);
3276 ApplyHazardWorkarounds();
3277
3278 MCSymbol *PostGetPCLabel =
3279 MCCtx.createTempSymbol("post_getpc", /*AlwaysAddSuffix=*/true);
3280 GetPC->setPostInstrSymbol(*MF, PostGetPCLabel);
3281
3282 MCSymbol *OffsetLo =
3283 MCCtx.createTempSymbol("offset_lo", /*AlwaysAddSuffix=*/true);
3284 MCSymbol *OffsetHi =
3285 MCCtx.createTempSymbol("offset_hi", /*AlwaysAddSuffix=*/true);
3286 BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_U32))
3287 .addReg(PCReg, RegState::Define, AMDGPU::sub0)
3288 .addReg(PCReg, {}, AMDGPU::sub0)
3289 .addSym(OffsetLo, MO_FAR_BRANCH_OFFSET);
3290 BuildMI(MBB, I, DL, get(AMDGPU::S_ADDC_U32))
3291 .addReg(PCReg, RegState::Define, AMDGPU::sub1)
3292 .addReg(PCReg, {}, AMDGPU::sub1)
3293 .addSym(OffsetHi, MO_FAR_BRANCH_OFFSET);
3294 ApplyHazardWorkarounds();
3295
3296 // Insert the indirect branch after the other terminator.
3297 BuildMI(&MBB, DL, get(AMDGPU::S_SETPC_B64))
3298 .addReg(PCReg);
3299
3300 // If a spill is needed for the pc register pair, we need to insert a spill
3301 // restore block right before the destination block, and insert a short branch
3302 // into the old destination block's fallthrough predecessor.
3303 // e.g.:
3304 //
3305 // s_cbranch_scc0 skip_long_branch:
3306 //
3307 // long_branch_bb:
3308 // spill s[8:9]
3309 // s_getpc_b64 s[8:9]
3310 // s_add_u32 s8, s8, restore_bb
3311 // s_addc_u32 s9, s9, 0
3312 // s_setpc_b64 s[8:9]
3313 //
3314 // skip_long_branch:
3315 // foo;
3316 //
3317 // .....
3318 //
3319 // dest_bb_fallthrough_predecessor:
3320 // bar;
3321 // s_branch dest_bb
3322 //
3323 // restore_bb:
3324 // restore s[8:9]
3325 // fallthrough dest_bb
3326 ///
3327 // dest_bb:
3328 // buzz;
3329
3330 Register LongBranchReservedReg = MFI->getLongBranchReservedReg();
3331 Register Scav;
3332
3333 // If we've previously reserved a register for long branches
3334 // avoid running the scavenger and just use those registers
3335 if (LongBranchReservedReg) {
3336 RS->enterBasicBlock(MBB);
3337 Scav = LongBranchReservedReg;
3338 } else {
3339 RS->enterBasicBlockEnd(MBB);
3340 Scav = RS->scavengeRegisterBackwards(
3341 AMDGPU::SReg_64RegClass, MachineBasicBlock::iterator(GetPC),
3342 /* RestoreAfter */ false, 0, /* AllowSpill */ false);
3343 }
3344 if (Scav) {
3345 RS->setRegUsed(Scav);
3346 MRI.replaceRegWith(PCReg, Scav);
3347 MRI.clearVirtRegs();
3348 } else {
3349 // As SGPR needs VGPR to be spilled, we reuse the slot of temporary VGPR for
3350 // SGPR spill.
3351 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3352 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3353 TRI->spillEmergencySGPR(GetPC, RestoreBB, AMDGPU::SGPR0_SGPR1, RS);
3354 MRI.replaceRegWith(PCReg, AMDGPU::SGPR0_SGPR1);
3355 MRI.clearVirtRegs();
3356 }
3357
3358 MCSymbol *DestLabel = Scav ? DestBB.getSymbol() : RestoreBB.getSymbol();
3359 // Now, the distance could be defined.
3361 MCSymbolRefExpr::create(DestLabel, MCCtx),
3362 MCSymbolRefExpr::create(PostGetPCLabel, MCCtx), MCCtx);
3363 // Add offset assignments.
3364 auto *Mask = MCConstantExpr::create(0xFFFFFFFFULL, MCCtx);
3365 OffsetLo->setVariableValue(MCBinaryExpr::createAnd(Offset, Mask, MCCtx));
3366 auto *ShAmt = MCConstantExpr::create(32, MCCtx);
3367 OffsetHi->setVariableValue(MCBinaryExpr::createAShr(Offset, ShAmt, MCCtx));
3368}
3369
3370unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
3371 switch (Cond) {
3372 case SIInstrInfo::SCC_TRUE:
3373 return AMDGPU::S_CBRANCH_SCC1;
3374 case SIInstrInfo::SCC_FALSE:
3375 return AMDGPU::S_CBRANCH_SCC0;
3376 case SIInstrInfo::VCCNZ:
3377 return AMDGPU::S_CBRANCH_VCCNZ;
3378 case SIInstrInfo::VCCZ:
3379 return AMDGPU::S_CBRANCH_VCCZ;
3380 case SIInstrInfo::EXECNZ:
3381 return AMDGPU::S_CBRANCH_EXECNZ;
3382 case SIInstrInfo::EXECZ:
3383 return AMDGPU::S_CBRANCH_EXECZ;
3384 default:
3385 llvm_unreachable("invalid branch predicate");
3386 }
3387}
3388
3389SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
3390 switch (Opcode) {
3391 case AMDGPU::S_CBRANCH_SCC0:
3392 return SCC_FALSE;
3393 case AMDGPU::S_CBRANCH_SCC1:
3394 return SCC_TRUE;
3395 case AMDGPU::S_CBRANCH_VCCNZ:
3396 return VCCNZ;
3397 case AMDGPU::S_CBRANCH_VCCZ:
3398 return VCCZ;
3399 case AMDGPU::S_CBRANCH_EXECNZ:
3400 return EXECNZ;
3401 case AMDGPU::S_CBRANCH_EXECZ:
3402 return EXECZ;
3403 default:
3404 return INVALID_BR;
3405 }
3406}
3407
3411 MachineBasicBlock *&FBB,
3413 bool AllowModify) const {
3414 if (I->getOpcode() == AMDGPU::S_BRANCH) {
3415 // Unconditional Branch
3416 TBB = I->getOperand(0).getMBB();
3417 return false;
3418 }
3419
3420 BranchPredicate Pred = getBranchPredicate(I->getOpcode());
3421 if (Pred == INVALID_BR)
3422 return true;
3423
3424 MachineBasicBlock *CondBB = I->getOperand(0).getMBB();
3425 Cond.push_back(MachineOperand::CreateImm(Pred));
3426 Cond.push_back(I->getOperand(1)); // Save the branch register.
3427
3428 ++I;
3429
3430 if (I == MBB.end()) {
3431 // Conditional branch followed by fall-through.
3432 TBB = CondBB;
3433 return false;
3434 }
3435
3436 if (I->getOpcode() == AMDGPU::S_BRANCH) {
3437 TBB = CondBB;
3438 FBB = I->getOperand(0).getMBB();
3439 return false;
3440 }
3441
3442 return true;
3443}
3444
3446 MachineBasicBlock *&FBB,
3448 bool AllowModify) const {
3449 MachineBasicBlock::iterator I = MBB.getFirstTerminator();
3450 auto E = MBB.end();
3451 if (I == E)
3452 return false;
3453
3454 // Skip over the instructions that are artificially terminators for special
3455 // exec management.
3456 while (I != E && !I->isBranch() && !I->isReturn()) {
3457 switch (I->getOpcode()) {
3458 case AMDGPU::S_MOV_B64_term:
3459 case AMDGPU::S_XOR_B64_term:
3460 case AMDGPU::S_OR_B64_term:
3461 case AMDGPU::S_ANDN2_B64_term:
3462 case AMDGPU::S_AND_B64_term:
3463 case AMDGPU::S_AND_SAVEEXEC_B64_term:
3464 case AMDGPU::S_MOV_B32_term:
3465 case AMDGPU::S_XOR_B32_term:
3466 case AMDGPU::S_OR_B32_term:
3467 case AMDGPU::S_ANDN2_B32_term:
3468 case AMDGPU::S_AND_B32_term:
3469 case AMDGPU::S_AND_SAVEEXEC_B32_term:
3470 case AMDGPU::V_CMPX_EQ_U32_nosdst_e32_term:
3471 case AMDGPU::V_CMPX_EQ_U64_nosdst_e32_term:
3472 break;
3473 case AMDGPU::SI_IF:
3474 case AMDGPU::SI_ELSE:
3475 case AMDGPU::SI_KILL_I1_TERMINATOR:
3476 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
3477 // FIXME: It's messy that these need to be considered here at all.
3478 return true;
3479 default:
3480 llvm_unreachable("unexpected non-branch terminator inst");
3481 }
3482
3483 ++I;
3484 }
3485
3486 if (I == E)
3487 return false;
3488
3489 return analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify);
3490}
3491
3493 int *BytesRemoved) const {
3494 unsigned Count = 0;
3495 unsigned RemovedSize = 0;
3496 for (MachineInstr &MI : llvm::make_early_inc_range(MBB.terminators())) {
3497 // Skip over artificial terminators when removing instructions.
3498 if (MI.isBranch() || MI.isReturn()) {
3499 RemovedSize += getInstSizeInBytes(MI);
3500 MI.eraseFromParent();
3501 ++Count;
3502 }
3503 }
3504
3505 if (BytesRemoved)
3506 *BytesRemoved = RemovedSize;
3507
3508 return Count;
3509}
3510
3511// Copy the flags onto the implicit condition register operand.
3513 const MachineOperand &OrigCond) {
3514 CondReg.setIsUndef(OrigCond.isUndef());
3515 CondReg.setIsKill(OrigCond.isKill());
3516}
3517
3520 MachineBasicBlock *FBB,
3522 const DebugLoc &DL,
3523 int *BytesAdded) const {
3524 if (!FBB && Cond.empty()) {
3525 BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
3526 .addMBB(TBB);
3527 if (BytesAdded)
3528 *BytesAdded = ST.hasOffset3fBug() ? 8 : 4;
3529 return 1;
3530 }
3531
3532 assert(TBB && Cond[0].isImm());
3533
3534 unsigned Opcode
3535 = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
3536
3537 if (!FBB) {
3538 MachineInstr *CondBr =
3539 BuildMI(&MBB, DL, get(Opcode))
3540 .addMBB(TBB);
3541
3542 // Copy the flags onto the implicit condition register operand.
3543 preserveCondRegFlags(CondBr->getOperand(1), Cond[1]);
3544 fixImplicitOperands(*CondBr);
3545
3546 if (BytesAdded)
3547 *BytesAdded = ST.hasOffset3fBug() ? 8 : 4;
3548 return 1;
3549 }
3550
3551 assert(TBB && FBB);
3552
3553 MachineInstr *CondBr =
3554 BuildMI(&MBB, DL, get(Opcode))
3555 .addMBB(TBB);
3556 fixImplicitOperands(*CondBr);
3557 BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
3558 .addMBB(FBB);
3559
3560 MachineOperand &CondReg = CondBr->getOperand(1);
3561 CondReg.setIsUndef(Cond[1].isUndef());
3562 CondReg.setIsKill(Cond[1].isKill());
3563
3564 if (BytesAdded)
3565 *BytesAdded = ST.hasOffset3fBug() ? 16 : 8;
3566
3567 return 2;
3568}
3569
3572 if (Cond.size() != 2) {
3573 return true;
3574 }
3575
3576 if (Cond[0].isImm()) {
3577 Cond[0].setImm(-Cond[0].getImm());
3578 return false;
3579 }
3580
3581 return true;
3582}
3583
3584namespace {
3585class AMDGPUPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
3586private:
3587 /// The compare instruction for loop control
3588 const MachineInstr *CmpInst = nullptr;
3589 /// The normalized condition used by createTripCountGreaterCondition()
3591
3592public:
3593 AMDGPUPipelinerLoopInfo(MachineInstr *CmpInst,
3595 : CmpInst(CmpInst), Cond(Cond.begin(), Cond.end()) {}
3596
3597 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
3598 return CmpInst && MI == CmpInst;
3599 }
3600
3601 std::optional<bool> createTripCountGreaterCondition(
3602 int TC, MachineBasicBlock &MBB,
3603 SmallVectorImpl<MachineOperand> &CondParam) override {
3604 CondParam = this->Cond;
3605 return {};
3606 }
3607
3608 void adjustTripCount(int TripCountAdjust) override {}
3609
3610 void setPreheader(MachineBasicBlock *NewPreheader) override {}
3611};
3612} // namespace
3613
3614std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
3616 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
3618 // Unanalyzable terminator.
3619 if (analyzeBranch(*LoopBB, TBB, FBB, Cond, /*AllowModify=*/false))
3620 return nullptr;
3621
3622 // Infinite loops are not supported.
3623 if (TBB == LoopBB && FBB == LoopBB)
3624 return nullptr;
3625
3626 // Must be conditional branch.
3627 if (FBB == nullptr)
3628 return nullptr;
3629
3630 assert((TBB == LoopBB || FBB == LoopBB) &&
3631 "The Loop must be a single-basic-block loop");
3632
3633 // Divergent (VCC/EXEC) back-edge is not supported.
3634 BranchPredicate Pred = static_cast<BranchPredicate>(Cond[0].getImm());
3635 if (Pred != SCC_TRUE && Pred != SCC_FALSE)
3636 return nullptr;
3637
3638 // Calls and inline assembly are not supported.
3639 for (const MachineInstr &MI : *LoopBB)
3640 if (MI.isCall() || MI.isInlineAsm())
3641 return nullptr;
3642
3643 // Normalization for createTripCountGreaterCondition(): make Cond mean
3644 // "exit the loop" so the expander emits correct prolog guard branches.
3645 if (TBB == LoopBB)
3647
3648 auto Instructions = make_range(
3650 LoopBB->rend());
3651 auto CmpI = llvm::find_if(Instructions, [&](const MachineInstr &MI) {
3652 return MI.modifiesRegister(Cond[1].getReg(), &RI);
3653 });
3654
3655 if (CmpI == Instructions.end() || CmpI->isPHI())
3656 return nullptr;
3657 MachineInstr *CmpInst = &*CmpI;
3658
3659 return std::make_unique<AMDGPUPipelinerLoopInfo>(CmpInst, Cond);
3660}
3661
3664 Register DstReg, Register TrueReg,
3665 Register FalseReg,
3666 SelectExpansion &Exp) const {
3667 switch (Cond[0].getImm()) {
3668 case VCCNZ:
3669 case VCCZ: {
3670 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3671 const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
3672 if (MRI.getRegClass(FalseReg) != RC)
3673 return false;
3674
3675 int NumInsts = AMDGPU::getRegBitWidth(*RC) / 32;
3676 Exp.CondCycles = Exp.TrueCycles = Exp.FalseCycles = NumInsts; // ???
3677
3678 // Limit to equal cost for branch vs. N v_cndmask_b32s.
3679 return RI.hasVGPRs(RC) && NumInsts <= 6;
3680 }
3681 case SCC_TRUE:
3682 case SCC_FALSE: {
3683 // FIXME: We could insert for VGPRs if we could replace the original compare
3684 // with a vector one.
3685 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3686 const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
3687 if (MRI.getRegClass(FalseReg) != RC)
3688 return false;
3689
3690 int NumInsts = AMDGPU::getRegBitWidth(*RC) / 32;
3691
3692 // Multiples of 8 can do s_cselect_b64
3693 if (NumInsts % 2 == 0)
3694 NumInsts /= 2;
3695
3696 Exp.CondCycles = Exp.TrueCycles = Exp.FalseCycles = NumInsts; // ???
3697 return RI.isSGPRClass(RC);
3698 }
3699 default:
3700 return false;
3701 }
3702}
3703
3707 Register TrueReg, Register FalseReg) const {
3708 BranchPredicate Pred = static_cast<BranchPredicate>(Cond[0].getImm());
3709 if (Pred == VCCZ || Pred == SCC_FALSE) {
3710 Pred = static_cast<BranchPredicate>(-Pred);
3711 std::swap(TrueReg, FalseReg);
3712 }
3713
3714 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3715 const TargetRegisterClass *DstRC = MRI.getRegClass(DstReg);
3716 unsigned DstSize = RI.getRegSizeInBits(*DstRC);
3717
3718 if (DstSize == 32) {
3720 if (Pred == SCC_TRUE) {
3721 Select = BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B32), DstReg)
3722 .addReg(TrueReg)
3723 .addReg(FalseReg);
3724 } else {
3725 // Instruction's operands are backwards from what is expected.
3726 Select = BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e32), DstReg)
3727 .addReg(FalseReg)
3728 .addReg(TrueReg);
3729 }
3730
3731 preserveCondRegFlags(Select->getOperand(3), Cond[1]);
3732 return;
3733 }
3734
3735 if (DstSize == 64 && Pred == SCC_TRUE) {
3737 BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), DstReg)
3738 .addReg(TrueReg)
3739 .addReg(FalseReg);
3740
3741 preserveCondRegFlags(Select->getOperand(3), Cond[1]);
3742 return;
3743 }
3744
3745 static const int16_t Sub0_15[] = {
3746 AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
3747 AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
3748 AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
3749 AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15,
3750 };
3751
3752 static const int16_t Sub0_15_64[] = {
3753 AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
3754 AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
3755 AMDGPU::sub8_sub9, AMDGPU::sub10_sub11,
3756 AMDGPU::sub12_sub13, AMDGPU::sub14_sub15,
3757 };
3758
3759 unsigned SelOp = AMDGPU::V_CNDMASK_B32_e32;
3760 const TargetRegisterClass *EltRC = &AMDGPU::VGPR_32RegClass;
3761 const int16_t *SubIndices = Sub0_15;
3762 int NElts = DstSize / 32;
3763
3764 // 64-bit select is only available for SALU.
3765 // TODO: Split 96-bit into 64-bit and 32-bit, not 3x 32-bit.
3766 if (Pred == SCC_TRUE) {
3767 if (NElts % 2) {
3768 SelOp = AMDGPU::S_CSELECT_B32;
3769 EltRC = &AMDGPU::SGPR_32RegClass;
3770 } else {
3771 SelOp = AMDGPU::S_CSELECT_B64;
3772 EltRC = &AMDGPU::SGPR_64RegClass;
3773 SubIndices = Sub0_15_64;
3774 NElts /= 2;
3775 }
3776 }
3777
3779 MBB, I, DL, get(AMDGPU::REG_SEQUENCE), DstReg);
3780
3781 I = MIB->getIterator();
3782
3784 for (int Idx = 0; Idx != NElts; ++Idx) {
3785 Register DstElt = MRI.createVirtualRegister(EltRC);
3786 Regs.push_back(DstElt);
3787
3788 unsigned SubIdx = SubIndices[Idx];
3789
3791 if (SelOp == AMDGPU::V_CNDMASK_B32_e32) {
3792 Select = BuildMI(MBB, I, DL, get(SelOp), DstElt)
3793 .addReg(FalseReg, {}, SubIdx)
3794 .addReg(TrueReg, {}, SubIdx);
3795 } else {
3796 Select = BuildMI(MBB, I, DL, get(SelOp), DstElt)
3797 .addReg(TrueReg, {}, SubIdx)
3798 .addReg(FalseReg, {}, SubIdx);
3799 }
3800
3801 preserveCondRegFlags(Select->getOperand(3), Cond[1]);
3803
3804 MIB.addReg(DstElt)
3805 .addImm(SubIdx);
3806 }
3807}
3808
3810
3811 if (MI.isBranch() || MI.isCall() || MI.isReturn() || MI.isIndirectBranch())
3812 return true;
3813
3814 switch (MI.getOpcode()) {
3815 case AMDGPU::S_ENDPGM:
3816 case AMDGPU::S_ENDPGM_SAVED:
3817 case AMDGPU::S_TRAP:
3818 case AMDGPU::S_GETREG_B32:
3819 case AMDGPU::S_SETREG_B32:
3820 case AMDGPU::S_SETREG_B32_mode:
3821 case AMDGPU::S_SETREG_IMM32_B32:
3822 case AMDGPU::S_SETREG_IMM32_B32_mode:
3823 case AMDGPU::S_SENDMSG:
3824 case AMDGPU::S_SENDMSGHALT:
3825 case AMDGPU::S_SENDMSG_RTN_B32:
3826 case AMDGPU::S_SENDMSG_RTN_B64:
3827 case AMDGPU::S_BARRIER_WAIT:
3828 case AMDGPU::S_BARRIER_SIGNAL_M0:
3829 case AMDGPU::S_BARRIER_SIGNAL_IMM:
3830 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_M0:
3831 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM:
3832 return true;
3833 default:
3834 return false;
3835 }
3836}
3837
3839 switch (MI.getOpcode()) {
3840 case AMDGPU::V_MOV_B16_t16_e32:
3841 case AMDGPU::V_MOV_B16_t16_e64:
3842 case AMDGPU::V_MOV_B32_e32:
3843 case AMDGPU::V_MOV_B32_e64:
3844 case AMDGPU::V_MOV_B64_PSEUDO:
3845 case AMDGPU::V_MOV_B64_e32:
3846 case AMDGPU::V_MOV_B64_e64:
3847 case AMDGPU::S_MOV_B32:
3848 case AMDGPU::S_MOV_B64:
3849 case AMDGPU::S_MOV_B64_IMM_PSEUDO:
3850 case AMDGPU::COPY:
3851 case AMDGPU::WWM_COPY:
3852 case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
3853 case AMDGPU::V_ACCVGPR_READ_B32_e64:
3854 case AMDGPU::V_ACCVGPR_MOV_B32:
3855 case AMDGPU::AV_MOV_B32_IMM_PSEUDO:
3856 case AMDGPU::AV_MOV_B64_IMM_PSEUDO:
3857 return true;
3858 default:
3859 return false;
3860 }
3861}
3862
3864 switch (MI.getOpcode()) {
3865 case AMDGPU::V_MOV_B16_t16_e32:
3866 case AMDGPU::V_MOV_B16_t16_e64:
3867 return 2;
3868 case AMDGPU::V_MOV_B32_e32:
3869 case AMDGPU::V_MOV_B32_e64:
3870 case AMDGPU::V_MOV_B64_PSEUDO:
3871 case AMDGPU::V_MOV_B64_e32:
3872 case AMDGPU::V_MOV_B64_e64:
3873 case AMDGPU::S_MOV_B32:
3874 case AMDGPU::S_MOV_B64:
3875 case AMDGPU::S_MOV_B64_IMM_PSEUDO:
3876 case AMDGPU::COPY:
3877 case AMDGPU::WWM_COPY:
3878 case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
3879 case AMDGPU::V_ACCVGPR_READ_B32_e64:
3880 case AMDGPU::V_ACCVGPR_MOV_B32:
3881 case AMDGPU::AV_MOV_B32_IMM_PSEUDO:
3882 case AMDGPU::AV_MOV_B64_IMM_PSEUDO:
3883 return 1;
3884 default:
3885 llvm_unreachable("MI is not a foldable copy");
3886 }
3887}
3888
3889static constexpr AMDGPU::OpName ModifierOpNames[] = {
3890 AMDGPU::OpName::src0_modifiers, AMDGPU::OpName::src1_modifiers,
3891 AMDGPU::OpName::src2_modifiers, AMDGPU::OpName::clamp,
3892 AMDGPU::OpName::omod, AMDGPU::OpName::op_sel};
3893
3895 unsigned Opc = MI.getOpcode();
3896 for (AMDGPU::OpName Name : reverse(ModifierOpNames)) {
3897 int Idx = AMDGPU::getNamedOperandIdx(Opc, Name);
3898 if (Idx >= 0)
3899 MI.removeOperand(Idx);
3900 }
3901}
3902
3904 const MCInstrDesc &NewDesc) const {
3905 MI.setDesc(NewDesc);
3906
3907 // Remove any leftover implicit operands from mutating the instruction. e.g.
3908 // if we replace an s_and_b32 with a copy, we don't need the implicit scc def
3909 // anymore.
3910 const MCInstrDesc &Desc = MI.getDesc();
3911 unsigned NumOps = Desc.getNumOperands() + Desc.implicit_uses().size() +
3912 Desc.implicit_defs().size();
3913
3914 for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
3915 MI.removeOperand(I);
3916}
3917
3918std::optional<int64_t> SIInstrInfo::extractSubregFromImm(int64_t Imm,
3919 unsigned SubRegIndex) {
3920 switch (SubRegIndex) {
3921 case AMDGPU::NoSubRegister:
3922 return Imm;
3923 case AMDGPU::sub0:
3924 return SignExtend64<32>(Imm);
3925 case AMDGPU::sub1:
3926 return SignExtend64<32>(Imm >> 32);
3927 case AMDGPU::lo16:
3928 return SignExtend64<16>(Imm);
3929 case AMDGPU::hi16:
3930 return SignExtend64<16>(Imm >> 16);
3931 case AMDGPU::sub1_lo16:
3932 return SignExtend64<16>(Imm >> 32);
3933 case AMDGPU::sub1_hi16:
3934 return SignExtend64<16>(Imm >> 48);
3935 default:
3936 return std::nullopt;
3937 }
3938
3939 llvm_unreachable("covered subregister switch");
3940}
3941
3943 unsigned OpIdx) {
3944 if (OpIdx == 0 || MI.getDesc().operands()[OpIdx - 1].OperandType !=
3946 return nullptr;
3947 return &MI.getOperand(OpIdx - 1);
3948}
3949
3950// bf16 floating-point inline constants are materialized as fp32, so the bf16
3951// value is in the high half.
3952static bool isBF16FPInlineConstant(int64_t Imm, bool HasInv2Pi) {
3953 bool IsFP = false;
3954 return (isInt<16>(Imm) || isUInt<16>(Imm)) &&
3955 AMDGPU::isInlinableLiteralBF16(Imm, HasInv2Pi, &IsFP) && IsFP;
3956}
3957
3958static unsigned getNumOpSelBitsForMods(const GCNSubtarget &ST,
3959 const MachineInstr &MI, unsigned OpIdx,
3960 unsigned Mods) {
3961 uint8_t OpType = MI.getDesc().operands()[OpIdx].OperandType;
3962 switch (OpType) {
3964 return ST.hasPKF32InstsReplicatingLower32BitsOfScalarInput() ? 2 : 0;
3972 return 2;
3975 if (!ST.hasBF16InlineConstFromUpperFP32())
3976 return 0;
3977
3979 return 0;
3980 return 1;
3981 default:
3982 return 0;
3983 }
3984}
3985
3986static unsigned getOpSelHalfSize(uint8_t OpType) {
3987 return OpType == AMDGPU::OPERAND_REG_IMM_V2FP32 ? 32 : 16;
3988}
3989
3990int64_t SIInstrInfo::getImmOperandBits(uint8_t OpType, int64_t Imm) const {
3991 switch (OpType) {
3993 // Only the low 32 bits of an immediate are encoded, and are replicated to
3994 // both halves.
3995 if (ST.hasPKF32InstsReplicatingLower32BitsOfScalarInput())
3996 return Make_64(Lo_32(Imm), Lo_32(Imm));
3997 break;
4000 if (ST.hasBF16InlineConstFromUpperFP32() &&
4001 isBF16FPInlineConstant(Lo_32(Imm), ST.hasInv2PiInlineImm()))
4002 return SignExtend64<32>(Lo_32(Imm) << 16);
4003 break;
4006 if (!ST.hasBF16InlineConstFromUpperFP32())
4007 break;
4008
4009 // Integer inline constants are sign extended, and literals only encode
4010 // the low 16 bits.
4011 if (isBF16FPInlineConstant(Imm, ST.hasInv2PiInlineImm()))
4012 return SignExtend64<32>((Imm & 0xffff) << 16);
4013 if (isInlineConstant(Imm, OpType))
4014 return SignExtend64<16>(Imm);
4015 return Imm & 0xffff;
4016 default:
4017 break;
4018 }
4019
4020 return Imm;
4021}
4022
4023static unsigned getSrcModifiers(const MachineInstr &MI, unsigned OpIdx) {
4024 const MachineOperand *ModsOp = getSrcModifiersOperand(MI, OpIdx);
4025 return ModsOp ? ModsOp->getImm() : SISrcMods::OP_SEL_1;
4026}
4027
4028static bool isImmOpSelLegal(const GCNSubtarget &ST, const MachineInstr &MI,
4029 unsigned OpIdx, int64_t Imm,
4030 std::optional<unsigned> Mods = std::nullopt) {
4031 if (!ST.hasBF16InlineConstFromUpperFP32())
4032 return true;
4033
4034 uint8_t OpType = MI.getDesc().operands()[OpIdx].OperandType;
4035 if (OpType != AMDGPU::OPERAND_REG_IMM_BF16 &&
4037 return true;
4038
4039 if (!isBF16FPInlineConstant(Imm, ST.hasInv2PiInlineImm()))
4040 return true;
4041
4042 unsigned SrcMods = Mods ? *Mods : getSrcModifiers(MI, OpIdx);
4043 return (SrcMods & SISrcMods::OP_SEL_0) ||
4044 !getNumOpSelBitsForMods(ST, MI, OpIdx, SrcMods);
4045}
4046
4048 unsigned OpIdx) const {
4049 const MachineOperand *ModsOp = getSrcModifiersOperand(MI, OpIdx);
4050 return ModsOp ? getNumOpSelBitsForMods(ST, MI, OpIdx, ModsOp->getImm()) : 0;
4051}
4052
4054 int64_t Imm) const {
4055 uint8_t OpType = MI.getDesc().operands()[OpIdx].OperandType;
4056 int64_t ImmBits = getImmOperandBits(OpType, Imm);
4057 if (ImmBits == Imm)
4058 return true;
4059
4060 return getSrcOperandValue(MI, OpIdx, ImmBits) ==
4061 getSrcOperandValue(MI, OpIdx, Imm);
4062}
4063
4064int64_t SIInstrInfo::getSrcOperandValue(const MachineInstr &MI, unsigned OpIdx,
4065 int64_t Bits, unsigned Mods) const {
4066 unsigned NumOpSelBits = getNumOpSelBitsForMods(ST, MI, OpIdx, Mods);
4067 if (!NumOpSelBits)
4068 return Bits;
4069
4070 uint8_t OpType = MI.getDesc().operands()[OpIdx].OperandType;
4071 unsigned HalfBits = getOpSelHalfSize(OpType);
4072 uint64_t HalfMask = maskTrailingOnes<uint64_t>(HalfBits);
4073 uint64_t Value = 0;
4074 for (unsigned I = 0; I != NumOpSelBits; ++I) {
4075 unsigned OpSel = I == 0 ? SISrcMods::OP_SEL_0 : SISrcMods::OP_SEL_1;
4076 unsigned Shift = (Mods & OpSel) ? HalfBits : 0;
4077 Value |= ((Bits >> Shift) & HalfMask) << (I * HalfBits);
4078 }
4079
4080 return SignExtend64(Value, NumOpSelBits * HalfBits);
4081}
4082
4083int64_t SIInstrInfo::getSrcOperandValue(const MachineInstr &MI, unsigned OpIdx,
4084 int64_t Bits) const {
4085 return getSrcOperandValue(MI, OpIdx, Bits, getSrcModifiers(MI, OpIdx));
4086}
4087
4088std::optional<unsigned> SIInstrInfo::getImmOpSelForValue(const MachineInstr &MI,
4089 unsigned OpIdx,
4090 int64_t Imm,
4091 int64_t Value,
4092 unsigned Mods) const {
4093 uint8_t OpType = MI.getDesc().operands()[OpIdx].OperandType;
4094 int64_t ImmBits = getImmOperandBits(OpType, Imm);
4095 unsigned NumOpSelBits = getNumOpSelBitsForMods(ST, MI, OpIdx, Mods);
4096 if (!NumOpSelBits)
4097 return ImmBits == Value ? std::optional(Mods) : std::nullopt;
4098
4099 unsigned Base = Mods & ~(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1);
4100 const unsigned OneBitCandidates[] = {Mods, Mods ^ SISrcMods::OP_SEL_0};
4101 const unsigned TwoBitCandidates[] = {Mods, Base | SISrcMods::OP_SEL_1, Base,
4105 ArrayRef<unsigned> Candidates = NumOpSelBits == 1
4106 ? ArrayRef<unsigned>(OneBitCandidates)
4107 : ArrayRef<unsigned>(TwoBitCandidates);
4108 for (unsigned NewMods : Candidates) {
4109 if (getSrcOperandValue(MI, OpIdx, ImmBits, NewMods) == Value)
4110 return NewMods;
4111 }
4112
4113 return std::nullopt;
4114}
4115
4116std::optional<unsigned>
4118 unsigned SubRegIndex) {
4119 if (SubRegIndex == AMDGPU::NoSubRegister)
4120 return TargetFlags;
4121
4122 unsigned LoReloc, HiReloc;
4123 switch (TargetFlags & MO_MASK) {
4124 case MO_REL32_LO:
4125 case MO_REL32_HI:
4126 case MO_REL64:
4127 LoReloc = MO_REL32_LO;
4128 HiReloc = MO_REL32_HI;
4129 break;
4130 case MO_GOTPCREL32_LO:
4131 case MO_GOTPCREL32_HI:
4132 LoReloc = MO_GOTPCREL32_LO;
4133 HiReloc = MO_GOTPCREL32_HI;
4134 break;
4135 case MO_ABS32_LO:
4136 case MO_ABS32_HI:
4137 case MO_ABS64:
4138 LoReloc = MO_ABS32_LO;
4139 HiReloc = MO_ABS32_HI;
4140 break;
4141 default:
4142 return std::nullopt;
4143 }
4144
4145 const unsigned BaseFlags = TargetFlags & ~MO_MASK;
4146 switch (SubRegIndex) {
4147 case AMDGPU::sub0:
4148 return BaseFlags | LoReloc;
4149 case AMDGPU::sub1:
4150 return BaseFlags | HiReloc;
4151 default:
4152 return std::nullopt;
4153 }
4154}
4155
4156static unsigned getNewFMAAKInst(const GCNSubtarget &ST, unsigned Opc) {
4157 switch (Opc) {
4158 case AMDGPU::V_MAC_F16_e32:
4159 case AMDGPU::V_MAC_F16_e64:
4160 case AMDGPU::V_MAD_F16_e64:
4161 return AMDGPU::V_MADAK_F16;
4162 case AMDGPU::V_MAC_F32_e32:
4163 case AMDGPU::V_MAC_F32_e64:
4164 case AMDGPU::V_MAD_F32_e64:
4165 return AMDGPU::V_MADAK_F32;
4166 case AMDGPU::V_FMAC_F32_e32:
4167 case AMDGPU::V_FMAC_F32_e64:
4168 case AMDGPU::V_FMA_F32_e64:
4169 return AMDGPU::V_FMAAK_F32;
4170 case AMDGPU::V_FMAC_F16_e32:
4171 case AMDGPU::V_FMAC_F16_e64:
4172 case AMDGPU::V_FMAC_F16_t16_e64:
4173 case AMDGPU::V_FMAC_F16_fake16_e64:
4174 case AMDGPU::V_FMAC_F16_t16_e32:
4175 case AMDGPU::V_FMAC_F16_fake16_e32:
4176 case AMDGPU::V_FMA_F16_e64:
4177 return ST.hasTrue16BitInsts() ? ST.useRealTrue16Insts()
4178 ? AMDGPU::V_FMAAK_F16_t16
4179 : AMDGPU::V_FMAAK_F16_fake16
4180 : AMDGPU::V_FMAAK_F16;
4181 case AMDGPU::V_FMAC_F64_e32:
4182 case AMDGPU::V_FMAC_F64_e64:
4183 case AMDGPU::V_FMA_F64_e64:
4184 return AMDGPU::V_FMAAK_F64;
4185 default:
4186 llvm_unreachable("invalid instruction");
4187 }
4188}
4189
4190static unsigned getNewFMAMKInst(const GCNSubtarget &ST, unsigned Opc) {
4191 switch (Opc) {
4192 case AMDGPU::V_MAC_F16_e32:
4193 case AMDGPU::V_MAC_F16_e64:
4194 case AMDGPU::V_MAD_F16_e64:
4195 return AMDGPU::V_MADMK_F16;
4196 case AMDGPU::V_MAC_F32_e32:
4197 case AMDGPU::V_MAC_F32_e64:
4198 case AMDGPU::V_MAD_F32_e64:
4199 return AMDGPU::V_MADMK_F32;
4200 case AMDGPU::V_FMAC_F32_e32:
4201 case AMDGPU::V_FMAC_F32_e64:
4202 case AMDGPU::V_FMA_F32_e64:
4203 return AMDGPU::V_FMAMK_F32;
4204 case AMDGPU::V_FMAC_F16_e32:
4205 case AMDGPU::V_FMAC_F16_e64:
4206 case AMDGPU::V_FMAC_F16_t16_e64:
4207 case AMDGPU::V_FMAC_F16_fake16_e64:
4208 case AMDGPU::V_FMAC_F16_t16_e32:
4209 case AMDGPU::V_FMAC_F16_fake16_e32:
4210 case AMDGPU::V_FMA_F16_e64:
4211 return ST.hasTrue16BitInsts() ? ST.useRealTrue16Insts()
4212 ? AMDGPU::V_FMAMK_F16_t16
4213 : AMDGPU::V_FMAMK_F16_fake16
4214 : AMDGPU::V_FMAMK_F16;
4215 case AMDGPU::V_FMAC_F64_e32:
4216 case AMDGPU::V_FMAC_F64_e64:
4217 case AMDGPU::V_FMA_F64_e64:
4218 return AMDGPU::V_FMAMK_F64;
4219 default:
4220 llvm_unreachable("invalid instruction");
4221 }
4222}
4223
4224// Return true if \p Opc is a mad/fma family which can be converted to to a
4225// madmk/madak form with a folded literal constant.
4226static bool isMADFMA(unsigned Opc) {
4227 switch (Opc) {
4228 case AMDGPU::V_MAD_F32_e64:
4229 case AMDGPU::V_MAC_F32_e64:
4230 case AMDGPU::V_MAD_F16_e64:
4231 case AMDGPU::V_MAC_F16_e64:
4232 case AMDGPU::V_FMA_F32_e64:
4233 case AMDGPU::V_FMAC_F32_e64:
4234 case AMDGPU::V_FMA_F16_e64:
4235 case AMDGPU::V_FMAC_F16_e64:
4236 case AMDGPU::V_FMAC_F16_t16_e64:
4237 case AMDGPU::V_FMAC_F16_fake16_e64:
4238 case AMDGPU::V_FMA_F64_e64:
4239 case AMDGPU::V_FMAC_F64_e64:
4240 return true;
4241 default:
4242 return false;
4243 }
4244}
4245
4247 Register Reg, MachineRegisterInfo *MRI) const {
4248 int64_t Imm;
4249 if (!getConstValDefinedInReg(DefMI, Reg, Imm))
4250 return false;
4251
4252 const bool HasMultipleUses = !MRI->hasOneNonDBGUse(Reg);
4253
4254 assert(!DefMI.getOperand(0).getSubReg() && "Expected SSA form");
4255
4256 unsigned Opc = UseMI.getOpcode();
4257 if (Opc == AMDGPU::COPY) {
4258 assert(!UseMI.getOperand(0).getSubReg() && "Expected SSA form");
4259
4260 Register DstReg = UseMI.getOperand(0).getReg();
4261 Register UseSubReg = UseMI.getOperand(1).getSubReg();
4262
4263 const TargetRegisterClass *DstRC = RI.getRegClassForReg(*MRI, DstReg);
4264
4265 if (HasMultipleUses) {
4266 // TODO: This should fold in more cases with multiple use, but we need to
4267 // more carefully consider what those uses are.
4268 unsigned ImmDefSize = RI.getRegSizeInBits(*MRI->getRegClass(Reg));
4269
4270 // Avoid breaking up a 64-bit inline immediate into a subregister extract.
4271 if (UseSubReg != AMDGPU::NoSubRegister && ImmDefSize == 64)
4272 return false;
4273
4274 // Most of the time folding a 32-bit inline constant is free (though this
4275 // might not be true if we can't later fold it into a real user).
4276 //
4277 // FIXME: This isInlineConstant check is imprecise if
4278 // getConstValDefinedInReg handled the tricky non-mov cases.
4279 if (ImmDefSize == 32 &&
4281 return false;
4282 }
4283
4284 bool Is16Bit = UseSubReg != AMDGPU::NoSubRegister &&
4285 RI.getSubRegIdxSize(UseSubReg) == 16;
4286
4287 if (Is16Bit) {
4288 if (RI.hasVGPRs(DstRC))
4289 return false; // Do not clobber vgpr_hi16
4290
4291 if (DstReg.isVirtual() && UseSubReg != AMDGPU::lo16)
4292 return false;
4293 }
4294
4295 MachineFunction *MF = UseMI.getMF();
4296
4297 unsigned NewOpc = AMDGPU::INSTRUCTION_LIST_END;
4298 MCRegister MovDstPhysReg =
4299 DstReg.isPhysical() ? DstReg.asMCReg() : MCRegister();
4300
4301 std::optional<int64_t> SubRegImm = extractSubregFromImm(Imm, UseSubReg);
4302
4303 // TODO: Try to fold with AMDGPU::V_MOV_B16_t16_e64
4304 for (unsigned MovOp :
4305 {AMDGPU::S_MOV_B32, AMDGPU::V_MOV_B32_e32, AMDGPU::S_MOV_B64,
4306 AMDGPU::V_MOV_B64_PSEUDO, AMDGPU::V_ACCVGPR_WRITE_B32_e64}) {
4307 const MCInstrDesc &MovDesc = get(MovOp);
4308
4309 const TargetRegisterClass *MovDstRC = getRegClass(MovDesc, 0);
4310 if (Is16Bit) {
4311 // We just need to find a correctly sized register class, so the
4312 // subregister index compatibility doesn't matter since we're statically
4313 // extracting the immediate value.
4314 MovDstRC = RI.getMatchingSuperRegClass(MovDstRC, DstRC, AMDGPU::lo16);
4315 if (!MovDstRC)
4316 continue;
4317
4318 if (MovDstPhysReg) {
4319 // FIXME: We probably should not do this. If there is a live value in
4320 // the high half of the register, it will be corrupted.
4321 MovDstPhysReg =
4322 RI.getMatchingSuperReg(MovDstPhysReg, AMDGPU::lo16, MovDstRC);
4323 if (!MovDstPhysReg)
4324 continue;
4325 }
4326 }
4327
4328 // Result class isn't the right size, try the next instruction.
4329 if (MovDstPhysReg) {
4330 if (!MovDstRC->contains(MovDstPhysReg))
4331 return false;
4332 } else if (!MRI->constrainRegClass(DstReg, MovDstRC)) {
4333 // TODO: This will be overly conservative in the case of 16-bit virtual
4334 // SGPRs. We could hack up the virtual register uses to use a compatible
4335 // 32-bit class.
4336 continue;
4337 }
4338
4339 const MCOperandInfo &OpInfo = MovDesc.operands()[1];
4340
4341 // Ensure the interpreted immediate value is a valid operand in the new
4342 // mov.
4343 //
4344 // FIXME: isImmOperandLegal should have form that doesn't require existing
4345 // MachineInstr or MachineOperand
4346 if (!RI.opCanUseLiteralConstant(OpInfo.OperandType) &&
4347 !isInlineConstant(*SubRegImm, OpInfo.OperandType))
4348 break;
4349
4350 NewOpc = MovOp;
4351 break;
4352 }
4353
4354 if (NewOpc == AMDGPU::INSTRUCTION_LIST_END)
4355 return false;
4356
4357 if (Is16Bit) {
4358 UseMI.getOperand(0).setSubReg(AMDGPU::NoSubRegister);
4359 if (MovDstPhysReg)
4360 UseMI.getOperand(0).setReg(MovDstPhysReg);
4361 assert(UseMI.getOperand(1).getReg().isVirtual());
4362 }
4363
4364 const MCInstrDesc &NewMCID = get(NewOpc);
4365 UseMI.setDesc(NewMCID);
4366 UseMI.getOperand(1).ChangeToImmediate(*SubRegImm);
4367 UseMI.addImplicitDefUseOperands(*MF);
4368 return true;
4369 }
4370
4371 if (isMADFMA(Opc)) {
4372 if (HasMultipleUses)
4373 return false;
4374
4375 // Don't fold if we are using source or output modifiers. The new VOP2
4376 // instructions don't have them.
4378 return false;
4379
4380 // If this is a free constant, there's no reason to do this.
4381 // TODO: We could fold this here instead of letting SIFoldOperands do it
4382 // later.
4383 int Src0Idx = getNamedOperandIdx(UseMI.getOpcode(), AMDGPU::OpName::src0);
4384
4385 // Any src operand can be used for the legality check.
4386 if (isInlineConstant(UseMI, Src0Idx, Imm))
4387 return false;
4388
4389 MachineOperand *Src0 = &UseMI.getOperand(Src0Idx);
4390
4391 MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
4392 MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
4393
4394 auto CopyRegOperandToNarrowerRC =
4395 [MRI, this](MachineInstr &MI, unsigned OpNo,
4396 const TargetRegisterClass *NewRC) -> void {
4397 if (!MI.getOperand(OpNo).isReg())
4398 return;
4399 Register Reg = MI.getOperand(OpNo).getReg();
4400 const TargetRegisterClass *RC = RI.getRegClassForReg(*MRI, Reg);
4401 if (RI.getCommonSubClass(RC, NewRC) != NewRC)
4402 return;
4403 Register Tmp = MRI->createVirtualRegister(NewRC);
4404 BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
4405 get(AMDGPU::COPY), Tmp)
4406 .addReg(Reg);
4407 MI.getOperand(OpNo).setReg(Tmp);
4408 };
4409
4410 // Multiplied part is the constant: Use v_madmk_{f16, f32}.
4411 if ((Src0->isReg() && Src0->getReg() == Reg) ||
4412 (Src1->isReg() && Src1->getReg() == Reg)) {
4413 MachineOperand *RegSrc =
4414 Src1->isReg() && Src1->getReg() == Reg ? Src0 : Src1;
4415 if (!RegSrc->isReg())
4416 return false;
4417 if (RI.isSGPRClass(MRI->getRegClass(RegSrc->getReg())) &&
4418 ST.getConstantBusLimit(Opc) < 2)
4419 return false;
4420
4421 if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
4422 return false;
4423
4424 // If src2 is also a literal constant then we have to choose which one to
4425 // fold. In general it is better to choose madak so that the other literal
4426 // can be materialized in an sgpr instead of a vgpr:
4427 // s_mov_b32 s0, literal
4428 // v_madak_f32 v0, s0, v0, literal
4429 // Instead of:
4430 // v_mov_b32 v1, literal
4431 // v_madmk_f32 v0, v0, literal, v1
4432 MachineInstr *Def = MRI->getUniqueVRegDef(Src2->getReg());
4433 if (Def && Def->isMoveImmediate() &&
4434 !isInlineConstant(Def->getOperand(1)))
4435 return false;
4436
4437 unsigned NewOpc = getNewFMAMKInst(ST, Opc);
4438 if (pseudoToMCOpcode(NewOpc) == -1)
4439 return false;
4440
4441 const std::optional<int64_t> SubRegImm = extractSubregFromImm(
4442 Imm, RegSrc == Src1 ? Src0->getSubReg() : Src1->getSubReg());
4443
4444 // FIXME: This would be a lot easier if we could return a new instruction
4445 // instead of having to modify in place.
4446
4447 Register SrcReg = RegSrc->getReg();
4448 unsigned SrcSubReg = RegSrc->getSubReg();
4449 Src0->setReg(SrcReg);
4450 Src0->setSubReg(SrcSubReg);
4451 Src0->setIsKill(RegSrc->isKill());
4452
4453 if (Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
4454 Opc == AMDGPU::V_FMAC_F32_e64 || Opc == AMDGPU::V_FMAC_F16_t16_e64 ||
4455 Opc == AMDGPU::V_FMAC_F16_fake16_e64 ||
4456 Opc == AMDGPU::V_FMAC_F16_e64 || Opc == AMDGPU::V_FMAC_F64_e64)
4457 UseMI.untieRegOperand(
4458 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
4459
4460 Src1->ChangeToImmediate(*SubRegImm);
4461
4463 UseMI.setDesc(get(NewOpc));
4464
4465 if (NewOpc == AMDGPU::V_FMAMK_F16_t16 ||
4466 NewOpc == AMDGPU::V_FMAMK_F16_fake16) {
4467 const TargetRegisterClass *NewRC = getRegClass(get(NewOpc), 0);
4468 Register Tmp = MRI->createVirtualRegister(NewRC);
4469 BuildMI(*UseMI.getParent(), std::next(UseMI.getIterator()),
4470 UseMI.getDebugLoc(), get(AMDGPU::COPY),
4471 UseMI.getOperand(0).getReg())
4472 .addReg(Tmp);
4473 UseMI.getOperand(0).setReg(Tmp);
4474 CopyRegOperandToNarrowerRC(UseMI, 1, NewRC);
4475 CopyRegOperandToNarrowerRC(UseMI, 3, NewRC);
4476 }
4477
4478 bool DeleteDef = MRI->use_nodbg_empty(Reg);
4479 if (DeleteDef)
4480 DefMI.eraseFromParent();
4481
4482 return true;
4483 }
4484
4485 // Added part is the constant: Use v_madak_{f16, f32}.
4486 if (Src2->isReg() && Src2->getReg() == Reg) {
4487 if (ST.getConstantBusLimit(Opc) < 2) {
4488 // Not allowed to use constant bus for another operand.
4489 // We can however allow an inline immediate as src0.
4490 bool Src0Inlined = false;
4491 if (Src0->isReg()) {
4492 // Try to inline constant if possible.
4493 // If the Def moves immediate and the use is single
4494 // We are saving VGPR here.
4495 MachineInstr *Def = MRI->getUniqueVRegDef(Src0->getReg());
4496 if (Def && Def->isMoveImmediate() &&
4497 isInlineConstant(Def->getOperand(1)) &&
4498 MRI->hasOneNonDBGUse(Src0->getReg())) {
4499 Src0->ChangeToImmediate(Def->getOperand(1).getImm());
4500 Src0Inlined = true;
4501 } else if (ST.getConstantBusLimit(Opc) <= 1 &&
4502 RI.isSGPRReg(*MRI, Src0->getReg())) {
4503 return false;
4504 }
4505 // VGPR is okay as Src0 - fallthrough
4506 }
4507
4508 if (Src1->isReg() && !Src0Inlined) {
4509 // We have one slot for inlinable constant so far - try to fill it
4510 MachineInstr *Def = MRI->getUniqueVRegDef(Src1->getReg());
4511 if (Def && Def->isMoveImmediate() &&
4512 isInlineConstant(Def->getOperand(1)) &&
4513 MRI->hasOneNonDBGUse(Src1->getReg()) && commuteInstruction(UseMI))
4514 Src0->ChangeToImmediate(Def->getOperand(1).getImm());
4515 else if (RI.isSGPRReg(*MRI, Src1->getReg()))
4516 return false;
4517 // VGPR is okay as Src1 - fallthrough
4518 }
4519 }
4520
4521 unsigned NewOpc = getNewFMAAKInst(ST, Opc);
4522 if (pseudoToMCOpcode(NewOpc) == -1)
4523 return false;
4524
4525 // FIXME: This would be a lot easier if we could return a new instruction
4526 // instead of having to modify in place.
4527
4528 if (Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
4529 Opc == AMDGPU::V_FMAC_F32_e64 || Opc == AMDGPU::V_FMAC_F16_t16_e64 ||
4530 Opc == AMDGPU::V_FMAC_F16_fake16_e64 ||
4531 Opc == AMDGPU::V_FMAC_F16_e64 || Opc == AMDGPU::V_FMAC_F64_e64)
4532 UseMI.untieRegOperand(
4533 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
4534
4535 const std::optional<int64_t> SubRegImm =
4536 extractSubregFromImm(Imm, Src2->getSubReg());
4537
4538 // ChangingToImmediate adds Src2 back to the instruction.
4539 Src2->ChangeToImmediate(*SubRegImm);
4540
4541 // These come before src2.
4543 UseMI.setDesc(get(NewOpc));
4544
4545 if (NewOpc == AMDGPU::V_FMAAK_F16_t16 ||
4546 NewOpc == AMDGPU::V_FMAAK_F16_fake16) {
4547 const TargetRegisterClass *NewRC = getRegClass(get(NewOpc), 0);
4548 Register Tmp = MRI->createVirtualRegister(NewRC);
4549 BuildMI(*UseMI.getParent(), std::next(UseMI.getIterator()),
4550 UseMI.getDebugLoc(), get(AMDGPU::COPY),
4551 UseMI.getOperand(0).getReg())
4552 .addReg(Tmp);
4553 UseMI.getOperand(0).setReg(Tmp);
4554 CopyRegOperandToNarrowerRC(UseMI, 1, NewRC);
4555 CopyRegOperandToNarrowerRC(UseMI, 2, NewRC);
4556 }
4557
4558 // It might happen that UseMI was commuted
4559 // and we now have SGPR as SRC1. If so 2 inlined
4560 // constant and SGPR are illegal.
4562
4563 int NewSrc0Idx =
4564 AMDGPU::getNamedOperandIdx(UseMI.getOpcode(), AMDGPU::OpName::src0);
4565 if (!isOperandLegal(UseMI, NewSrc0Idx))
4566 legalizeOpWithMove(UseMI, NewSrc0Idx);
4567
4568 bool DeleteDef = MRI->use_nodbg_empty(Reg);
4569 if (DeleteDef)
4570 DefMI.eraseFromParent();
4571
4572 return true;
4573 }
4574
4575 return false;
4576 }
4577
4578 // Early exit for generic instructions which will never fold an immediate.
4579 if (!isTargetSpecificOpcode(UseMI.getOpcode()))
4580 return false;
4581
4582 // Directly fold inline immediates into the uses. These should be free-ish
4583 // regardless of the uses.
4584 bool FoldedInlineImm = false;
4585
4586 for (MachineOperand &UseMO : UseMI.explicit_uses()) {
4587 if (!UseMO.isReg() || UseMO.getReg() != Reg || UseMO.isTied())
4588 continue;
4589
4590 unsigned UseOpIdx = UseMO.getOperandNo();
4591
4592 int64_t ImmVal = Imm;
4593 if (unsigned UseSubReg = UseMO.getSubReg()) {
4594 std::optional<int64_t> SubImm = extractSubregFromImm(Imm, UseSubReg);
4595 if (!SubImm)
4596 continue;
4597 ImmVal = *SubImm;
4598 }
4599
4600 if (!isInlineConstant(UseMI, UseOpIdx, ImmVal) ||
4601 !isImmEquivalentToReg(UseMI, UseOpIdx, ImmVal))
4602 continue;
4603
4605 if (!isOperandLegal(UseMI, UseOpIdx, &ImmOp))
4606 continue;
4607
4608 UseMO.ChangeToImmediate(ImmVal);
4609 FoldedInlineImm = true;
4610 }
4611
4612 // TODO: Consider applying tryConstantFoldOp here
4613 return FoldedInlineImm;
4614}
4615
4616static bool
4619 if (BaseOps1.size() != BaseOps2.size())
4620 return false;
4621 for (size_t I = 0, E = BaseOps1.size(); I < E; ++I) {
4622 if (!BaseOps1[I]->isIdenticalTo(*BaseOps2[I]))
4623 return false;
4624 }
4625 return true;
4626}
4627
4628static bool offsetsDoNotOverlap(LocationSize WidthA, int OffsetA,
4629 LocationSize WidthB, int OffsetB) {
4630 int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
4631 int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
4632 LocationSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
4633 return LowWidth.hasValue() &&
4634 LowOffset + (int)LowWidth.getValue() <= HighOffset;
4635}
4636
4637bool SIInstrInfo::checkInstOffsetsDoNotOverlap(const MachineInstr &MIa,
4638 const MachineInstr &MIb) const {
4639 SmallVector<const MachineOperand *, 4> BaseOps0, BaseOps1;
4640 int64_t Offset0, Offset1;
4641 LocationSize Dummy0 = LocationSize::precise(0);
4642 LocationSize Dummy1 = LocationSize::precise(0);
4643 bool Offset0IsScalable, Offset1IsScalable;
4644 if (!getMemOperandsWithOffsetWidth(MIa, BaseOps0, Offset0, Offset0IsScalable,
4645 Dummy0) ||
4646 !getMemOperandsWithOffsetWidth(MIb, BaseOps1, Offset1, Offset1IsScalable,
4647 Dummy1))
4648 return false;
4649
4650 if (!memOpsHaveSameBaseOperands(BaseOps0, BaseOps1))
4651 return false;
4652
4653 if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
4654 // FIXME: Handle ds_read2 / ds_write2.
4655 return false;
4656 }
4657 LocationSize Width0 = MIa.memoperands().front()->getSize();
4658 LocationSize Width1 = MIb.memoperands().front()->getSize();
4659 return offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1);
4660}
4661
4663 const MachineInstr &MIb) const {
4664 assert(MIa.mayLoadOrStore() &&
4665 "MIa must load from or modify a memory location");
4666 assert(MIb.mayLoadOrStore() &&
4667 "MIb must load from or modify a memory location");
4668
4670 return false;
4671
4672 // XXX - Can we relax this between address spaces?
4673 if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
4674 return false;
4675
4676 if (isLDSDMA(MIa) || isLDSDMA(MIb))
4677 return false;
4678
4679 if (MIa.isBundle() || MIb.isBundle())
4680 return false;
4681
4682 // These only alias each other, and only on overlapping dword ranges.
4683 const bool IsLdStIdxA = isa<AMDGPUMI::VLoadStoreIdxInst>(MIa);
4684 const bool IsLdStIdxB = isa<AMDGPUMI::VLoadStoreIdxInst>(MIb);
4685 if (IsLdStIdxA || IsLdStIdxB) {
4686 if (IsLdStIdxA && IsLdStIdxB)
4687 return checkInstOffsetsDoNotOverlap(MIa, MIb);
4688 return true;
4689 }
4690
4691 // TODO: Should we check the address space from the MachineMemOperand? That
4692 // would allow us to distinguish objects we know don't alias based on the
4693 // underlying address space, even if it was lowered to a different one,
4694 // e.g. private accesses lowered to use MUBUF instructions on a scratch
4695 // buffer.
4696 if (isDS(MIa)) {
4697 if (isDS(MIb))
4698 return checkInstOffsetsDoNotOverlap(MIa, MIb);
4699
4700 return !isFLAT(MIb) || isSegmentSpecificFLAT(MIb);
4701 }
4702
4703 if (isMUBUF(MIa) || isMTBUF(MIa)) {
4704 if (isMUBUF(MIb) || isMTBUF(MIb))
4705 return checkInstOffsetsDoNotOverlap(MIa, MIb);
4706
4707 if (isFLAT(MIb))
4708 return isFLATScratch(MIb);
4709
4710 return !isSMRD(MIb);
4711 }
4712
4713 if (isSMRD(MIa)) {
4714 if (isSMRD(MIb))
4715 return checkInstOffsetsDoNotOverlap(MIa, MIb);
4716
4717 if (isFLAT(MIb))
4718 return isFLATScratch(MIb);
4719
4720 return !isMUBUF(MIb) && !isMTBUF(MIb);
4721 }
4722
4723 if (isFLAT(MIa)) {
4724 if (isFLAT(MIb)) {
4725 if ((isFLATScratch(MIa) && isFLATGlobal(MIb)) ||
4726 (isFLATGlobal(MIa) && isFLATScratch(MIb)))
4727 return true;
4728
4729 return checkInstOffsetsDoNotOverlap(MIa, MIb);
4730 }
4731
4732 return false;
4733 }
4734
4735 return false;
4736}
4737
4738static unsigned getNewFMAInst(const GCNSubtarget &ST, unsigned Opc) {
4739 switch (Opc) {
4740 case AMDGPU::V_MAC_F16_e32:
4741 case AMDGPU::V_MAC_F16_e64:
4742 return AMDGPU::V_MAD_F16_e64;
4743 case AMDGPU::V_MAC_F32_e32:
4744 case AMDGPU::V_MAC_F32_e64:
4745 return AMDGPU::V_MAD_F32_e64;
4746 case AMDGPU::V_MAC_LEGACY_F32_e32:
4747 case AMDGPU::V_MAC_LEGACY_F32_e64:
4748 return AMDGPU::V_MAD_LEGACY_F32_e64;
4749 case AMDGPU::V_FMAC_LEGACY_F32_e32:
4750 case AMDGPU::V_FMAC_LEGACY_F32_e64:
4751 return AMDGPU::V_FMA_LEGACY_F32_e64;
4752 case AMDGPU::V_FMAC_F16_e32:
4753 case AMDGPU::V_FMAC_F16_e64:
4754 case AMDGPU::V_FMAC_F16_t16_e64:
4755 case AMDGPU::V_FMAC_F16_fake16_e64:
4756 return ST.hasTrue16BitInsts() ? ST.useRealTrue16Insts()
4757 ? AMDGPU::V_FMA_F16_gfx9_t16_e64
4758 : AMDGPU::V_FMA_F16_gfx9_fake16_e64
4759 : AMDGPU::V_FMA_F16_gfx9_e64;
4760 case AMDGPU::V_FMAC_F32_e32:
4761 case AMDGPU::V_FMAC_F32_e64:
4762 return AMDGPU::V_FMA_F32_e64;
4763 case AMDGPU::V_FMAC_F64_e32:
4764 case AMDGPU::V_FMAC_F64_e64:
4765 return AMDGPU::V_FMA_F64_e64;
4766 default:
4767 llvm_unreachable("invalid instruction");
4768 }
4769}
4770
4771/// Helper struct for the implementation of 3-address conversion to communicate
4772/// updates made to instruction operands.
4774 /// Other instruction whose def is no longer used by the converted
4775 /// instruction.
4777};
4778
4780 LiveIntervals *LIS) const {
4781 MachineBasicBlock &MBB = *MI.getParent();
4782 MachineInstr *CandidateMI = &MI;
4783
4784 if (MI.isBundle()) {
4785 // This is a temporary placeholder for bundle handling that enables us to
4786 // exercise the relevant code paths in the two-address instruction pass.
4787 if (MI.getBundleSize() != 1)
4788 return nullptr;
4789 CandidateMI = MI.getNextNode();
4790 }
4791
4793 MachineInstr *NewMI = convertToThreeAddressImpl(*CandidateMI, U);
4794 if (!NewMI)
4795 return nullptr;
4796
4797 if (MI.isBundle()) {
4798 CandidateMI->eraseFromBundle();
4799
4800 for (MachineOperand &MO : MI.all_defs()) {
4801 if (MO.isTied())
4802 MI.untieRegOperand(MO.getOperandNo());
4803 }
4804 } else {
4805 if (LIS) {
4806 LIS->ReplaceMachineInstrInMaps(MI, *NewMI);
4807 // SlotIndex of defs needs to be updated when converting to early-clobber
4808 MachineOperand &Def = NewMI->getOperand(0);
4809 if (Def.isEarlyClobber() && Def.isReg() &&
4810 LIS->hasInterval(Def.getReg())) {
4811 SlotIndex OldIndex = LIS->getInstructionIndex(*NewMI).getRegSlot(false);
4812 SlotIndex NewIndex = LIS->getInstructionIndex(*NewMI).getRegSlot(true);
4813 auto &LI = LIS->getInterval(Def.getReg());
4814 auto UpdateDefIndex = [&](LiveRange &LR) {
4815 auto *S = LR.find(OldIndex);
4816 if (S != LR.end() && S->start == OldIndex) {
4817 assert(S->valno && S->valno->def == OldIndex);
4818 S->start = NewIndex;
4819 S->valno->def = NewIndex;
4820 }
4821 };
4822 UpdateDefIndex(LI);
4823 for (auto &SR : LI.subranges())
4824 UpdateDefIndex(SR);
4825 }
4826
4827 // A use tied to an early-clobber def is read at the early-clobber slot.
4828 // The three-address instruction has no tied operands, so the use is now
4829 // read at the register slot.
4830 const MachineOperand &OldDef = MI.getOperand(0);
4831 if (OldDef.isEarlyClobber()) {
4832 assert(OldDef.isTied() &&
4833 "expected a tied def in the two-address form");
4835 MI.getOperand(MI.findTiedOperandIdx(OldDef.getOperandNo()))
4836 .getReg();
4837 SlotIndex Idx = LIS->getInstructionIndex(*NewMI);
4838 SlotIndex OldEnd = Idx.getRegSlot(true);
4839 SlotIndex NewEnd = Idx.getRegSlot();
4840 auto UpdateUseIndex = [&](LiveRange &LR) {
4841 LiveRange::Segment *S = LR.getSegmentContaining(Idx);
4842 if (S && S->end == OldEnd)
4843 S->end = NewEnd;
4844 };
4845 LiveInterval &LI = LIS->getInterval(UseReg);
4846 UpdateUseIndex(LI);
4847 for (LiveInterval::SubRange &SR : LI.subranges())
4848 UpdateUseIndex(SR);
4849 }
4850 }
4851 }
4852
4853 if (U.RemoveMIUse) {
4854 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4855 // The only user is the instruction which will be killed.
4856 Register DefReg = U.RemoveMIUse->getOperand(0).getReg();
4857
4858 if (MRI.hasOneNonDBGUse(DefReg)) {
4859 // We cannot just remove the DefMI here, calling pass will crash.
4860 U.RemoveMIUse->setDesc(get(AMDGPU::IMPLICIT_DEF));
4861 U.RemoveMIUse->getOperand(0).setIsDead(true);
4862 for (unsigned I = U.RemoveMIUse->getNumOperands() - 1; I != 0; --I)
4863 U.RemoveMIUse->removeOperand(I);
4864 }
4865
4866 if (MI.isBundle()) {
4867 VirtRegInfo VRI = AnalyzeVirtRegInBundle(MI, DefReg);
4868 if (!VRI.Reads && !VRI.Writes) {
4869 for (MachineOperand &MO : MI.all_uses()) {
4870 if (MO.isReg() && MO.getReg() == DefReg) {
4871 assert(MO.getSubReg() == 0 &&
4872 "tied sub-registers in bundles currently not supported");
4873 MI.removeOperand(MO.getOperandNo());
4874 break;
4875 }
4876 }
4877
4878 if (LIS)
4879 LIS->shrinkToUses(&LIS->getInterval(DefReg));
4880 }
4881 } else if (LIS) {
4882 LiveInterval &DefLI = LIS->getInterval(DefReg);
4883
4884 // We cannot delete the original instruction here, so hack out the use
4885 // in the original instruction with a dummy register so we can use
4886 // shrinkToUses to deal with any multi-use edge cases. Other targets do
4887 // not have the complexity of deleting a use to consider here.
4888 Register DummyReg = MRI.cloneVirtualRegister(DefReg);
4889 for (MachineOperand &MIOp : MI.uses()) {
4890 if (MIOp.isReg() && MIOp.getReg() == DefReg) {
4891 MIOp.setIsUndef(true);
4892 MIOp.setReg(DummyReg);
4893 }
4894 }
4895
4896 if (MI.isBundle()) {
4897 VirtRegInfo VRI = AnalyzeVirtRegInBundle(MI, DefReg);
4898 if (!VRI.Reads && !VRI.Writes) {
4899 for (MachineOperand &MIOp : MI.uses()) {
4900 if (MIOp.isReg() && MIOp.getReg() == DefReg) {
4901 MIOp.setIsUndef(true);
4902 MIOp.setReg(DummyReg);
4903 }
4904 }
4905 }
4906
4907 MI.addOperand(MachineOperand::CreateReg(DummyReg, false, false, false,
4908 false, /*isUndef=*/true));
4909 }
4910
4911 LIS->shrinkToUses(&DefLI);
4912 }
4913 }
4914
4915 return MI.isBundle() ? &MI : NewMI;
4916}
4917
4919SIInstrInfo::convertToThreeAddressImpl(MachineInstr &MI,
4920 ThreeAddressUpdates &U) const {
4921 MachineBasicBlock &MBB = *MI.getParent();
4922 unsigned Opc = MI.getOpcode();
4923
4924 // Handle MFMA.
4925 int NewMFMAOpc = AMDGPU::getMFMAEarlyClobberOp(Opc);
4926 if (NewMFMAOpc != -1) {
4928 BuildMI(MBB, MI, MI.getDebugLoc(), get(NewMFMAOpc));
4929 for (unsigned I = 0, E = MI.getNumExplicitOperands(); I != E; ++I)
4930 MIB.add(MI.getOperand(I));
4931 return MIB;
4932 }
4933
4934 if (SIInstrInfo::isWMMA(MI)) {
4935 unsigned NewOpc = AMDGPU::mapWMMA2AddrTo3AddrOpcode(MI.getOpcode());
4936 MachineInstrBuilder MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
4937 .setMIFlags(MI.getFlags());
4938 for (unsigned I = 0, E = MI.getNumExplicitOperands(); I != E; ++I)
4939 MIB->addOperand(MI.getOperand(I));
4940 return MIB;
4941 }
4942
4943 assert(Opc != AMDGPU::V_FMAC_F16_t16_e32 &&
4944 Opc != AMDGPU::V_FMAC_F16_fake16_e32 &&
4945 "V_FMAC_F16_t16/fake16_e32 is not supported and not expected to be "
4946 "present pre-RA");
4947
4948 // Handle MAC/FMAC.
4949 bool IsF64 = Opc == AMDGPU::V_FMAC_F64_e32 || Opc == AMDGPU::V_FMAC_F64_e64;
4950 bool IsLegacy = Opc == AMDGPU::V_MAC_LEGACY_F32_e32 ||
4951 Opc == AMDGPU::V_MAC_LEGACY_F32_e64 ||
4952 Opc == AMDGPU::V_FMAC_LEGACY_F32_e32 ||
4953 Opc == AMDGPU::V_FMAC_LEGACY_F32_e64;
4954 bool Src0Literal = false;
4955
4956 switch (Opc) {
4957 default:
4958 return nullptr;
4959 case AMDGPU::V_MAC_F16_e64:
4960 case AMDGPU::V_FMAC_F16_e64:
4961 case AMDGPU::V_FMAC_F16_t16_e64:
4962 case AMDGPU::V_FMAC_F16_fake16_e64:
4963 case AMDGPU::V_MAC_F32_e64:
4964 case AMDGPU::V_MAC_LEGACY_F32_e64:
4965 case AMDGPU::V_FMAC_F32_e64:
4966 case AMDGPU::V_FMAC_LEGACY_F32_e64:
4967 case AMDGPU::V_FMAC_F64_e64:
4968 break;
4969 case AMDGPU::V_MAC_F16_e32:
4970 case AMDGPU::V_FMAC_F16_e32:
4971 case AMDGPU::V_MAC_F32_e32:
4972 case AMDGPU::V_MAC_LEGACY_F32_e32:
4973 case AMDGPU::V_FMAC_F32_e32:
4974 case AMDGPU::V_FMAC_LEGACY_F32_e32:
4975 case AMDGPU::V_FMAC_F64_e32: {
4976 int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
4977 AMDGPU::OpName::src0);
4978 const MachineOperand *Src0 = &MI.getOperand(Src0Idx);
4979 if (!Src0->isReg() && !Src0->isImm())
4980 return nullptr;
4981
4982 if (Src0->isImm() && !isInlineConstant(MI, Src0Idx, *Src0))
4983 Src0Literal = true;
4984
4985 break;
4986 }
4987 }
4988
4989 MachineInstrBuilder MIB;
4990 const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4991 const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
4992 const MachineOperand *Src0Mods =
4993 getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
4994 const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
4995 const MachineOperand *Src1Mods =
4996 getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
4997 const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
4998 const MachineOperand *Src2Mods =
4999 getNamedOperand(MI, AMDGPU::OpName::src2_modifiers);
5000 const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
5001 const MachineOperand *Omod = getNamedOperand(MI, AMDGPU::OpName::omod);
5002 const MachineOperand *OpSel = getNamedOperand(MI, AMDGPU::OpName::op_sel);
5003
5004 if (!Src0Mods && !Src1Mods && !Src2Mods && !Clamp && !Omod && !IsLegacy &&
5005 (!IsF64 || ST.hasFmaakFmamkF64Insts()) &&
5006 // If we have an SGPR input, we will violate the constant bus restriction.
5007 (ST.getConstantBusLimit(Opc) > 1 || !Src0->isReg() ||
5008 !RI.isSGPRReg(MBB.getParent()->getRegInfo(), Src0->getReg()))) {
5009 MachineInstr *DefMI = nullptr;
5010 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5011 std::optional<int64_t> ImmOpt;
5012 int64_t Imm;
5013
5014 if (!Src0Literal &&
5015 (ImmOpt = getImmOrMaterializedImm(MRI, *Src2, &DefMI))) {
5016 unsigned NewOpc = getNewFMAAKInst(ST, Opc);
5017 if (pseudoToMCOpcode(NewOpc) != -1) {
5018 MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
5019 .add(*Dst)
5020 .add(*Src0)
5021 .add(*Src1)
5022 .addImm(*ImmOpt)
5023 .setMIFlags(MI.getFlags());
5024 U.RemoveMIUse = DefMI;
5025 return MIB;
5026 }
5027 }
5028 unsigned NewOpc = getNewFMAMKInst(ST, Opc);
5029 if (!Src0Literal &&
5030 (ImmOpt = getImmOrMaterializedImm(MRI, *Src1, &DefMI))) {
5031 if (pseudoToMCOpcode(NewOpc) != -1) {
5032 MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
5033 .add(*Dst)
5034 .add(*Src0)
5035 .addImm(*ImmOpt)
5036 .add(*Src2)
5037 .setMIFlags(MI.getFlags());
5038 U.RemoveMIUse = DefMI;
5039 return MIB;
5040 }
5041 }
5042 if ((ImmOpt = getImmOrMaterializedImm(MRI, *Src0, &DefMI))) {
5043 Imm = *ImmOpt;
5044 if (pseudoToMCOpcode(NewOpc) != -1 &&
5046 MI, AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::src0),
5047 Src1)) {
5048 MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
5049 .add(*Dst)
5050 .add(*Src1)
5051 .addImm(Imm)
5052 .add(*Src2)
5053 .setMIFlags(MI.getFlags());
5054 U.RemoveMIUse = DefMI;
5055 return MIB;
5056 }
5057 }
5058 }
5059
5060 // VOP2 mac/fmac with a literal operand cannot be converted to VOP3 mad/fma
5061 // if VOP3 does not allow a literal operand.
5062 if (Src0Literal && !ST.hasVOP3Literal())
5063 return nullptr;
5064
5065 unsigned NewOpc = getNewFMAInst(ST, Opc);
5066
5067 if (pseudoToMCOpcode(NewOpc) == -1)
5068 return nullptr;
5069
5070 MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
5071 .add(*Dst)
5072 .addImm(Src0Mods ? Src0Mods->getImm() : 0)
5073 .add(*Src0)
5074 .addImm(Src1Mods ? Src1Mods->getImm() : 0)
5075 .add(*Src1)
5076 .addImm(Src2Mods ? Src2Mods->getImm() : 0)
5077 .add(*Src2)
5078 .addImm(Clamp ? Clamp->getImm() : 0)
5079 .addImm(Omod ? Omod->getImm() : 0)
5080 .setMIFlags(MI.getFlags());
5081 if (AMDGPU::hasNamedOperand(NewOpc, AMDGPU::OpName::op_sel))
5082 MIB.addImm(OpSel ? OpSel->getImm() : 0);
5083 return MIB;
5084}
5085
5086// It's not generally safe to move VALU instructions across these since it will
5087// start using the register as a base index rather than directly.
5088// XXX - Why isn't hasSideEffects sufficient for these?
5090 switch (MI.getOpcode()) {
5091 case AMDGPU::S_SET_GPR_IDX_ON:
5092 case AMDGPU::S_SET_GPR_IDX_MODE:
5093 case AMDGPU::S_SET_GPR_IDX_OFF:
5094 return true;
5095 default:
5096 return false;
5097 }
5098}
5099
5101 const MachineBasicBlock *MBB,
5102 const MachineFunction &MF) const {
5103 // Skipping the check for SP writes in the base implementation. The reason it
5104 // was added was apparently due to compile time concerns.
5105 //
5106 // TODO: Do we really want this barrier? It triggers unnecessary hazard nops
5107 // but is probably avoidable.
5108
5109 // Copied from base implementation.
5110 // Terminators and labels can't be scheduled around.
5111 if (MI.isTerminator() || MI.isPosition())
5112 return true;
5113
5114 // INLINEASM_BR can jump to another block
5115 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
5116 return true;
5117
5118 if (MI.getOpcode() == AMDGPU::SCHED_BARRIER && MI.getOperand(0).getImm() == 0)
5119 return true;
5120
5121 // Target-independent instructions do not have an implicit-use of EXEC, even
5122 // when they operate on VGPRs. Treating EXEC modifications as scheduling
5123 // boundaries prevents incorrect movements of such instructions.
5124 return MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
5125 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
5126 MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
5127 MI.getOpcode() == AMDGPU::S_SETPRIO ||
5128 MI.getOpcode() == AMDGPU::S_SETPRIO_INC_WG ||
5130}
5131
5133 return Opcode == AMDGPU::DS_ORDERED_COUNT ||
5134 Opcode == AMDGPU::DS_ADD_GS_REG_RTN ||
5135 Opcode == AMDGPU::DS_SUB_GS_REG_RTN || isGWS(Opcode);
5136}
5137
5139 // Instructions that access scratch use FLAT encoding or BUF encodings.
5140 if ((!isFLAT(MI) || isFLATGlobal(MI)) && !isBUF(MI))
5141 return false;
5142
5143 // SCRATCH instructions always access scratch.
5144 if (isFLATScratch(MI))
5145 return true;
5146
5147 // If FLAT_SCRATCH registers are not initialized, we can never access scratch
5148 // via the aperture.
5149 if (MI.getMF()->getFunction().hasFnAttribute("amdgpu-no-flat-scratch-init"))
5150 return false;
5151
5152 // If there are no memory operands then conservatively assume the flat
5153 // operation may access scratch.
5154 if (MI.memoperands_empty())
5155 return true;
5156
5157 // See if any memory operand specifies an address space that involves scratch.
5158 return any_of(MI.memoperands(), [](const MachineMemOperand *Memop) {
5159 unsigned AS = Memop->getAddrSpace();
5160 if (AS == AMDGPUAS::FLAT_ADDRESS) {
5161 const MDNode *MD = Memop->getAAInfo().NoAliasAddrSpace;
5162 return !MD || !AMDGPU::hasValueInRangeLikeMetadata(
5163 *MD, AMDGPUAS::PRIVATE_ADDRESS);
5164 }
5165 return AS == AMDGPUAS::PRIVATE_ADDRESS;
5166 });
5167}
5168
5170 assert(isFLAT(MI));
5171
5172 // All flat instructions use the VMEM counter except prefetch.
5173 if (!usesVM_CNT(MI))
5174 return false;
5175
5176 // If there are no memory operands then conservatively assume the flat
5177 // operation may access VMEM.
5178 if (MI.memoperands_empty())
5179 return true;
5180
5181 // See if any memory operand specifies an address space that involves VMEM.
5182 // Flat operations only supported FLAT, LOCAL (LDS), or address spaces
5183 // involving VMEM such as GLOBAL, CONSTANT, PRIVATE (SCRATCH), etc. The REGION
5184 // (GDS) address space is not supported by flat operations. Therefore, simply
5185 // return true unless only the LDS address space is found.
5186 for (const MachineMemOperand *Memop : MI.memoperands()) {
5187 unsigned AS = Memop->getAddrSpace();
5189 if (AS != AMDGPUAS::LOCAL_ADDRESS)
5190 return true;
5191 }
5192
5193 return false;
5194}
5195
5197 bool TgSplit) const {
5198 assert(isFLAT(MI));
5199
5200 // Flat instruction such as SCRATCH and GLOBAL do not use the lgkm counter.
5201 if (!usesLGKM_CNT(MI))
5202 return false;
5203
5204 // If in tgsplit mode then there can be no use of LDS.
5205 if (TgSplit)
5206 return false;
5207
5208 // If there are no memory operands then conservatively assume the flat
5209 // operation may access LDS.
5210 if (MI.memoperands_empty())
5211 return true;
5212
5213 // See if any memory operand specifies an address space that involves LDS.
5214 for (const MachineMemOperand *Memop : MI.memoperands()) {
5215 unsigned AS = Memop->getAddrSpace();
5217 return true;
5218 }
5219
5220 return false;
5221}
5222
5224 if (!isAsync(MI))
5226 if (usesTENSOR_CNT(MI))
5228 if (!usesASYNC_CNT(MI))
5230
5231 // TODO: Declare the stage of each async instruction in TableGen alongside
5232 // its definition, instead of listing opcodes here.
5233 switch (MI.getOpcode()) {
5234 // Keep in sync with FLATInstructions.td.
5235 case AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B8:
5236 case AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B8_replay:
5237 case AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B8_SADDR:
5238 case AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B32:
5239 case AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B32_SADDR:
5240 case AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B64:
5241 case AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B64_SADDR:
5242 case AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B128:
5243 case AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B128_SADDR:
5245 case AMDGPU::CLUSTER_LOAD_ASYNC_TO_LDS_B8:
5246 case AMDGPU::CLUSTER_LOAD_ASYNC_TO_LDS_B8_SADDR:
5247 case AMDGPU::CLUSTER_LOAD_ASYNC_TO_LDS_B32:
5248 case AMDGPU::CLUSTER_LOAD_ASYNC_TO_LDS_B32_SADDR:
5249 case AMDGPU::CLUSTER_LOAD_ASYNC_TO_LDS_B64:
5250 case AMDGPU::CLUSTER_LOAD_ASYNC_TO_LDS_B64_SADDR:
5251 case AMDGPU::CLUSTER_LOAD_ASYNC_TO_LDS_B128:
5252 case AMDGPU::CLUSTER_LOAD_ASYNC_TO_LDS_B128_SADDR:
5254 case AMDGPU::GLOBAL_STORE_ASYNC_FROM_LDS_B8:
5255 case AMDGPU::GLOBAL_STORE_ASYNC_FROM_LDS_B8_SADDR:
5256 case AMDGPU::GLOBAL_STORE_ASYNC_FROM_LDS_B32:
5257 case AMDGPU::GLOBAL_STORE_ASYNC_FROM_LDS_B32_SADDR:
5258 case AMDGPU::GLOBAL_STORE_ASYNC_FROM_LDS_B64:
5259 case AMDGPU::GLOBAL_STORE_ASYNC_FROM_LDS_B64_SADDR:
5260 case AMDGPU::GLOBAL_STORE_ASYNC_FROM_LDS_B128:
5261 case AMDGPU::GLOBAL_STORE_ASYNC_FROM_LDS_B128_SADDR:
5263 default:
5264 llvm_unreachable("Async opcode has no associated async stage");
5265 }
5266}
5267
5269 // Skip the full operand and register alias search modifiesRegister
5270 // does. There's only a handful of instructions that touch this, it's only an
5271 // implicit def, and doesn't alias any other registers.
5272 return is_contained(MI.getDesc().implicit_defs(), AMDGPU::MODE);
5273}
5274
5276 unsigned Opcode = MI.getOpcode();
5277
5278 if (MI.mayStore() && isSMRD(MI))
5279 return true; // scalar store or atomic
5280
5281 // This will terminate the function when other lanes may need to continue.
5282 if (MI.isReturn())
5283 return true;
5284
5285 // These instructions cause shader I/O that may cause hardware lockups
5286 // when executed with an empty EXEC mask.
5287 //
5288 // Note: exp with VM = DONE = 0 is automatically skipped by hardware when
5289 // EXEC = 0, but checking for that case here seems not worth it
5290 // given the typical code patterns.
5291 if (Opcode == AMDGPU::S_SENDMSG || Opcode == AMDGPU::S_SENDMSGHALT ||
5292 isEXP(Opcode) || Opcode == AMDGPU::DS_ORDERED_COUNT ||
5293 Opcode == AMDGPU::S_TRAP || Opcode == AMDGPU::S_WAIT_EVENT ||
5294 Opcode == AMDGPU::S_SETHALT)
5295 return true;
5296
5297 if (MI.isCall() || MI.isInlineAsm())
5298 return true; // conservative assumption
5299
5300 // V_PERM_PK16 must issue with EXEC != 0 so its follower (or an inserted
5301 // V_NOP) actually runs on the VALU pipe. Returning true here keeps the
5302 // s_cbranch_execz that skips this region when EXEC is empty.
5303 if (ST.hasVPermPk16Hazard() && isVPermPk16(Opcode))
5304 return true;
5305
5306 // Assume that barrier interactions are only intended with active lanes.
5307 if (isBarrier(Opcode))
5308 return true;
5309
5310 // A mode change is a scalar operation that influences vector instructions.
5312 return true;
5313
5314 // These are like SALU instructions in terms of effects, so it's questionable
5315 // whether we should return true for those.
5316 //
5317 // However, executing them with EXEC = 0 causes them to operate on undefined
5318 // data, which we avoid by returning true here.
5319 if (Opcode == AMDGPU::V_READFIRSTLANE_B32 ||
5320 Opcode == AMDGPU::V_READLANE_B32 || Opcode == AMDGPU::V_WRITELANE_B32 ||
5321 Opcode == AMDGPU::SI_RESTORE_S32_FROM_VGPR ||
5322 Opcode == AMDGPU::SI_SPILL_S32_TO_VGPR)
5323 return true;
5324
5325 return false;
5326}
5327
5329 const MachineInstr &MI) const {
5330 if (MI.isMetaInstruction())
5331 return false;
5332
5333 // This won't read exec if this is an SGPR->SGPR copy.
5334 if (MI.isCopyLike()) {
5335 if (!RI.isSGPRReg(MRI, MI.getOperand(0).getReg()))
5336 return true;
5337
5338 // Make sure this isn't copying exec as a normal operand
5339 return MI.readsRegister(AMDGPU::EXEC, &RI);
5340 }
5341
5342 // Make a conservative assumption about the callee.
5343 if (MI.isCall())
5344 return true;
5345
5346 // Be conservative with any unhandled generic opcodes.
5347 if (!isTargetSpecificOpcode(MI.getOpcode()))
5348 return true;
5349
5350 return !isSALU(MI) || MI.readsRegister(AMDGPU::EXEC, &RI);
5351}
5352
5354 switch (Imm.getBitWidth()) {
5355 case 1: // This likely will be a condition code mask.
5356 return true;
5357
5358 case 32:
5359 return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
5360 ST.hasInv2PiInlineImm());
5361 case 64:
5362 return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
5363 ST.hasInv2PiInlineImm());
5364 case 16:
5365 return ST.has16BitInsts() &&
5366 AMDGPU::isInlinableLiteralI16(Imm.getSExtValue(),
5367 ST.hasInv2PiInlineImm());
5368 default:
5369 llvm_unreachable("invalid bitwidth");
5370 }
5371}
5372
5374 APInt IntImm = Imm.bitcastToAPInt();
5375 int64_t IntImmVal = IntImm.getSExtValue();
5376 bool HasInv2Pi = ST.hasInv2PiInlineImm();
5377 switch (APFloat::SemanticsToEnum(Imm.getSemantics())) {
5378 default:
5379 llvm_unreachable("invalid fltSemantics");
5382 return isInlineConstant(IntImm);
5384 return ST.has16BitInsts() &&
5385 AMDGPU::isInlinableLiteralBF16(IntImmVal, HasInv2Pi);
5387 return ST.has16BitInsts() &&
5388 AMDGPU::isInlinableLiteralFP16(IntImmVal, HasInv2Pi);
5389 }
5390}
5391
5392bool SIInstrInfo::isInlineConstant(int64_t Imm, uint8_t OperandType) const {
5393 // MachineOperand provides no way to tell the true operand size, since it only
5394 // records a 64-bit value. We need to know the size to determine if a 32-bit
5395 // floating point immediate bit pattern is legal for an integer immediate. It
5396 // would be for any 32-bit integer operand, but would not be for a 64-bit one.
5397 switch (OperandType) {
5407 int32_t Trunc = static_cast<int32_t>(Imm);
5408 return AMDGPU::isInlinableLiteral32(Trunc, ST.hasInv2PiInlineImm());
5409 }
5417 return AMDGPU::isInlinableLiteral64(Imm, ST.hasInv2PiInlineImm());
5420 // We would expect inline immediates to not be concerned with an integer/fp
5421 // distinction. However, in the case of 16-bit integer operations, the
5422 // "floating point" values appear to not work. It seems read the low 16-bits
5423 // of 32-bit immediates, which happens to always work for the integer
5424 // values.
5425 //
5426 // See llvm bugzilla 46302.
5427 //
5428 // TODO: Theoretically we could use op-sel to use the high bits of the
5429 // 32-bit FP values.
5438 return AMDGPU::isPKFMACF16InlineConstant(Imm, ST.isGFX11Plus());
5443 return false;
5446 if (isInt<16>(Imm) || isUInt<16>(Imm)) {
5447 // A few special case instructions have 16-bit operands on subtargets
5448 // where 16-bit instructions are not legal.
5449 // TODO: Do the 32-bit immediates work? We shouldn't really need to handle
5450 // constants in these cases
5451 int16_t Trunc = static_cast<int16_t>(Imm);
5452 return ST.has16BitInsts() &&
5453 AMDGPU::isInlinableLiteralFP16(Trunc, ST.hasInv2PiInlineImm());
5454 }
5455
5456 return false;
5457 }
5460 if (isInt<16>(Imm) || isUInt<16>(Imm)) {
5461 int16_t Trunc = static_cast<int16_t>(Imm);
5462 return ST.has16BitInsts() &&
5463 AMDGPU::isInlinableLiteralBF16(Trunc, ST.hasInv2PiInlineImm());
5464 }
5465 return false;
5466 }
5471 return false;
5473 return isLegalAV64PseudoImm(Imm);
5476 // Always embedded in the instruction for free.
5477 return true;
5487 // Just ignore anything else.
5488 return false;
5489 default:
5490 llvm_unreachable("invalid operand type");
5491 }
5492}
5493
5494static bool compareMachineOp(const MachineOperand &Op0,
5495 const MachineOperand &Op1) {
5496 if (Op0.getType() != Op1.getType())
5497 return false;
5498
5499 switch (Op0.getType()) {
5501 return Op0.getReg() == Op1.getReg();
5503 return Op0.getImm() == Op1.getImm();
5504 default:
5505 llvm_unreachable("Didn't expect to be comparing these operand types");
5506 }
5507}
5508
5510 const MCOperandInfo &OpInfo) const {
5511 if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
5512 return true;
5513
5514 if (!RI.opCanUseLiteralConstant(OpInfo.OperandType))
5515 return false;
5516
5517 if (!isVOP3(InstDesc) || !AMDGPU::isSISrcOperand(OpInfo))
5518 return true;
5519
5520 return ST.hasVOP3Literal();
5521}
5522
5523bool SIInstrInfo::isImmOperandLegal(const MCInstrDesc &InstDesc, unsigned OpNo,
5524 int64_t ImmVal) const {
5525 const unsigned Opc = InstDesc.getOpcode();
5526 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
5527 if (Src1Idx != -1 && isDPP(Opc) &&
5528 (!ST.hasDPPSrc1SGPR() || AMDGPU::isVOP3DPPSrc1RevOpc(ST, Opc)) &&
5529 OpNo == static_cast<unsigned>(Src1Idx))
5530 return false;
5531
5532 const MCOperandInfo &OpInfo = InstDesc.operands()[OpNo];
5533 if (isInlineConstant(ImmVal, OpInfo.OperandType)) {
5534 if (isMAI(InstDesc) && ST.hasMFMAInlineLiteralBug() &&
5535 OpNo == (unsigned)AMDGPU::getNamedOperandIdx(InstDesc.getOpcode(),
5536 AMDGPU::OpName::src2))
5537 return false;
5538
5539 if (ST.hasBF16InlineConstFromUpperFP32() && isVOP1(Opc)) {
5540 if ((OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_BF16 ||
5541 OpInfo.OperandType == AMDGPU::OPERAND_REG_INLINE_C_BF16) &&
5542 isInlineConstant(ImmVal, OpInfo.OperandType))
5543 return false;
5544 }
5545
5546 return RI.opCanUseInlineConstant(OpInfo.OperandType);
5547 }
5548
5549 return isLiteralOperandLegal(InstDesc, OpInfo);
5550}
5551
5553 unsigned OpNo, int64_t ImmVal,
5554 unsigned Mods) const {
5555 return isImmOperandLegal(MI.getDesc(), OpNo, ImmVal) &&
5556 isImmOpSelLegal(ST, MI, OpNo, ImmVal, Mods);
5557}
5558
5559bool SIInstrInfo::isImmOperandLegal(const MCInstrDesc &InstDesc, unsigned OpNo,
5560 const MachineOperand &MO) const {
5561 if (MO.isImm())
5562 return isImmOperandLegal(InstDesc, OpNo, MO.getImm());
5563
5564 assert((MO.isTargetIndex() || MO.isFI() || MO.isGlobal()) &&
5565 "unexpected imm-like operand kind");
5566 const MCOperandInfo &OpInfo = InstDesc.operands()[OpNo];
5567 return isLiteralOperandLegal(InstDesc, OpInfo);
5568}
5569
5571 // 2 32-bit inline constants packed into one.
5572 return AMDGPU::isInlinableLiteral32(Lo_32(Imm), ST.hasInv2PiInlineImm()) &&
5573 AMDGPU::isInlinableLiteral32(Hi_32(Imm), ST.hasInv2PiInlineImm());
5574}
5575
5576bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
5577 // GFX90A does not have V_MUL_LEGACY_F32_e32.
5578 if (Opcode == AMDGPU::V_MUL_LEGACY_F32_e64 && ST.hasGFX90AInsts())
5579 return false;
5580
5581 int Op32 = AMDGPU::getVOPe32(Opcode);
5582 if (Op32 == -1)
5583 return false;
5584
5585 return pseudoToMCOpcode(Op32) != -1;
5586}
5587
5588/// Return true if \p MI is a VALU comparison, i.e. an instruction that writes
5589/// a lane mask with one bit per lane, and zeroes the bits of lanes that were
5590/// inactive when it executed.
5591///
5592/// TODO: Also handle the sdst result of V_ADD_CO_U32 and V_SUB_CO_U32 and
5593/// V_DIV_SCALE_F32.
5594static bool isVCmp(const SIInstrInfo &TII, const MachineInstr &MI) {
5595 if (TII.isVOPC(MI))
5596 return true;
5597 int Op32 = AMDGPU::getVOPe32(MI.getOpcode());
5598 return Op32 != -1 && TII.isVOPC(Op32);
5599}
5600
5602 const MachineRegisterInfo &MRI,
5603 unsigned Depth) const {
5604 assert(MRI.isSSA() && "isMaskedByExec requires SSA form");
5606 const MachineBasicBlock *MBB = Use.getParent();
5607
5608 // EXEC itself is trivially masked by EXEC.
5609 if (Reg == LMC.ExecReg)
5610 return true;
5611
5612 // Maximum depth of the def-use walk.
5613 constexpr unsigned MaxDepth = 6;
5614 if (Depth >= MaxDepth || !Reg.isVirtual())
5615 return false;
5616
5617 // Only look at definitions that can execute under the same EXEC mask as the
5618 // use.
5619 const MachineInstr *Def = MRI.getVRegDef(Reg);
5620 if (!Def || Def->getParent() != MBB)
5621 return false;
5622
5623 if (isVCmp(*this, *Def))
5624 return true;
5625
5626 // Recurse into an operand, which must be a whole register to say anything
5627 // about the whole lane mask. A constant zero has no bits set for inactive
5628 // lanes, so it is trivially masked. Any other immediate may set them.
5629 auto Recurse = [&](unsigned OpIdx) {
5630 const MachineOperand &MO = Def->getOperand(OpIdx);
5631 if (std::optional<int64_t> Imm = getImmOrMaterializedImm(MRI, MO))
5632 return *Imm == 0;
5633 return MO.isReg() && !MO.getSubReg() &&
5634 isMaskedByExec(MO.getReg(), Use, MRI, Depth + 1);
5635 };
5636
5637 unsigned Opc = Def->getOpcode();
5638 if (Opc == AMDGPU::COPY && Recurse(1))
5639 return true;
5640 if (Opc == LMC.AndOpc && (Recurse(1) || Recurse(2)))
5641 return true;
5642 if (Opc == LMC.AndN2Opc && Recurse(1))
5643 return true;
5644 if ((Opc == LMC.OrOpc || Opc == LMC.XorOpc || Opc == LMC.CSelectOpc) &&
5645 Recurse(1) && Recurse(2))
5646 return true;
5647
5648 return false;
5649}
5650
5651bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
5652 // The src0_modifier operand is present on all instructions
5653 // that have modifiers.
5654
5655 return AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::src0_modifiers);
5656}
5657
5659 AMDGPU::OpName OpName) const {
5660 const MachineOperand *Mods = getNamedOperand(MI, OpName);
5661 return Mods && Mods->getImm();
5662}
5663
5665 return any_of(ModifierOpNames,
5666 [&](AMDGPU::OpName Name) { return hasModifiersSet(MI, Name); });
5667}
5668
5670 const MachineRegisterInfo &MRI) const {
5671 const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
5672 // Can't shrink instruction with three operands.
5673 if (Src2) {
5674 switch (MI.getOpcode()) {
5675 default: return false;
5676
5677 case AMDGPU::V_ADDC_U32_e64:
5678 case AMDGPU::V_SUBB_U32_e64:
5679 case AMDGPU::V_SUBBREV_U32_e64: {
5680 const MachineOperand *Src1
5681 = getNamedOperand(MI, AMDGPU::OpName::src1);
5682 if (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()))
5683 return false;
5684 // Additional verification is needed for sdst/src2.
5685 return true;
5686 }
5687 case AMDGPU::V_MAC_F16_e64:
5688 case AMDGPU::V_MAC_F32_e64:
5689 case AMDGPU::V_MAC_LEGACY_F32_e64:
5690 case AMDGPU::V_FMAC_F16_e64:
5691 case AMDGPU::V_FMAC_F16_t16_e64:
5692 case AMDGPU::V_FMAC_F16_fake16_e64:
5693 case AMDGPU::V_FMAC_F32_e64:
5694 case AMDGPU::V_FMAC_F64_e64:
5695 case AMDGPU::V_FMAC_LEGACY_F32_e64:
5696 if (!Src2->isReg() || !RI.isVGPR(MRI, Src2->getReg()) ||
5697 hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
5698 return false;
5699 break;
5700
5701 case AMDGPU::V_CNDMASK_B32_e64:
5702 break;
5703 }
5704 }
5705
5706 const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
5707 if (Src1 && (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()) ||
5708 hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
5709 return false;
5710
5711 // Make sure src0 isn't using any modifiers.
5712 if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
5713 return false;
5714
5715 // Can it be shrunk to a valid 32 bit opcode?
5716 if (!hasVALU32BitEncoding(MI.getOpcode()))
5717 return false;
5718
5719 const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
5720 if (Src0 && Src0->isImm()) {
5721 unsigned Op32 = AMDGPU::getVOPe32(MI.getOpcode());
5722 if (!isImmOperandLegal(
5723 get(Op32), AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src0),
5724 *Src0))
5725 return false;
5726 }
5727
5728 // Check output modifiers
5729 return !hasModifiersSet(MI, AMDGPU::OpName::omod) &&
5730 !hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
5731 !hasModifiersSet(MI, AMDGPU::OpName::byte_sel) &&
5732 // TODO: Can we avoid checking bound_ctrl/fi here?
5733 // They are only used by permlane*_swap special case.
5734 !hasModifiersSet(MI, AMDGPU::OpName::bound_ctrl) &&
5735 !hasModifiersSet(MI, AMDGPU::OpName::fi);
5736}
5737
5738// Set VCC operand with all flags from \p Orig, except for setting it as
5739// implicit.
5741 const MachineOperand &Orig) {
5742
5743 for (MachineOperand &Use : MI.implicit_operands()) {
5744 if (Use.isUse() &&
5745 (Use.getReg() == AMDGPU::VCC || Use.getReg() == AMDGPU::VCC_LO)) {
5746 Use.setIsUndef(Orig.isUndef());
5747 Use.setIsKill(Orig.isKill());
5748 return;
5749 }
5750 }
5751}
5752
5754 unsigned Op32) const {
5755 MachineBasicBlock *MBB = MI.getParent();
5756
5757 const MCInstrDesc &Op32Desc = get(Op32);
5758 MachineInstrBuilder Inst32 =
5759 BuildMI(*MBB, MI, MI.getDebugLoc(), Op32Desc)
5760 .setMIFlags(MI.getFlags());
5761
5762 // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
5763 // For VOPC instructions, this is replaced by an implicit def of vcc.
5764
5765 // We assume the defs of the shrunk opcode are in the same order, and the
5766 // shrunk opcode loses the last def (SGPR def, in the VOP3->VOPC case).
5767 for (int I = 0, E = Op32Desc.getNumDefs(); I != E; ++I)
5768 Inst32.add(MI.getOperand(I));
5769
5770 const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
5771
5772 int Idx = MI.getNumExplicitDefs();
5773 for (const MachineOperand &Use : MI.explicit_uses()) {
5774 int OpTy = MI.getDesc().operands()[Idx++].OperandType;
5776 continue;
5777
5778 if (&Use == Src2) {
5779 if (AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2) == -1) {
5780 // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
5781 // replaced with an implicit read of vcc or vcc_lo. The implicit read
5782 // of vcc was already added during the initial BuildMI, but we
5783 // 1) may need to change vcc to vcc_lo to preserve the original register
5784 // 2) have to preserve the original flags.
5785 copyFlagsToImplicitVCC(*Inst32, *Src2);
5786 continue;
5787 }
5788 }
5789
5790 Inst32.add(Use);
5791 }
5792
5793 // FIXME: Losing implicit operands
5794 fixImplicitOperands(*Inst32);
5795
5796 // The explicit carry/result def is dropped in favor of an implicit VCC def;
5797 // preserve the dead flag.
5798 const MachineOperand *OldSDst = getNamedOperand(MI, AMDGPU::OpName::sdst);
5799 if (OldSDst && OldSDst->isDead()) {
5800 if (MachineOperand *NewVCC =
5801 Inst32->findRegisterDefOperand(RI.getVCC(), &RI))
5802 NewVCC->setIsDead();
5803 }
5804
5805 return Inst32;
5806}
5807
5809 // Null is free
5810 Register Reg = RegOp.getReg();
5811 if (Reg == AMDGPU::SGPR_NULL || Reg == AMDGPU::SGPR_NULL64)
5812 return false;
5813
5814 // SGPRs use the constant bus
5815
5816 // FIXME: implicit registers that are not part of the MCInstrDesc's implicit
5817 // physical register operands should also count, except for exec.
5818 if (RegOp.isImplicit())
5819 return Reg == AMDGPU::VCC || Reg == AMDGPU::VCC_LO || Reg == AMDGPU::M0;
5820
5821 // SGPRs use the constant bus
5822 return AMDGPU::SReg_32RegClass.contains(Reg) ||
5823 AMDGPU::SReg_64RegClass.contains(Reg);
5824}
5825
5827 const MachineRegisterInfo &MRI) const {
5828 Register Reg = RegOp.getReg();
5829 return Reg.isVirtual() ? RI.isSGPRClass(MRI.getRegClass(Reg))
5830 : physRegUsesConstantBus(RegOp);
5831}
5832
5834 const MachineOperand &MO,
5835 const MCOperandInfo &OpInfo) const {
5836 // Literal constants use the constant bus.
5837 if (!MO.isReg())
5838 return !isInlineConstant(MO, OpInfo);
5839
5840 Register Reg = MO.getReg();
5841 return Reg.isVirtual() ? RI.isSGPRClass(MRI.getRegClass(Reg))
5843}
5844
5846 for (const MachineOperand &MO : MI.implicit_operands()) {
5847 // We only care about reads.
5848 if (MO.isDef())
5849 continue;
5850
5851 switch (MO.getReg()) {
5852 case AMDGPU::VCC:
5853 case AMDGPU::VCC_LO:
5854 case AMDGPU::VCC_HI:
5855 case AMDGPU::M0:
5856 case AMDGPU::FLAT_SCR:
5857 return MO.getReg();
5858
5859 default:
5860 break;
5861 }
5862 }
5863
5864 return Register();
5865}
5866
5867static bool shouldReadExec(const MachineInstr &MI) {
5868 if (SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false)) {
5869 switch (MI.getOpcode()) {
5870 case AMDGPU::V_READLANE_B32:
5871 case AMDGPU::SI_RESTORE_S32_FROM_VGPR:
5872 case AMDGPU::V_WRITELANE_B32:
5873 case AMDGPU::SI_SPILL_S32_TO_VGPR:
5874 return false;
5875 }
5876
5877 return true;
5878 }
5879
5880 if (MI.isPreISelOpcode() ||
5881 SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
5884 return false;
5885
5886 return true;
5887}
5888
5889static bool isRegOrFI(const MachineOperand &MO) {
5890 return MO.isReg() || MO.isFI();
5891}
5892
5893static bool isSubRegOf(const SIRegisterInfo &TRI,
5894 const MachineOperand &SuperVec,
5895 const MachineOperand &SubReg) {
5896 if (SubReg.getReg().isPhysical())
5897 return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
5898
5899 return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
5900 SubReg.getReg() == SuperVec.getReg();
5901}
5902
5903// Verify the illegal copy from vector register to SGPR for generic opcode COPY
5904bool SIInstrInfo::verifyCopy(const MachineInstr &MI,
5905 const MachineRegisterInfo &MRI,
5906 StringRef &ErrInfo) const {
5907 Register DstReg = MI.getOperand(0).getReg();
5908 Register SrcReg = MI.getOperand(1).getReg();
5909 // This is a check for copy from vector register to SGPR
5910 if (RI.isVectorRegister(MRI, SrcReg) && RI.isSGPRReg(MRI, DstReg)) {
5911 ErrInfo = "illegal copy from vector register to SGPR";
5912 return false;
5913 }
5914 return true;
5915}
5916
5918 StringRef &ErrInfo) const {
5919 uint32_t Opcode = MI.getOpcode();
5920 const MachineFunction *MF = MI.getMF();
5921 const MachineRegisterInfo &MRI = MF->getRegInfo();
5922
5923 // FIXME: At this point the COPY verify is done only for non-ssa forms.
5924 // Find a better property to recognize the point where instruction selection
5925 // is just done.
5926 // We can only enforce this check after SIFixSGPRCopies pass so that the
5927 // illegal copies are legalized and thereafter we don't expect a pass
5928 // inserting similar copies.
5929 if (!MRI.isSSA() && MI.isCopy())
5930 return verifyCopy(MI, MRI, ErrInfo);
5931
5932 if (SIInstrInfo::isGenericOpcode(Opcode))
5933 return true;
5934
5935 int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
5936 int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
5937 int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
5938 int Src3Idx = -1;
5939 if (Src0Idx == -1) {
5940 // VOPD V_DUAL_* instructions use different operand names.
5941 Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0X);
5942 Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vsrc1X);
5943 Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0Y);
5944 Src3Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vsrc1Y);
5945 }
5946
5947 // Make sure the number of operands is correct.
5948 const MCInstrDesc &Desc = get(Opcode);
5949 if (!Desc.isVariadic() &&
5950 Desc.getNumOperands() != MI.getNumExplicitOperands()) {
5951 ErrInfo = "Instruction has wrong number of operands.";
5952 return false;
5953 }
5954
5955 if (MI.isInlineAsm()) {
5956 // Verify register classes for inlineasm constraints.
5957 for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
5958 I != E; ++I) {
5959 const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
5960 if (!RC)
5961 continue;
5962
5963 const MachineOperand &Op = MI.getOperand(I);
5964 if (!Op.isReg())
5965 continue;
5966
5967 Register Reg = Op.getReg();
5968 if (!Reg.isVirtual() && !RC->contains(Reg)) {
5969 ErrInfo = "inlineasm operand has incorrect register class.";
5970 return false;
5971 }
5972 }
5973
5974 return true;
5975 }
5976
5977 if (isImage(MI) && MI.memoperands_empty() && MI.mayLoadOrStore()) {
5978 ErrInfo = "missing memory operand from image instruction.";
5979 return false;
5980 }
5981
5982 // Make sure the register classes are correct.
5983 for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
5984 const MachineOperand &MO = MI.getOperand(i);
5985 if (MO.isFPImm()) {
5986 ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
5987 "all fp values to integers.";
5988 return false;
5989 }
5990
5991 const MCOperandInfo &OpInfo = Desc.operands()[i];
5992
5993 switch (OpInfo.OperandType) {
5995 if (MI.getOperand(i).isImm() || MI.getOperand(i).isGlobal()) {
5996 ErrInfo = "Illegal immediate value for operand.";
5997 return false;
5998 }
5999 break;
6013 break;
6027 if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
6028 ErrInfo = "Illegal immediate value for operand.";
6029 return false;
6030 }
6031 break;
6032 }
6037 if (ST.has64BitLiterals() && Desc.getSize() != 4 && MO.isImm() &&
6038 !isInlineConstant(MI, i) &&
6040 OpInfo.OperandType ==
6042 ErrInfo = "illegal 64-bit immediate value for operand.";
6043 return false;
6044 }
6045 break;
6048 if (!MI.getOperand(i).isImm() || !isInlineConstant(MI, i)) {
6049 ErrInfo = "Expected inline constant for operand.";
6050 return false;
6051 }
6052 break;
6055 break;
6060 // Check if this operand is an immediate.
6061 // FrameIndex operands will be replaced by immediates, so they are
6062 // allowed.
6063 if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
6064 ErrInfo = "Expected immediate, but got non-immediate";
6065 return false;
6066 }
6067 break;
6071 break;
6072 default:
6073 if (OpInfo.isGenericType())
6074 continue;
6075 break;
6076 }
6077 }
6078
6079 // Verify SDWA
6080 if (isSDWA(MI)) {
6081 if (!ST.hasSDWA()) {
6082 ErrInfo = "SDWA is not supported on this target";
6083 return false;
6084 }
6085
6086 for (auto Op : {AMDGPU::OpName::src0_sel, AMDGPU::OpName::src1_sel,
6087 AMDGPU::OpName::dst_sel}) {
6088 const MachineOperand *MO = getNamedOperand(MI, Op);
6089 if (!MO)
6090 continue;
6091 int64_t Imm = MO->getImm();
6093 ErrInfo = "Invalid SDWA selection";
6094 return false;
6095 }
6096 }
6097
6098 int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
6099
6100 for (int OpIdx : {DstIdx, Src0Idx, Src1Idx, Src2Idx}) {
6101 if (OpIdx == -1)
6102 continue;
6103 const MachineOperand &MO = MI.getOperand(OpIdx);
6104
6105 if (!ST.hasSDWAScalar()) {
6106 // Only VGPRS on VI
6107 if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
6108 ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
6109 return false;
6110 }
6111 } else {
6112 // No immediates on GFX9
6113 if (!MO.isReg()) {
6114 ErrInfo =
6115 "Only reg allowed as operands in SDWA instructions on GFX9+";
6116 return false;
6117 }
6118 }
6119 }
6120
6121 if (!ST.hasSDWAOmod()) {
6122 // No omod allowed on VI
6123 const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
6124 if (OMod != nullptr &&
6125 (!OMod->isImm() || OMod->getImm() != 0)) {
6126 ErrInfo = "OMod not allowed in SDWA instructions on VI";
6127 return false;
6128 }
6129 }
6130
6131 if (Opcode == AMDGPU::V_CVT_F32_FP8_sdwa ||
6132 Opcode == AMDGPU::V_CVT_F32_BF8_sdwa ||
6133 Opcode == AMDGPU::V_CVT_PK_F32_FP8_sdwa ||
6134 Opcode == AMDGPU::V_CVT_PK_F32_BF8_sdwa) {
6135 const MachineOperand *Src0ModsMO =
6136 getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
6137 unsigned Mods = Src0ModsMO->getImm();
6138 if (Mods & SISrcMods::ABS || Mods & SISrcMods::NEG ||
6139 Mods & SISrcMods::SEXT) {
6140 ErrInfo = "sext, abs and neg are not allowed on this instruction";
6141 return false;
6142 }
6143 }
6144
6145 uint32_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
6146 if (isVOPC(BasicOpcode)) {
6147 if (!ST.hasSDWASdst() && DstIdx != -1) {
6148 // Only vcc allowed as dst on VI for VOPC
6149 const MachineOperand &Dst = MI.getOperand(DstIdx);
6150 if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
6151 ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
6152 return false;
6153 }
6154 } else if (!ST.hasSDWAOutModsVOPC()) {
6155 // No clamp allowed on GFX9 for VOPC
6156 const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
6157 if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
6158 ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
6159 return false;
6160 }
6161
6162 // No omod allowed on GFX9 for VOPC
6163 const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
6164 if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
6165 ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
6166 return false;
6167 }
6168 }
6169 }
6170
6171 const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
6172 if (DstUnused && DstUnused->isImm() &&
6173 DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
6174 const MachineOperand &Dst = MI.getOperand(DstIdx);
6175 if (!Dst.isReg() || !Dst.isTied()) {
6176 ErrInfo = "Dst register should have tied register";
6177 return false;
6178 }
6179
6180 const MachineOperand &TiedMO =
6181 MI.getOperand(MI.findTiedOperandIdx(DstIdx));
6182 if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
6183 ErrInfo =
6184 "Dst register should be tied to implicit use of preserved register";
6185 return false;
6186 }
6187 if (TiedMO.getReg().isPhysical() && Dst.getReg() != TiedMO.getReg()) {
6188 ErrInfo = "Dst register should use same physical register as preserved";
6189 return false;
6190 }
6191 }
6192 }
6193
6194 // REV-type opcodes apply DPP to src1, so src1 must be a VGPR even on
6195 // subtargets that otherwise permit an SGPR there.
6196 if (isDPP(MI) && Src1Idx != -1 &&
6197 (!ST.hasDPPSrc1SGPR() || AMDGPU::isVOP3DPPSrc1RevOpc(ST, Opcode))) {
6198 const MachineOperand &Src1MO = MI.getOperand(Src1Idx);
6199 if (Src1MO.isReg() && RI.isSGPRReg(MRI, Src1MO.getReg())) {
6200 ErrInfo = "DPP src1 cannot be SGPR on this subtarget";
6201 return false;
6202 }
6203 if (Src1MO.isImm()) {
6204 ErrInfo = "DPP src1 cannot be an immediate on this subtarget";
6205 return false;
6206 }
6207 }
6208
6209 // Verify MIMG / VIMAGE / VSAMPLE
6210 if (isImage(Opcode) && !MI.mayStore()) {
6211 // Ensure that the return type used is large enough for all the options
6212 // being used TFE/LWE require an extra result register.
6213 const MachineOperand *DMask = getNamedOperand(MI, AMDGPU::OpName::dmask);
6214 if (DMask) {
6215 uint64_t DMaskImm = DMask->getImm();
6216 uint32_t RegCount = isGather4(Opcode) ? 4 : llvm::popcount(DMaskImm);
6217 const MachineOperand *TFE = getNamedOperand(MI, AMDGPU::OpName::tfe);
6218 const MachineOperand *LWE = getNamedOperand(MI, AMDGPU::OpName::lwe);
6219 const MachineOperand *D16 = getNamedOperand(MI, AMDGPU::OpName::d16);
6220
6221 // Adjust for packed 16 bit values
6222 if (D16 && D16->getImm() && !ST.hasUnpackedD16VMem())
6223 RegCount = divideCeil(RegCount, 2);
6224
6225 // Adjust if using LWE or TFE
6226 if ((LWE && LWE->getImm()) || (TFE && TFE->getImm()))
6227 RegCount += 1;
6228
6229 const uint32_t DstIdx =
6230 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
6231 const MachineOperand &Dst = MI.getOperand(DstIdx);
6232 if (Dst.isReg()) {
6233 const TargetRegisterClass *DstRC = getOpRegClass(MI, DstIdx);
6234 uint32_t DstSize = RI.getRegSizeInBits(*DstRC) / 32;
6235 if (RegCount > DstSize) {
6236 ErrInfo = "Image instruction returns too many registers for dst "
6237 "register class";
6238 return false;
6239 }
6240 }
6241 }
6242 }
6243
6244 // Verify VOP*. Ignore multiple sgpr operands on writelane.
6245 if (isVALU(MI, /*AllowLDSDMA=*/false) &&
6246 Desc.getOpcode() != AMDGPU::V_WRITELANE_B32) {
6247 unsigned ConstantBusCount = 0;
6248 bool UsesLiteral = false;
6249 const MachineOperand *LiteralVal = nullptr;
6250
6251 int ImmIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm);
6252 if (ImmIdx != -1) {
6253 ++ConstantBusCount;
6254 UsesLiteral = true;
6255 LiteralVal = &MI.getOperand(ImmIdx);
6256 }
6257
6258 SmallVector<Register, 2> SGPRsUsed;
6259 Register SGPRUsed;
6260
6261 // Only look at the true operands. Only a real operand can use the constant
6262 // bus, and we don't want to check pseudo-operands like the source modifier
6263 // flags.
6264 for (int OpIdx : {Src0Idx, Src1Idx, Src2Idx, Src3Idx}) {
6265 if (OpIdx == -1)
6266 continue;
6267 const MachineOperand &MO = MI.getOperand(OpIdx);
6268 if (usesConstantBus(MRI, MO, MI.getDesc().operands()[OpIdx])) {
6269 if (MO.isReg()) {
6270 SGPRUsed = MO.getReg();
6271 if (!llvm::is_contained(SGPRsUsed, SGPRUsed)) {
6272 ++ConstantBusCount;
6273 SGPRsUsed.push_back(SGPRUsed);
6274 }
6275 } else if (!MO.isFI()) { // Treat FI like a register.
6276 if (!UsesLiteral) {
6277 ++ConstantBusCount;
6278 UsesLiteral = true;
6279 LiteralVal = &MO;
6280 } else if (!MO.isIdenticalTo(*LiteralVal)) {
6281 assert(isVOP2(MI) || isVOP3(MI));
6282 ErrInfo = "VOP2/VOP3 instruction uses more than one literal";
6283 return false;
6284 }
6285 }
6286 }
6287 }
6288
6289 SGPRUsed = findImplicitSGPRRead(MI);
6290 if (SGPRUsed) {
6291 // Implicit uses may safely overlap true operands
6292 if (llvm::all_of(SGPRsUsed, [this, SGPRUsed](unsigned SGPR) {
6293 return !RI.regsOverlap(SGPRUsed, SGPR);
6294 })) {
6295 ++ConstantBusCount;
6296 SGPRsUsed.push_back(SGPRUsed);
6297 }
6298 }
6299
6300 // v_writelane_b32 is an exception from constant bus restriction:
6301 // vsrc0 can be sgpr, const or m0 and lane select sgpr, m0 or inline-const
6302 if (ConstantBusCount > ST.getConstantBusLimit(Opcode) &&
6303 Opcode != AMDGPU::V_WRITELANE_B32) {
6304 ErrInfo = "VOP* instruction violates constant bus restriction";
6305 return false;
6306 }
6307
6308 if (isVOP3(MI) && UsesLiteral && !ST.hasVOP3Literal()) {
6309 ErrInfo = "VOP3 instruction uses literal";
6310 return false;
6311 }
6312 }
6313
6314 // Special case for writelane - this can break the multiple constant bus rule,
6315 // but still can't use more than one SGPR register
6316 if (Desc.getOpcode() == AMDGPU::V_WRITELANE_B32) {
6317 unsigned SGPRCount = 0;
6318 Register SGPRUsed;
6319
6320 for (int OpIdx : {Src0Idx, Src1Idx}) {
6321 if (OpIdx == -1)
6322 break;
6323
6324 const MachineOperand &MO = MI.getOperand(OpIdx);
6325
6326 if (usesConstantBus(MRI, MO, MI.getDesc().operands()[OpIdx])) {
6327 if (MO.isReg() && MO.getReg() != AMDGPU::M0) {
6328 if (MO.getReg() != SGPRUsed)
6329 ++SGPRCount;
6330 SGPRUsed = MO.getReg();
6331 }
6332 }
6333 if (SGPRCount > ST.getConstantBusLimit(Opcode)) {
6334 ErrInfo = "WRITELANE instruction violates constant bus restriction";
6335 return false;
6336 }
6337 }
6338 }
6339
6340 if (Opcode == AMDGPU::ASYNCMARK || Opcode == AMDGPU::WAIT_ASYNCMARK) {
6341 int64_t Mask = MI.getOperand(MI.getNumExplicitOperands() - 1).getImm();
6342 if (!AMDGPU::isValidAsyncStageMask(Mask)) {
6343 ErrInfo = "invalid asyncmark stage mask";
6344 return false;
6345 }
6346 }
6347
6348 // An offset past the addressable VGPRs is an out-of-bounds access, which is
6349 // allowed, but each dword must still be a VGPR.
6350 if (const auto *LdSt = dyn_cast<AMDGPUMI::VLoadStoreIdxInst>(&MI)) {
6351 const MachineOperand &Offset = LdSt->getOffsetOp();
6352 if (!Offset.isImm() || Offset.getImm() < 0 ||
6353 Offset.getImm() + LdSt->getBitWidth() / 32 >
6354 AMDGPU::VGPR_32RegClass.getNumRegs()) {
6355 ErrInfo = "invalid VGPR address space offset";
6356 return false;
6357 }
6358 }
6359
6360 // Verify misc. restrictions on specific instructions.
6361 if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32_e64 ||
6362 Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64_e64) {
6363 const MachineOperand &Src0 = MI.getOperand(Src0Idx);
6364 const MachineOperand &Src1 = MI.getOperand(Src1Idx);
6365 const MachineOperand &Src2 = MI.getOperand(Src2Idx);
6366 if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
6367 if (!compareMachineOp(Src0, Src1) &&
6368 !compareMachineOp(Src0, Src2)) {
6369 ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
6370 return false;
6371 }
6372 }
6373 if ((getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm() &
6374 SISrcMods::ABS) ||
6375 (getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm() &
6376 SISrcMods::ABS) ||
6377 (getNamedOperand(MI, AMDGPU::OpName::src2_modifiers)->getImm() &
6378 SISrcMods::ABS)) {
6379 ErrInfo = "ABS not allowed in VOP3B instructions";
6380 return false;
6381 }
6382 }
6383
6384 if (isSOP2(MI) || isSOPC(MI)) {
6385 const MachineOperand &Src0 = MI.getOperand(Src0Idx);
6386 const MachineOperand &Src1 = MI.getOperand(Src1Idx);
6387
6388 if (!isRegOrFI(Src0) && !isRegOrFI(Src1) &&
6389 !isInlineConstant(Src0, Desc.operands()[Src0Idx]) &&
6390 !isInlineConstant(Src1, Desc.operands()[Src1Idx]) &&
6391 !Src0.isIdenticalTo(Src1)) {
6392 ErrInfo = "SOP2/SOPC instruction requires too many immediate constants";
6393 return false;
6394 }
6395 }
6396
6397 if (isSOPK(MI)) {
6398 const auto *Op = getNamedOperand(MI, AMDGPU::OpName::simm16);
6399 if (Desc.isBranch()) {
6400 if (!Op->isMBB()) {
6401 ErrInfo = "invalid branch target for SOPK instruction";
6402 return false;
6403 }
6404 } else {
6405 uint64_t Imm = Op->getImm();
6406 if (sopkIsZext(Opcode)) {
6407 if (!isUInt<16>(Imm)) {
6408 ErrInfo = "invalid immediate for SOPK instruction";
6409 return false;
6410 }
6411 } else {
6412 if (!isInt<16>(Imm)) {
6413 ErrInfo = "invalid immediate for SOPK instruction";
6414 return false;
6415 }
6416 }
6417 }
6418 }
6419
6420 if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
6421 Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
6422 Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
6423 Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
6424 const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
6425 Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
6426
6427 const unsigned StaticNumOps =
6428 Desc.getNumOperands() + Desc.implicit_uses().size();
6429 const unsigned NumImplicitOps = IsDst ? 2 : 1;
6430
6431 // Require additional implicit operands. This allows a fixup done by the
6432 // post RA scheduler where the main implicit operand is killed and
6433 // implicit-defs are added for sub-registers that remain live after this
6434 // instruction.
6435 if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
6436 ErrInfo = "missing implicit register operands";
6437 return false;
6438 }
6439
6440 const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
6441 if (IsDst) {
6442 if (!Dst->isUse()) {
6443 ErrInfo = "v_movreld_b32 vdst should be a use operand";
6444 return false;
6445 }
6446
6447 unsigned UseOpIdx;
6448 if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
6449 UseOpIdx != StaticNumOps + 1) {
6450 ErrInfo = "movrel implicit operands should be tied";
6451 return false;
6452 }
6453 }
6454
6455 const MachineOperand &Src0 = MI.getOperand(Src0Idx);
6456 const MachineOperand &ImpUse
6457 = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
6458 if (!ImpUse.isReg() || !ImpUse.isUse() ||
6459 !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
6460 ErrInfo = "src0 should be subreg of implicit vector use";
6461 return false;
6462 }
6463 }
6464
6465 // Make sure we aren't losing exec uses in the td files. This mostly requires
6466 // being careful when using let Uses to try to add other use registers.
6467 if (shouldReadExec(MI)) {
6468 if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
6469 ErrInfo = "VALU instruction does not implicitly read exec mask";
6470 return false;
6471 }
6472 }
6473
6474 if (isSMRD(MI)) {
6475 if (MI.mayStore() &&
6476 ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) {
6477 // The register offset form of scalar stores may only use m0 as the
6478 // soffset register.
6479 const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soffset);
6480 if (Soff && Soff->getReg() != AMDGPU::M0) {
6481 ErrInfo = "scalar stores must use m0 as offset register";
6482 return false;
6483 }
6484 }
6485 }
6486
6487 if (isFLAT(MI) && !ST.hasFlatInstOffsets()) {
6488 const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
6489 if (Offset->getImm() != 0) {
6490 ErrInfo = "subtarget does not support offsets in flat instructions";
6491 return false;
6492 }
6493 }
6494
6495 if (isDS(MI) && !ST.hasGDS()) {
6496 const MachineOperand *GDSOp = getNamedOperand(MI, AMDGPU::OpName::gds);
6497 if (GDSOp && GDSOp->getImm() != 0) {
6498 ErrInfo = "GDS is not supported on this subtarget";
6499 return false;
6500 }
6501 }
6502
6503 if (isImage(MI)) {
6504 const MachineOperand *DimOp = getNamedOperand(MI, AMDGPU::OpName::dim);
6505 if (DimOp) {
6506 int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opcode,
6507 AMDGPU::OpName::vaddr0);
6508 AMDGPU::OpName RSrcOpName =
6509 isMIMG(MI) ? AMDGPU::OpName::srsrc : AMDGPU::OpName::rsrc;
6510 int RsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, RSrcOpName);
6511 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opcode);
6512 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6513 AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
6514 const AMDGPU::MIMGDimInfo *Dim =
6516
6517 if (!Dim) {
6518 ErrInfo = "dim is out of range";
6519 return false;
6520 }
6521
6522 bool IsA16 = false;
6523 if (ST.hasR128A16()) {
6524 const MachineOperand *R128A16 = getNamedOperand(MI, AMDGPU::OpName::r128);
6525 IsA16 = R128A16->getImm() != 0;
6526 } else if (ST.hasA16()) {
6527 const MachineOperand *A16 = getNamedOperand(MI, AMDGPU::OpName::a16);
6528 IsA16 = A16->getImm() != 0;
6529 }
6530
6531 bool IsNSA = RsrcIdx - VAddr0Idx > 1;
6532
6533 unsigned AddrWords =
6534 AMDGPU::getAddrSizeMIMGOp(BaseOpcode, Dim, IsA16, ST.hasG16());
6535
6536 unsigned VAddrWords;
6537 if (IsNSA) {
6538 VAddrWords = RsrcIdx - VAddr0Idx;
6539 if (ST.hasPartialNSAEncoding() &&
6540 AddrWords > ST.getNSAMaxSize(isVSAMPLE(MI))) {
6541 unsigned LastVAddrIdx = RsrcIdx - 1;
6542 VAddrWords += getOpSize(MI, LastVAddrIdx) / 4 - 1;
6543 }
6544 } else {
6545 VAddrWords = getOpSize(MI, VAddr0Idx) / 4;
6546 if (AddrWords > 12)
6547 AddrWords = 16;
6548 }
6549
6550 if (VAddrWords != AddrWords) {
6551 LLVM_DEBUG(dbgs() << "bad vaddr size, expected " << AddrWords
6552 << " but got " << VAddrWords << "\n");
6553 ErrInfo = "bad vaddr size";
6554 return false;
6555 }
6556 }
6557 }
6558
6559 const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
6560 if (DppCt) {
6561 using namespace AMDGPU::DPP;
6562
6563 unsigned DC = DppCt->getImm();
6564 if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
6565 DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
6566 (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
6567 (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
6568 (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
6569 (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST) ||
6570 (DC >= DppCtrl::DPP_UNUSED8_FIRST && DC <= DppCtrl::DPP_UNUSED8_LAST)) {
6571 ErrInfo = "Invalid dpp_ctrl value";
6572 return false;
6573 }
6574 if (DC >= DppCtrl::WAVE_SHL1 && DC <= DppCtrl::WAVE_ROR1 &&
6575 !ST.hasDPPWavefrontShifts()) {
6576 ErrInfo = "Invalid dpp_ctrl value: "
6577 "wavefront shifts are not supported on GFX10+";
6578 return false;
6579 }
6580 if (DC >= DppCtrl::BCAST15 && DC <= DppCtrl::BCAST31 &&
6581 !ST.hasDPPBroadcasts()) {
6582 ErrInfo = "Invalid dpp_ctrl value: "
6583 "broadcasts are not supported on GFX10+";
6584 return false;
6585 }
6586 if (DC >= DppCtrl::ROW_SHARE_FIRST && DC <= DppCtrl::ROW_XMASK_LAST &&
6587 ST.getGeneration() < AMDGPUSubtarget::GFX10) {
6588 if (DC >= DppCtrl::ROW_NEWBCAST_FIRST &&
6589 DC <= DppCtrl::ROW_NEWBCAST_LAST &&
6590 !ST.hasGFX90AInsts()) {
6591 ErrInfo = "Invalid dpp_ctrl value: "
6592 "row_newbroadcast/row_share is not supported before "
6593 "GFX90A/GFX10";
6594 return false;
6595 }
6596 if (DC > DppCtrl::ROW_NEWBCAST_LAST || !ST.hasGFX90AInsts()) {
6597 ErrInfo = "Invalid dpp_ctrl value: "
6598 "row_share and row_xmask are not supported before GFX10";
6599 return false;
6600 }
6601 }
6602
6603 if (Opcode != AMDGPU::V_MOV_B64_DPP_PSEUDO &&
6605 ST.hasFeature(AMDGPU::FeatureDPALU_DPP) &&
6606 AMDGPU::isDPALU_DPP(Desc, *this, ST)) {
6607 ErrInfo = "Invalid dpp_ctrl value: "
6608 "DP ALU dpp only support row_newbcast";
6609 return false;
6610 }
6611 }
6612
6613 if ((MI.mayStore() || MI.mayLoad()) && !isVGPRSpill(MI)) {
6614 const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
6615 AMDGPU::OpName DataName =
6616 isDS(Opcode) ? AMDGPU::OpName::data0 : AMDGPU::OpName::vdata;
6617 const MachineOperand *Data = getNamedOperand(MI, DataName);
6618 const MachineOperand *Data2 = getNamedOperand(MI, AMDGPU::OpName::data1);
6619 if (Data && !Data->isReg())
6620 Data = nullptr;
6621
6622 if (!ST.hasGFX90AInsts()) {
6623 if ((Dst && RI.isAGPR(MRI, Dst->getReg())) ||
6624 (Data && RI.isAGPR(MRI, Data->getReg())) ||
6625 (Data2 && RI.isAGPR(MRI, Data2->getReg()))) {
6626 ErrInfo = "Invalid register class: "
6627 "agpr loads and stores not supported on this GPU";
6628 return false;
6629 }
6630 }
6631 }
6632
6633 if (ST.needsAlignedVGPRs()) {
6634 const auto isAlignedReg = [&MI, &MRI, this](AMDGPU::OpName OpName) -> bool {
6636 if (!Op)
6637 return true;
6638 Register Reg = Op->getReg();
6639 if (Reg.isPhysical())
6640 return !(RI.getHWRegIndex(Reg) & 1);
6641 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
6642 return RI.getRegSizeInBits(RC) > 32 && RI.isProperlyAlignedRC(RC) &&
6643 !(RI.getChannelFromSubReg(Op->getSubReg()) & 1);
6644 };
6645
6646 if (isMIMG(MI)) {
6647 if (!isAlignedReg(AMDGPU::OpName::vaddr)) {
6648 ErrInfo = "Subtarget requires even aligned vector registers "
6649 "for vaddr operand of image instructions";
6650 return false;
6651 }
6652 }
6653 }
6654
6655 if (Opcode == AMDGPU::V_ACCVGPR_WRITE_B32_e64 && !ST.hasGFX90AInsts()) {
6656 const MachineOperand *Src = getNamedOperand(MI, AMDGPU::OpName::src0);
6657 if (Src->isReg() && RI.isSGPRReg(MRI, Src->getReg())) {
6658 ErrInfo = "Invalid register class: "
6659 "v_accvgpr_write with an SGPR is not supported on this GPU";
6660 return false;
6661 }
6662 }
6663
6664 if (Desc.getOpcode() == AMDGPU::G_AMDGPU_WAVE_ADDRESS) {
6665 const MachineOperand &SrcOp = MI.getOperand(1);
6666 if (!SrcOp.isReg() || SrcOp.getReg().isVirtual()) {
6667 ErrInfo = "pseudo expects only physical SGPRs";
6668 return false;
6669 }
6670 }
6671
6672 if (const MachineOperand *CPol = getNamedOperand(MI, AMDGPU::OpName::cpol)) {
6673 if (CPol->getImm() & AMDGPU::CPol::SCAL) {
6674 if (!ST.hasScaleOffset()) {
6675 ErrInfo = "subtarget does not support offset scaling";
6676 return false;
6677 }
6678 if (!AMDGPU::supportsScaleOffset(*this, MI.getOpcode())) {
6679 ErrInfo = "instruction does not support offset scaling";
6680 return false;
6681 }
6682 }
6683 }
6684
6685 // See SIInstrInfo::isLegalSingleSGPRReadInstOperand for more information.
6686 if (AMDGPU::isSingleSGPRReadInst(Opcode)) {
6687 for (unsigned I = 0; I < 3; ++I) {
6689 return false;
6690 }
6691 }
6692
6693 if (ST.hasFlatScratchHiInB64InstHazard() && isSALU(MI) &&
6694 MI.readsRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_HI, nullptr)) {
6695 const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::sdst);
6696 if ((Dst && RI.getRegClassForReg(MRI, Dst->getReg()) ==
6697 &AMDGPU::SReg_64RegClass) ||
6698 Opcode == AMDGPU::S_BITCMP0_B64 || Opcode == AMDGPU::S_BITCMP1_B64) {
6699 ErrInfo = "Instruction cannot read flat_scratch_base_hi";
6700 return false;
6701 }
6702 }
6703
6704 // GFX950 v_pk_{add,mul,fma}_f32 must not have an invalid op_sel.
6705 if (!isLegalPkF32OpSel(*this, MI)) {
6706 ErrInfo = "GFX950 v_pk_{add,mul,fma}_f32 has an invalid op_sel.";
6707 return false;
6708 }
6709
6710 return true;
6711}
6712
6714 if (MI.getOpcode() == AMDGPU::S_MOV_B32) {
6715 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
6716 return MI.getOperand(1).isReg() || RI.isAGPR(MRI, MI.getOperand(0).getReg())
6717 ? AMDGPU::COPY
6718 : AMDGPU::V_MOV_B32_e32;
6719 }
6720 return getVALUOp(MI.getOpcode());
6721}
6722
6723// It is more readable to list mapped opcodes on the same line.
6724// clang-format off
6725
6726unsigned SIInstrInfo::getVALUOp(unsigned Opc) const {
6727 switch (Opc) {
6728 default: return AMDGPU::INSTRUCTION_LIST_END;
6729 case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
6730 case AMDGPU::COPY: return AMDGPU::COPY;
6731 case AMDGPU::PHI: return AMDGPU::PHI;
6732 case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
6733 case AMDGPU::WQM: return AMDGPU::WQM;
6734 case AMDGPU::SOFT_WQM: return AMDGPU::SOFT_WQM;
6735 case AMDGPU::STRICT_WWM: return AMDGPU::STRICT_WWM;
6736 case AMDGPU::STRICT_WQM: return AMDGPU::STRICT_WQM;
6737 case AMDGPU::S_ADD_I32:
6738 return ST.hasAddNoCarryInsts() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
6739 case AMDGPU::S_ADDC_U32:
6740 return AMDGPU::V_ADDC_U32_e32;
6741 case AMDGPU::S_SUB_I32:
6742 return ST.hasAddNoCarryInsts() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_CO_U32_e32;
6743 // FIXME: These are not consistently handled, and selected when the carry is
6744 // used.
6745 case AMDGPU::S_ADD_U32:
6746 return AMDGPU::V_ADD_CO_U32_e32;
6747 case AMDGPU::S_SUB_U32:
6748 return AMDGPU::V_SUB_CO_U32_e32;
6749 case AMDGPU::S_ADD_U64_PSEUDO:
6750 return AMDGPU::V_ADD_U64_PSEUDO;
6751 case AMDGPU::S_SUB_U64_PSEUDO:
6752 return AMDGPU::V_SUB_U64_PSEUDO;
6753 case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
6754 case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_U32_e64;
6755 case AMDGPU::S_MUL_HI_U32: return AMDGPU::V_MUL_HI_U32_e64;
6756 case AMDGPU::S_MUL_HI_I32: return AMDGPU::V_MUL_HI_I32_e64;
6757 case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
6758 case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
6759 case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
6760 case AMDGPU::S_XNOR_B32:
6761 return ST.hasDLInsts() ? AMDGPU::V_XNOR_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
6762 case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
6763 case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
6764 case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
6765 case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
6766 case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
6767 case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64_e64;
6768 case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
6769 case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64_e64;
6770 case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
6771 case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64_e64;
6772 case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32_e64;
6773 case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32_e64;
6774 case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32_e64;
6775 case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32_e64;
6776 case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
6777 case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
6778 case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
6779 case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
6780 case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e64;
6781 case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e64;
6782 case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e64;
6783 case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e64;
6784 case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e64;
6785 case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e64;
6786 case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e64;
6787 case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e64;
6788 case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e64;
6789 case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e64;
6790 case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e64;
6791 case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e64;
6792 case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e64;
6793 case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e64;
6794 case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
6795 case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
6796 case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
6797 case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
6798 case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
6799 case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
6800 case AMDGPU::S_CVT_F32_I32: return AMDGPU::V_CVT_F32_I32_e64;
6801 case AMDGPU::S_CVT_F32_U32: return AMDGPU::V_CVT_F32_U32_e64;
6802 case AMDGPU::S_CVT_I32_F32: return AMDGPU::V_CVT_I32_F32_e64;
6803 case AMDGPU::S_CVT_U32_F32: return AMDGPU::V_CVT_U32_F32_e64;
6804 case AMDGPU::S_CVT_F32_F16:
6805 case AMDGPU::S_CVT_HI_F32_F16:
6806 return ST.useRealTrue16Insts() ? AMDGPU::V_CVT_F32_F16_t16_e64
6807 : AMDGPU::V_CVT_F32_F16_fake16_e64;
6808 case AMDGPU::S_CVT_F16_F32:
6809 return ST.useRealTrue16Insts() ? AMDGPU::V_CVT_F16_F32_t16_e64
6810 : AMDGPU::V_CVT_F16_F32_fake16_e64;
6811 case AMDGPU::S_CEIL_F32: return AMDGPU::V_CEIL_F32_e64;
6812 case AMDGPU::S_FLOOR_F32: return AMDGPU::V_FLOOR_F32_e64;
6813 case AMDGPU::S_TRUNC_F32: return AMDGPU::V_TRUNC_F32_e64;
6814 case AMDGPU::S_RNDNE_F32: return AMDGPU::V_RNDNE_F32_e64;
6815 case AMDGPU::S_CEIL_F16:
6816 return ST.useRealTrue16Insts() ? AMDGPU::V_CEIL_F16_t16_e64
6817 : AMDGPU::V_CEIL_F16_fake16_e64;
6818 case AMDGPU::S_FLOOR_F16:
6819 return ST.useRealTrue16Insts() ? AMDGPU::V_FLOOR_F16_t16_e64
6820 : AMDGPU::V_FLOOR_F16_fake16_e64;
6821 case AMDGPU::S_TRUNC_F16:
6822 return ST.useRealTrue16Insts() ? AMDGPU::V_TRUNC_F16_t16_e64
6823 : AMDGPU::V_TRUNC_F16_fake16_e64;
6824 case AMDGPU::S_RNDNE_F16:
6825 return ST.useRealTrue16Insts() ? AMDGPU::V_RNDNE_F16_t16_e64
6826 : AMDGPU::V_RNDNE_F16_fake16_e64;
6827 case AMDGPU::S_ADD_F32: return AMDGPU::V_ADD_F32_e64;
6828 case AMDGPU::S_SUB_F32: return AMDGPU::V_SUB_F32_e64;
6829 case AMDGPU::S_MIN_F32: return AMDGPU::V_MIN_F32_e64;
6830 case AMDGPU::S_MAX_F32: return AMDGPU::V_MAX_F32_e64;
6831 case AMDGPU::S_MINIMUM_F32: return AMDGPU::V_MINIMUM_F32_e64;
6832 case AMDGPU::S_MAXIMUM_F32: return AMDGPU::V_MAXIMUM_F32_e64;
6833 case AMDGPU::S_MUL_F32: return AMDGPU::V_MUL_F32_e64;
6834 case AMDGPU::S_ADD_F16:
6835 return ST.useRealTrue16Insts() ? AMDGPU::V_ADD_F16_t16_e64
6836 : AMDGPU::V_ADD_F16_fake16_e64;
6837 case AMDGPU::S_SUB_F16:
6838 return ST.useRealTrue16Insts() ? AMDGPU::V_SUB_F16_t16_e64
6839 : AMDGPU::V_SUB_F16_fake16_e64;
6840 case AMDGPU::S_MIN_F16:
6841 return ST.useRealTrue16Insts() ? AMDGPU::V_MIN_F16_t16_e64
6842 : AMDGPU::V_MIN_F16_fake16_e64;
6843 case AMDGPU::S_MAX_F16:
6844 return ST.useRealTrue16Insts() ? AMDGPU::V_MAX_F16_t16_e64
6845 : AMDGPU::V_MAX_F16_fake16_e64;
6846 case AMDGPU::S_MINIMUM_F16:
6847 return ST.useRealTrue16Insts() ? AMDGPU::V_MINIMUM_F16_t16_e64
6848 : AMDGPU::V_MINIMUM_F16_fake16_e64;
6849 case AMDGPU::S_MAXIMUM_F16:
6850 return ST.useRealTrue16Insts() ? AMDGPU::V_MAXIMUM_F16_t16_e64
6851 : AMDGPU::V_MAXIMUM_F16_fake16_e64;
6852 case AMDGPU::S_MUL_F16:
6853 return ST.useRealTrue16Insts() ? AMDGPU::V_MUL_F16_t16_e64
6854 : AMDGPU::V_MUL_F16_fake16_e64;
6855 case AMDGPU::S_CVT_PK_RTZ_F16_F32: return AMDGPU::V_CVT_PKRTZ_F16_F32_e64;
6856 case AMDGPU::S_FMAC_F32: return AMDGPU::V_FMAC_F32_e64;
6857 case AMDGPU::S_FMAC_F16:
6858 return ST.useRealTrue16Insts() ? AMDGPU::V_FMAC_F16_t16_e64
6859 : AMDGPU::V_FMAC_F16_fake16_e64;
6860 case AMDGPU::S_FMAMK_F32: return AMDGPU::V_FMAMK_F32;
6861 case AMDGPU::S_FMAAK_F32: return AMDGPU::V_FMAAK_F32;
6862 case AMDGPU::S_CMP_LT_F32: return AMDGPU::V_CMP_LT_F32_e64;
6863 case AMDGPU::S_CMP_EQ_F32: return AMDGPU::V_CMP_EQ_F32_e64;
6864 case AMDGPU::S_CMP_LE_F32: return AMDGPU::V_CMP_LE_F32_e64;
6865 case AMDGPU::S_CMP_GT_F32: return AMDGPU::V_CMP_GT_F32_e64;
6866 case AMDGPU::S_CMP_LG_F32: return AMDGPU::V_CMP_LG_F32_e64;
6867 case AMDGPU::S_CMP_GE_F32: return AMDGPU::V_CMP_GE_F32_e64;
6868 case AMDGPU::S_CMP_O_F32: return AMDGPU::V_CMP_O_F32_e64;
6869 case AMDGPU::S_CMP_U_F32: return AMDGPU::V_CMP_U_F32_e64;
6870 case AMDGPU::S_CMP_NGE_F32: return AMDGPU::V_CMP_NGE_F32_e64;
6871 case AMDGPU::S_CMP_NLG_F32: return AMDGPU::V_CMP_NLG_F32_e64;
6872 case AMDGPU::S_CMP_NGT_F32: return AMDGPU::V_CMP_NGT_F32_e64;
6873 case AMDGPU::S_CMP_NLE_F32: return AMDGPU::V_CMP_NLE_F32_e64;
6874 case AMDGPU::S_CMP_NEQ_F32: return AMDGPU::V_CMP_NEQ_F32_e64;
6875 case AMDGPU::S_CMP_NLT_F32: return AMDGPU::V_CMP_NLT_F32_e64;
6876 case AMDGPU::S_CMP_LT_F16:
6877 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_LT_F16_t16_e64
6878 : AMDGPU::V_CMP_LT_F16_fake16_e64;
6879 case AMDGPU::S_CMP_EQ_F16:
6880 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_EQ_F16_t16_e64
6881 : AMDGPU::V_CMP_EQ_F16_fake16_e64;
6882 case AMDGPU::S_CMP_LE_F16:
6883 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_LE_F16_t16_e64
6884 : AMDGPU::V_CMP_LE_F16_fake16_e64;
6885 case AMDGPU::S_CMP_GT_F16:
6886 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_GT_F16_t16_e64
6887 : AMDGPU::V_CMP_GT_F16_fake16_e64;
6888 case AMDGPU::S_CMP_LG_F16:
6889 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_LG_F16_t16_e64
6890 : AMDGPU::V_CMP_LG_F16_fake16_e64;
6891 case AMDGPU::S_CMP_GE_F16:
6892 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_GE_F16_t16_e64
6893 : AMDGPU::V_CMP_GE_F16_fake16_e64;
6894 case AMDGPU::S_CMP_O_F16:
6895 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_O_F16_t16_e64
6896 : AMDGPU::V_CMP_O_F16_fake16_e64;
6897 case AMDGPU::S_CMP_U_F16:
6898 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_U_F16_t16_e64
6899 : AMDGPU::V_CMP_U_F16_fake16_e64;
6900 case AMDGPU::S_CMP_NGE_F16:
6901 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NGE_F16_t16_e64
6902 : AMDGPU::V_CMP_NGE_F16_fake16_e64;
6903 case AMDGPU::S_CMP_NLG_F16:
6904 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NLG_F16_t16_e64
6905 : AMDGPU::V_CMP_NLG_F16_fake16_e64;
6906 case AMDGPU::S_CMP_NGT_F16:
6907 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NGT_F16_t16_e64
6908 : AMDGPU::V_CMP_NGT_F16_fake16_e64;
6909 case AMDGPU::S_CMP_NLE_F16:
6910 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NLE_F16_t16_e64
6911 : AMDGPU::V_CMP_NLE_F16_fake16_e64;
6912 case AMDGPU::S_CMP_NEQ_F16:
6913 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NEQ_F16_t16_e64
6914 : AMDGPU::V_CMP_NEQ_F16_fake16_e64;
6915 case AMDGPU::S_CMP_NLT_F16:
6916 return ST.useRealTrue16Insts() ? AMDGPU::V_CMP_NLT_F16_t16_e64
6917 : AMDGPU::V_CMP_NLT_F16_fake16_e64;
6918 case AMDGPU::V_S_EXP_F32_e64: return AMDGPU::V_EXP_F32_e64;
6919 case AMDGPU::V_S_EXP_F16_e64:
6920 return ST.useRealTrue16Insts() ? AMDGPU::V_EXP_F16_t16_e64
6921 : AMDGPU::V_EXP_F16_fake16_e64;
6922 case AMDGPU::V_S_LOG_F32_e64: return AMDGPU::V_LOG_F32_e64;
6923 case AMDGPU::V_S_LOG_F16_e64:
6924 return ST.useRealTrue16Insts() ? AMDGPU::V_LOG_F16_t16_e64
6925 : AMDGPU::V_LOG_F16_fake16_e64;
6926 case AMDGPU::V_S_RCP_F32_e64: return AMDGPU::V_RCP_F32_e64;
6927 case AMDGPU::V_S_RCP_F16_e64:
6928 return ST.useRealTrue16Insts() ? AMDGPU::V_RCP_F16_t16_e64
6929 : AMDGPU::V_RCP_F16_fake16_e64;
6930 case AMDGPU::V_S_RSQ_F32_e64: return AMDGPU::V_RSQ_F32_e64;
6931 case AMDGPU::V_S_RSQ_F16_e64:
6932 return ST.useRealTrue16Insts() ? AMDGPU::V_RSQ_F16_t16_e64
6933 : AMDGPU::V_RSQ_F16_fake16_e64;
6934 case AMDGPU::V_S_SQRT_F32_e64: return AMDGPU::V_SQRT_F32_e64;
6935 case AMDGPU::V_S_SQRT_F16_e64:
6936 return ST.useRealTrue16Insts() ? AMDGPU::V_SQRT_F16_t16_e64
6937 : AMDGPU::V_SQRT_F16_fake16_e64;
6938 }
6940 "Unexpected scalar opcode without corresponding vector one!");
6941}
6942
6943// clang-format on
6944
6948 const DebugLoc &DL, Register Reg,
6949 bool IsSCCLive,
6950 SlotIndexes *Indexes) const {
6951 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6952 const SIInstrInfo *TII = ST.getInstrInfo();
6954 if (IsSCCLive) {
6955 // Insert two move instructions, one to save the original value of EXEC and
6956 // the other to turn on all bits in EXEC. This is required as we can't use
6957 // the single instruction S_OR_SAVEEXEC that clobbers SCC.
6958 auto StoreExecMI = BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), Reg)
6960 auto FlipExecMI =
6961 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addImm(-1);
6962 if (Indexes) {
6963 Indexes->insertMachineInstrInMaps(*StoreExecMI);
6964 Indexes->insertMachineInstrInMaps(*FlipExecMI);
6965 }
6966 } else {
6967 auto SaveExec =
6968 BuildMI(MBB, MBBI, DL, TII->get(LMC.OrSaveExecOpc), Reg).addImm(-1);
6969 SaveExec->getOperand(3).setIsDead(); // Mark SCC as dead.
6970 if (Indexes)
6971 Indexes->insertMachineInstrInMaps(*SaveExec);
6972 }
6973}
6974
6977 const DebugLoc &DL, Register Reg,
6978 SlotIndexes *Indexes) const {
6980 auto ExecRestoreMI = BuildMI(MBB, MBBI, DL, get(LMC.MovOpc), LMC.ExecReg)
6981 .addReg(Reg, RegState::Kill);
6982 if (Indexes)
6983 Indexes->insertMachineInstrInMaps(*ExecRestoreMI);
6984}
6985
6989 "Not a whole wave func");
6990 MachineBasicBlock &MBB = *MF.begin();
6991 for (MachineInstr &MI : MBB)
6992 if (MI.getOpcode() == AMDGPU::SI_WHOLE_WAVE_FUNC_SETUP ||
6993 MI.getOpcode() == AMDGPU::G_AMDGPU_WHOLE_WAVE_FUNC_SETUP)
6994 return &MI;
6995
6996 llvm_unreachable("Couldn't find SI_SETUP_WHOLE_WAVE_FUNC instruction");
6997}
6998
7000 unsigned OpNo) const {
7001 const MCInstrDesc &Desc = get(MI.getOpcode());
7002 if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
7003 Desc.operands()[OpNo].RegClass == -1) {
7004 Register Reg = MI.getOperand(OpNo).getReg();
7005
7006 if (Reg.isVirtual()) {
7007 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
7008 return MRI.getRegClass(Reg);
7009 }
7010 return RI.getPhysRegBaseClass(Reg);
7011 }
7012
7013 int16_t RegClass = getOpRegClassID(Desc.operands()[OpNo]);
7014 return RegClass < 0 ? nullptr : RI.getRegClass(RegClass);
7015}
7016
7017// Convert VOP3 operand index to source number.
7018static unsigned VOP3OpIdxToSrcN(const MachineInstr &MI, unsigned OpIdx) {
7019 constexpr AMDGPU::OpName OpNames[] = {
7020 AMDGPU::OpName::src0, AMDGPU::OpName::src1, AMDGPU::OpName::src2};
7021
7022 for (auto [I, OpName] : enumerate(OpNames)) {
7023 int SrcIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpNames[I]);
7024 if (static_cast<unsigned>(SrcIdx) == OpIdx)
7025 return I;
7026 }
7027
7028 return UINT_MAX;
7029}
7030
7033 MachineBasicBlock *MBB = MI.getParent();
7034 MachineOperand &MO = MI.getOperand(OpIdx);
7035 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7036 unsigned RCID = getOpRegClassID(get(MI.getOpcode()).operands()[OpIdx]);
7037 const TargetRegisterClass *RC = RI.getRegClass(RCID);
7038 unsigned Size = RI.getRegSizeInBits(*RC);
7039 unsigned Opcode = (Size == 64) ? AMDGPU::V_MOV_B64_PSEUDO
7040 : Size == 16 ? AMDGPU::V_MOV_B16_t16_e64
7041 : AMDGPU::V_MOV_B32_e32;
7042 if (MO.isReg())
7043 Opcode = AMDGPU::COPY;
7044 else if (RI.isSGPRClass(RC))
7045 Opcode = (Size == 64) ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
7046
7047 const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
7048 Register Reg = MRI.createVirtualRegister(VRC);
7049 DebugLoc DL = MBB->findDebugLoc(I);
7050
7051 if (Size == 128 && AMDGPU::isPackedSingleSGPR64BitInst(MI.getOpcode()) &&
7053 // Special case for V_PK_*64 instructions: these do not have OPSEL but SGPR
7054 // sources behave like OPSEL is set replicating low 64-bits into high. VGPR
7055 // sources in turn read actual 4 registers. To move operand from an SGPR to
7056 // a VGPR we need to replicate low half.
7057 // We also do not select immediates for these instructions so it always has
7058 // to be an SGPR register here.
7059 // Operands which are not legal as per isLegalSingleSGPRReadInstOperand()
7060 // sent here specifically to fix a non-splat SGPR and shall perform a full
7061 // copy.
7062
7063 const TargetRegisterClass *VRC64 = RI.getVGPRClassForBitWidth(64);
7064 Register Low64 = MRI.createVirtualRegister(VRC64);
7065 assert(MO.isReg() && RI.isSGPRReg(MRI, MO.getReg()));
7066 BuildMI(*MBB, I, DL, get(TargetOpcode::COPY), Low64)
7067 .addReg(MO.getReg(), {}, AMDGPU::sub0_sub1);
7068 BuildMI(*MBB, I, DL, get(TargetOpcode::REG_SEQUENCE), Reg)
7069 .addReg(Low64)
7070 .addImm(AMDGPU::sub0_sub1)
7071 .addReg(Low64)
7072 .addImm(AMDGPU::sub2_sub3);
7073 } else if (Opcode == AMDGPU::V_MOV_B16_t16_e64) {
7074 BuildMI(*MBB, I, DL, get(Opcode), Reg)
7075 .addImm(0) // src0_modifiers
7076 .add(MO)
7077 .addImm(0); // op_sel
7078 } else {
7079 BuildMI(*MBB, I, DL, get(Opcode), Reg).add(MO);
7080 }
7081
7082 MO.ChangeToRegister(Reg, false);
7083}
7084
7087 const MachineOperand &SuperReg, const TargetRegisterClass *SuperRC,
7088 unsigned SubIdx, const TargetRegisterClass *SubRC) const {
7089 if (!SuperReg.getReg().isVirtual())
7090 return RI.getSubReg(SuperReg.getReg(), SubIdx);
7091
7092 MachineBasicBlock *MBB = MI->getParent();
7093 const DebugLoc &DL = MI->getDebugLoc();
7094 Register SubReg = MRI.createVirtualRegister(SubRC);
7095
7096 unsigned NewSubIdx = RI.composeSubRegIndices(SuperReg.getSubReg(), SubIdx);
7097 BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
7098 .addReg(SuperReg.getReg(), {}, NewSubIdx);
7099 return SubReg;
7100}
7101
7104 const MachineOperand &Op, const TargetRegisterClass *SuperRC,
7105 unsigned SubIdx, const TargetRegisterClass *SubRC) const {
7106 if (Op.isImm()) {
7107 if (SubIdx == AMDGPU::sub0)
7108 return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
7109 if (SubIdx == AMDGPU::sub1)
7110 return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
7111
7112 llvm_unreachable("Unhandled register index for immediate");
7113 }
7114
7115 unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
7116 SubIdx, SubRC);
7117 return MachineOperand::CreateReg(SubReg, false);
7118}
7119
7120// Change the order of operands from (0, 1, 2) to (0, 2, 1)
7121void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
7122 assert(Inst.getNumExplicitOperands() == 3);
7123 MachineOperand Op1 = Inst.getOperand(1);
7124 Inst.removeOperand(1);
7125 Inst.addOperand(Op1);
7126}
7127
7129 const MCOperandInfo &OpInfo,
7130 const MachineOperand &MO) const {
7131 if (!MO.isReg())
7132 return false;
7133
7134 Register Reg = MO.getReg();
7135
7136 const TargetRegisterClass *DRC = RI.getRegClass(getOpRegClassID(OpInfo));
7137 if (Reg.isPhysical())
7138 return DRC->contains(Reg);
7139
7140 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
7141
7142 if (MO.getSubReg()) {
7143 const TargetRegisterClass *SuperRC =
7144 RI.getLargestLegalSuperClass(RC, MRI.getMF());
7145 if (!SuperRC)
7146 return false;
7147 return RI.getMatchingSuperRegClass(SuperRC, DRC, MO.getSubReg()) != nullptr;
7148 }
7149
7150 return RI.getCommonSubClass(DRC, RC) != nullptr;
7151}
7152
7154 const MachineOperand &MO) const {
7155 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
7156 const MCOperandInfo OpInfo = MI.getDesc().operands()[OpIdx];
7157 unsigned Opc = MI.getOpcode();
7158
7159 // See SIInstrInfo::isLegalSingleSGPRReadInstOperand for more information.
7160 if (MO.isReg() && RI.isSGPRReg(MRI, MO.getReg()) &&
7161 AMDGPU::isSingleSGPRReadInst(MI.getOpcode()) &&
7163 &MO))
7164 return false;
7165
7166 if (!isLegalRegOperand(MRI, OpInfo, MO))
7167 return false;
7168
7169 // check Accumulate GPR operand
7170 bool IsAGPR = RI.isAGPR(MRI, MO.getReg());
7171 if (IsAGPR && !ST.hasMAIInsts())
7172 return false;
7173 if (IsAGPR && (!ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
7174 (MI.mayLoad() || MI.mayStore() || isDS(Opc) || isMIMG(Opc)))
7175 return false;
7176 // Atomics should have both vdst and vdata either vgpr or agpr.
7177 const int VDstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
7178 const int DataIdx = AMDGPU::getNamedOperandIdx(
7179 Opc, isDS(Opc) ? AMDGPU::OpName::data0 : AMDGPU::OpName::vdata);
7180 if ((int)OpIdx == VDstIdx && DataIdx != -1 &&
7181 MI.getOperand(DataIdx).isReg() &&
7182 RI.isAGPR(MRI, MI.getOperand(DataIdx).getReg()) != IsAGPR)
7183 return false;
7184 if ((int)OpIdx == DataIdx) {
7185 if (VDstIdx != -1 &&
7186 RI.isAGPR(MRI, MI.getOperand(VDstIdx).getReg()) != IsAGPR)
7187 return false;
7188 // DS instructions with 2 src operands also must have tied RC.
7189 const int Data1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data1);
7190 if (Data1Idx != -1 && MI.getOperand(Data1Idx).isReg() &&
7191 RI.isAGPR(MRI, MI.getOperand(Data1Idx).getReg()) != IsAGPR)
7192 return false;
7193 }
7194
7195 // Check V_ACCVGPR_WRITE_B32_e64
7196 if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64 && !ST.hasGFX90AInsts() &&
7197 (int)OpIdx == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) &&
7198 RI.isSGPRReg(MRI, MO.getReg()))
7199 return false;
7200
7201 if (ST.hasFlatScratchHiInB64InstHazard() &&
7202 MO.getReg() == AMDGPU::SRC_FLAT_SCRATCH_BASE_HI && isSALU(MI)) {
7203 if (const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::sdst)) {
7204 if (AMDGPU::getRegBitWidth(*RI.getRegClassForReg(MRI, Dst->getReg())) ==
7205 64)
7206 return false;
7207 }
7208 if (Opc == AMDGPU::S_BITCMP0_B64 || Opc == AMDGPU::S_BITCMP1_B64)
7209 return false;
7210 }
7211 if ((!ST.hasDPPSrc1SGPR() || AMDGPU::isVOP3DPPSrc1RevOpc(ST, Opc)) &&
7212 isDPP(MI) && RI.isSGPRReg(MRI, MO.getReg()) &&
7213 (int)OpIdx == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1))
7214 return false;
7215
7216 return true;
7217}
7218
7220 const MachineRegisterInfo &MRI, const MachineInstr &MI, unsigned SrcN,
7221 const MachineOperand *MO) const {
7222 constexpr unsigned NumOps = 3;
7223 constexpr AMDGPU::OpName OpNames[NumOps * 2] = {
7224 AMDGPU::OpName::src0, AMDGPU::OpName::src1,
7225 AMDGPU::OpName::src2, AMDGPU::OpName::src0_modifiers,
7226 AMDGPU::OpName::src1_modifiers, AMDGPU::OpName::src2_modifiers};
7227
7228 assert(SrcN < NumOps);
7229
7230 if (!MO) {
7231 int SrcIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpNames[SrcN]);
7232 if (SrcIdx == -1)
7233 return true;
7234 MO = &MI.getOperand(SrcIdx);
7235 }
7236
7237 if (!MO->isReg() || !RI.isSGPRReg(MRI, MO->getReg()))
7238 return true;
7239
7240 int ModsIdx =
7241 AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpNames[NumOps + SrcN]);
7242 if (ModsIdx == -1)
7243 return false;
7244
7245 unsigned Mods = MI.getOperand(ModsIdx).getImm();
7246 bool OpSel = Mods & SISrcMods::OP_SEL_0;
7247 bool OpSelHi = Mods & SISrcMods::OP_SEL_1;
7248
7249 return !OpSel && !OpSelHi;
7250}
7251
7252bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
7253 const MachineOperand *MO) const {
7254 const MachineFunction &MF = *MI.getMF();
7255 const MachineRegisterInfo &MRI = MF.getRegInfo();
7256 const MCInstrDesc &InstDesc = MI.getDesc();
7257 const MCOperandInfo &OpInfo = InstDesc.operands()[OpIdx];
7258 int64_t RegClass = getOpRegClassID(OpInfo);
7259 const TargetRegisterClass *DefinedRC =
7260 RegClass != -1 ? RI.getRegClass(RegClass) : nullptr;
7261 if (!MO)
7262 MO = &MI.getOperand(OpIdx);
7263
7264 const bool IsInlineConst = !MO->isReg() && isInlineConstant(*MO, OpInfo);
7265
7266 if (isVALU(MI, /*AllowLDSDMA=*/false) && !IsInlineConst &&
7267 usesConstantBus(MRI, *MO, OpInfo)) {
7268 const MachineOperand *UsedLiteral = nullptr;
7269
7270 int ConstantBusLimit = ST.getConstantBusLimit(MI.getOpcode());
7271 int LiteralLimit = !isVOP3(MI) || ST.hasVOP3Literal() ? 1 : 0;
7272
7273 // TODO: Be more permissive with frame indexes.
7274 if (!MO->isReg() && !isInlineConstant(*MO, OpInfo)) {
7275 if (!LiteralLimit--)
7276 return false;
7277
7278 UsedLiteral = MO;
7279 }
7280
7282 if (MO->isReg())
7283 SGPRsUsed.insert(RegSubRegPair(MO->getReg(), MO->getSubReg()));
7284
7285 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
7286 if (i == OpIdx)
7287 continue;
7288 const MachineOperand &Op = MI.getOperand(i);
7289 if (Op.isReg()) {
7290 if (Op.isUse()) {
7291 RegSubRegPair SGPR(Op.getReg(), Op.getSubReg());
7292 if (regUsesConstantBus(Op, MRI) && SGPRsUsed.insert(SGPR).second) {
7293 if (--ConstantBusLimit <= 0)
7294 return false;
7295 }
7296 }
7297 } else if (AMDGPU::isSISrcOperand(InstDesc.operands()[i]) &&
7298 !isInlineConstant(Op, InstDesc.operands()[i])) {
7299 // The same literal may be used multiple times.
7300 if (!UsedLiteral)
7301 UsedLiteral = &Op;
7302 else if (UsedLiteral->isIdenticalTo(Op))
7303 continue;
7304
7305 if (!LiteralLimit--)
7306 return false;
7307 if (--ConstantBusLimit <= 0)
7308 return false;
7309 }
7310 }
7311 } else if (!IsInlineConst && !MO->isReg() && isSALU(MI)) {
7312 // There can be at most one literal operand, but it can be repeated.
7313 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
7314 if (i == OpIdx)
7315 continue;
7316 const MachineOperand &Op = MI.getOperand(i);
7317 if (!Op.isReg() && !Op.isFI() && !Op.isRegMask() &&
7318 !isInlineConstant(Op, InstDesc.operands()[i]) &&
7319 !Op.isIdenticalTo(*MO))
7320 return false;
7321
7322 // Do not fold a non-inlineable and non-register operand into an
7323 // instruction that already has a frame index. The frame index handling
7324 // code could not handle well when a frame index co-exists with another
7325 // non-register operand, unless that operand is an inlineable immediate.
7326 if (Op.isFI())
7327 return false;
7328 }
7329 }
7330
7331 if (MO->isReg()) {
7332 if (!DefinedRC)
7333 return OpInfo.OperandType == MCOI::OPERAND_UNKNOWN;
7334 return isLegalRegOperand(MI, OpIdx, *MO);
7335 }
7336
7337 if (MO->isImm()) {
7338 uint64_t Imm = MO->getImm();
7339 bool Is64BitFPOp = OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_FP64 ||
7340 OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_V2FP64;
7341 bool Is64BitOp = Is64BitFPOp ||
7342 OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_INT64 ||
7343 OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_V2INT32 ||
7344 OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_V2FP32 ||
7345 OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_V2INT64;
7346 if (Is64BitOp &&
7347 !AMDGPU::isInlinableLiteral64(Imm, ST.hasInv2PiInlineImm())) {
7348 if (!AMDGPU::isValid32BitLiteral(Imm, Is64BitFPOp) &&
7349 (!ST.has64BitLiterals() || InstDesc.getSize() != 4))
7350 return false;
7351
7352 // FIXME: We can use sign extended 64-bit literals, but only for signed
7353 // operands. At the moment we do not know if an operand is signed.
7354 // Such operand will be encoded as its low 32 bits and then either
7355 // correctly sign extended or incorrectly zero extended by HW.
7356 // If 64-bit literals are supported and the literal will be encoded
7357 // as full 64 bit we still can use it.
7358 if (!Is64BitFPOp && (int32_t)Imm < 0 &&
7359 (!ST.has64BitLiterals() || AMDGPU::isValid32BitLiteral(Imm, false)))
7360 return false;
7361 }
7362
7363 if (IsInlineConst && !isImmOpSelLegal(ST, MI, OpIdx, Imm))
7364 return false;
7365 }
7366
7367 // Handle non-register types that are treated like immediates.
7368 assert(MO->isImm() || MO->isTargetIndex() || MO->isFI() || MO->isGlobal());
7369
7370 if (!DefinedRC) {
7371 // This operand expects an immediate.
7372 return true;
7373 }
7374
7375 return isImmOperandLegal(MI, OpIdx, *MO);
7376}
7377
7379 bool IsGFX950Only = ST.hasGFX950Insts();
7380 bool IsGFX940Only = ST.hasGFX940Insts();
7381
7382 if (!IsGFX950Only && !IsGFX940Only)
7383 return false;
7384
7385 if (!isVALU(MI, /*AllowLDSDMA=*/false))
7386 return false;
7387
7388 // V_COS, V_EXP, V_RCP, etc.
7389 if (isTRANS(MI))
7390 return true;
7391
7392 // DOT2, DOT2C, DOT4, etc.
7393 if (isDOT(MI))
7394 return true;
7395
7396 // MFMA, SMFMA
7397 if (isMFMA(MI))
7398 return true;
7399
7400 unsigned Opcode = MI.getOpcode();
7401 switch (Opcode) {
7402 case AMDGPU::V_CVT_PK_BF8_F32_e64:
7403 case AMDGPU::V_CVT_PK_FP8_F32_e64:
7404 case AMDGPU::V_MQSAD_PK_U16_U8_e64:
7405 case AMDGPU::V_MQSAD_U32_U8_e64:
7406 case AMDGPU::V_PK_ADD_F16:
7407 case AMDGPU::V_PK_ADD_F32:
7408 case AMDGPU::V_PK_ADD_I16:
7409 case AMDGPU::V_PK_ADD_U16:
7410 case AMDGPU::V_PK_ASHRREV_I16:
7411 case AMDGPU::V_PK_FMA_F16:
7412 case AMDGPU::V_PK_FMA_F32:
7413 case AMDGPU::V_PK_FMAC_F16_e32:
7414 case AMDGPU::V_PK_FMAC_F16_e64:
7415 case AMDGPU::V_PK_LSHLREV_B16:
7416 case AMDGPU::V_PK_LSHRREV_B16:
7417 case AMDGPU::V_PK_MAD_I16:
7418 case AMDGPU::V_PK_MAD_U16:
7419 case AMDGPU::V_PK_MAX_F16:
7420 case AMDGPU::V_PK_MAX_I16:
7421 case AMDGPU::V_PK_MAX_U16:
7422 case AMDGPU::V_PK_MIN_F16:
7423 case AMDGPU::V_PK_MIN_I16:
7424 case AMDGPU::V_PK_MIN_U16:
7425 case AMDGPU::V_PK_MOV_B32:
7426 case AMDGPU::V_PK_MUL_F16:
7427 case AMDGPU::V_PK_MUL_F32:
7428 case AMDGPU::V_PK_MUL_LO_U16:
7429 case AMDGPU::V_PK_SUB_I16:
7430 case AMDGPU::V_PK_SUB_U16:
7431 case AMDGPU::V_QSAD_PK_U16_U8_e64:
7432 return true;
7433 default:
7434 return false;
7435 }
7436}
7437
7439 MachineInstr &MI) const {
7440 unsigned Opc = MI.getOpcode();
7441 const MCInstrDesc &InstrDesc = get(Opc);
7442
7443 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
7444 MachineOperand &Src0 = MI.getOperand(Src0Idx);
7445
7446 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
7447 MachineOperand &Src1 = MI.getOperand(Src1Idx);
7448
7449 // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
7450 // we need to only have one constant bus use before GFX10.
7451 bool HasImplicitSGPR = findImplicitSGPRRead(MI);
7452 if (HasImplicitSGPR && ST.getConstantBusLimit(Opc) <= 1 && Src0.isReg() &&
7453 RI.isSGPRReg(MRI, Src0.getReg()))
7454 legalizeOpWithMove(MI, Src0Idx);
7455
7456 // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
7457 // both the value to write (src0) and lane select (src1). Fix up non-SGPR
7458 // src0/src1 with V_READFIRSTLANE.
7459 if (Opc == AMDGPU::V_WRITELANE_B32) {
7460 const DebugLoc &DL = MI.getDebugLoc();
7461 if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
7462 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7463 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
7464 .add(Src0);
7465 Src0.ChangeToRegister(Reg, false);
7466 }
7467 if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
7468 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7469 const DebugLoc &DL = MI.getDebugLoc();
7470 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
7471 .add(Src1);
7472 Src1.ChangeToRegister(Reg, false);
7473 }
7474 return;
7475 }
7476
7477 // Special case: V_FMAC_F32 and V_FMAC_F16 have src2.
7478 if (Opc == AMDGPU::V_FMAC_F32_e32 || Opc == AMDGPU::V_FMAC_F16_e32) {
7479 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
7480 if (!RI.isVGPR(MRI, MI.getOperand(Src2Idx).getReg()))
7481 legalizeOpWithMove(MI, Src2Idx);
7482 }
7483
7484 // VOP2 src0 instructions support all operand types, so we don't need to check
7485 // their legality. If src1 is already legal, we don't need to do anything.
7486 if (isLegalRegOperand(MRI, InstrDesc.operands()[Src1Idx], Src1))
7487 return;
7488
7489 // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
7490 // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
7491 // select is uniform.
7492 if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
7493 RI.isVGPR(MRI, Src1.getReg())) {
7494 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7495 const DebugLoc &DL = MI.getDebugLoc();
7496 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
7497 .add(Src1);
7498 Src1.ChangeToRegister(Reg, false);
7499 return;
7500 }
7501
7502 // We do not use commuteInstruction here because it is too aggressive and will
7503 // commute if it is possible. We only want to commute here if it improves
7504 // legality. This can be called a fairly large number of times so don't waste
7505 // compile time pointlessly swapping and checking legality again.
7506 if (HasImplicitSGPR || !MI.isCommutable()) {
7507 legalizeOpWithMove(MI, Src1Idx);
7508 return;
7509 }
7510
7511 // If src0 can be used as src1, commuting will make the operands legal.
7512 // Otherwise we have to give up and insert a move.
7513 //
7514 // TODO: Other immediate-like operand kinds could be commuted if there was a
7515 // MachineOperand::ChangeTo* for them.
7516 if ((!Src1.isImm() && !Src1.isReg()) ||
7517 !isLegalRegOperand(MRI, InstrDesc.operands()[Src1Idx], Src0)) {
7518 legalizeOpWithMove(MI, Src1Idx);
7519 return;
7520 }
7521
7522 int CommutedOpc = commuteOpcode(MI);
7523 if (CommutedOpc == -1) {
7524 legalizeOpWithMove(MI, Src1Idx);
7525 return;
7526 }
7527
7528 MI.setDesc(get(CommutedOpc));
7529
7530 Register Src0Reg = Src0.getReg();
7531 unsigned Src0SubReg = Src0.getSubReg();
7532 bool Src0Kill = Src0.isKill();
7533
7534 if (Src1.isImm())
7535 Src0.ChangeToImmediate(Src1.getImm());
7536 else if (Src1.isReg()) {
7537 Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
7538 Src0.setSubReg(Src1.getSubReg());
7539 } else
7540 llvm_unreachable("Should only have register or immediate operands");
7541
7542 Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
7543 Src1.setSubReg(Src0SubReg);
7545}
7546
7547// Legalize VOP3 operands. All operand types are supported for any operand
7548// but only one literal constant and only starting from GFX10.
7550 MachineInstr &MI) const {
7551 unsigned Opc = MI.getOpcode();
7552
7553 int VOP3Idx[3] = {
7554 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
7555 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
7556 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
7557 };
7558
7559 if (Opc == AMDGPU::V_PERMLANE16_B32_e64 ||
7560 Opc == AMDGPU::V_PERMLANEX16_B32_e64 ||
7561 Opc == AMDGPU::V_PERMLANE_BCAST_B32_e64 ||
7562 Opc == AMDGPU::V_PERMLANE_UP_B32_e64 ||
7563 Opc == AMDGPU::V_PERMLANE_DOWN_B32_e64 ||
7564 Opc == AMDGPU::V_PERMLANE_XOR_B32_e64 ||
7565 Opc == AMDGPU::V_PERMLANE_IDX_GEN_B32_e64) {
7566 // src1 and src2 must be scalar
7567 MachineOperand &Src1 = MI.getOperand(VOP3Idx[1]);
7568 const DebugLoc &DL = MI.getDebugLoc();
7569 if (Src1.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src1.getReg()))) {
7570 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7571 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
7572 .add(Src1);
7573 Src1.ChangeToRegister(Reg, false);
7574 }
7575 if (VOP3Idx[2] != -1) {
7576 MachineOperand &Src2 = MI.getOperand(VOP3Idx[2]);
7577 if (Src2.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src2.getReg()))) {
7578 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7579 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
7580 .add(Src2);
7581 Src2.ChangeToRegister(Reg, false);
7582 }
7583 }
7584 }
7585
7586 // Find the one SGPR operand we are allowed to use.
7587 int ConstantBusLimit = ST.getConstantBusLimit(Opc);
7588 int LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
7589 SmallDenseSet<unsigned> SGPRsUsed;
7590 Register SGPRReg = findUsedSGPR(MI, VOP3Idx);
7591 if (SGPRReg) {
7592 SGPRsUsed.insert(SGPRReg);
7593 --ConstantBusLimit;
7594 }
7595
7596 for (int Idx : VOP3Idx) {
7597 if (Idx == -1)
7598 break;
7599 MachineOperand &MO = MI.getOperand(Idx);
7600
7601 if (!MO.isReg()) {
7602 if (isInlineConstant(MO, get(Opc).operands()[Idx]))
7603 continue;
7604
7605 if (LiteralLimit > 0 && ConstantBusLimit > 0) {
7606 --LiteralLimit;
7607 --ConstantBusLimit;
7608 continue;
7609 }
7610
7611 --LiteralLimit;
7612 --ConstantBusLimit;
7613 legalizeOpWithMove(MI, Idx);
7614 continue;
7615 }
7616
7617 if (!RI.isSGPRClass(RI.getRegClassForReg(MRI, MO.getReg())))
7618 continue; // VGPRs are legal
7619
7620 // We can use one SGPR in each VOP3 instruction prior to GFX10
7621 // and two starting from GFX10.
7622 if (SGPRsUsed.count(MO.getReg()))
7623 continue;
7624 if (ConstantBusLimit > 0) {
7625 SGPRsUsed.insert(MO.getReg());
7626 --ConstantBusLimit;
7627 continue;
7628 }
7629
7630 // If we make it this far, then the operand is not legal and we must
7631 // legalize it.
7632 legalizeOpWithMove(MI, Idx);
7633 }
7634
7635 // Special case: V_FMAC_F32 and V_FMAC_F16 have src2 tied to vdst.
7636 if ((Opc == AMDGPU::V_FMAC_F32_e64 || Opc == AMDGPU::V_FMAC_F16_e64 ||
7637 Opc == AMDGPU::V_FMAC_F16_fake16_e64 ||
7638 Opc == AMDGPU::V_FMAC_F16_t16_e64) &&
7639 !RI.isVGPR(MRI, MI.getOperand(VOP3Idx[2]).getReg()))
7640 legalizeOpWithMove(MI, VOP3Idx[2]);
7641
7642 // Fix the register class of single-sgpr-read instructions on gfx12+. See
7643 // SIInstrInfo::isLegalSingleSGPRReadInstOperand for more information.
7645 for (unsigned I = 0; I < 3; ++I) {
7646 if (!isLegalSingleSGPRReadInstOperand(MRI, MI, /*SrcN=*/I))
7647 legalizeOpWithMove(MI, VOP3Idx[I]);
7648 }
7649 }
7650}
7651
7654 const TargetRegisterClass *DstRC /*=nullptr*/) const {
7655 const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
7656 const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
7657 if (DstRC)
7658 SRC = RI.getCommonSubClass(SRC, DstRC);
7659
7660 Register DstReg = MRI.createVirtualRegister(SRC);
7661 unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
7662
7663 if (RI.hasAGPRs(VRC)) {
7664 VRC = RI.getEquivalentVGPRClass(VRC);
7665 Register NewSrcReg = MRI.createVirtualRegister(VRC);
7666 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
7667 get(TargetOpcode::COPY), NewSrcReg)
7668 .addReg(SrcReg);
7669 SrcReg = NewSrcReg;
7670 }
7671
7672 if (SubRegs == 1) {
7673 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
7674 get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
7675 .addReg(SrcReg);
7676 return DstReg;
7677 }
7678
7680 for (unsigned i = 0; i < SubRegs; ++i) {
7681 Register SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
7682 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
7683 get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
7684 .addReg(SrcReg, {}, RI.getSubRegFromChannel(i));
7685 SRegs.push_back(SGPR);
7686 }
7687
7689 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
7690 get(AMDGPU::REG_SEQUENCE), DstReg);
7691 for (unsigned i = 0; i < SubRegs; ++i) {
7692 MIB.addReg(SRegs[i]);
7693 MIB.addImm(RI.getSubRegFromChannel(i));
7694 }
7695 return DstReg;
7696}
7697
7699 MachineInstr &MI) const {
7700
7701 // If the pointer is store in VGPRs, then we need to move them to
7702 // SGPRs using v_readfirstlane. This is safe because we only select
7703 // loads with uniform pointers to SMRD instruction so we know the
7704 // pointer value is uniform.
7705 MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
7706 if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
7707 Register SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
7708 SBase->setReg(SGPR);
7709 }
7710 MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soffset);
7711 if (SOff && !RI.isSGPRReg(MRI, SOff->getReg())) {
7712 Register SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
7713 SOff->setReg(SGPR);
7714 }
7715}
7716
7718 unsigned Opc = Inst.getOpcode();
7719 int OldSAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
7720 if (OldSAddrIdx < 0)
7721 return false;
7722
7723 assert(isSegmentSpecificFLAT(Inst) || (isFLAT(Inst) && ST.hasFlatGVSMode()));
7724
7725 int NewOpc = AMDGPU::getGlobalVaddrOp(Opc);
7726 if (NewOpc < 0)
7728 if (NewOpc < 0)
7729 return false;
7730
7732 MachineOperand &SAddr = Inst.getOperand(OldSAddrIdx);
7733 if (RI.isSGPRReg(MRI, SAddr.getReg()))
7734 return false;
7735
7736 int NewVAddrIdx = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vaddr);
7737 if (NewVAddrIdx < 0)
7738 return false;
7739
7740 int OldVAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
7741
7742 // Check vaddr, it shall be zero or absent.
7743 MachineInstr *VAddrDef = nullptr;
7744 if (OldVAddrIdx >= 0) {
7745 MachineOperand &VAddr = Inst.getOperand(OldVAddrIdx);
7746 VAddrDef = MRI.getUniqueVRegDef(VAddr.getReg());
7747 if (!VAddrDef || !VAddrDef->isMoveImmediate() ||
7748 !VAddrDef->getOperand(1).isImm() ||
7749 VAddrDef->getOperand(1).getImm() != 0)
7750 return false;
7751 }
7752
7753 const MCInstrDesc &NewDesc = get(NewOpc);
7754 Inst.setDesc(NewDesc);
7755
7756 // Callers expect iterator to be valid after this call, so modify the
7757 // instruction in place.
7758 if (OldVAddrIdx == NewVAddrIdx) {
7759 MachineOperand &NewVAddr = Inst.getOperand(NewVAddrIdx);
7760 // Clear use list from the old vaddr holding a zero register.
7761 MRI.removeRegOperandFromUseList(&NewVAddr);
7762 MRI.moveOperands(&NewVAddr, &SAddr, 1);
7763 Inst.removeOperand(OldSAddrIdx);
7764 // Update the use list with the pointer we have just moved from vaddr to
7765 // saddr position. Otherwise new vaddr will be missing from the use list.
7766 MRI.removeRegOperandFromUseList(&NewVAddr);
7767 MRI.addRegOperandToUseList(&NewVAddr);
7768 } else {
7769 assert(OldSAddrIdx == NewVAddrIdx);
7770
7771 if (OldVAddrIdx >= 0) {
7772 int NewVDstIn = AMDGPU::getNamedOperandIdx(NewOpc,
7773 AMDGPU::OpName::vdst_in);
7774
7775 // removeOperand doesn't try to fixup tied operand indexes at it goes, so
7776 // it asserts. Untie the operands for now and retie them afterwards.
7777 if (NewVDstIn != -1) {
7778 int OldVDstIn = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
7779 Inst.untieRegOperand(OldVDstIn);
7780 }
7781
7782 Inst.removeOperand(OldVAddrIdx);
7783
7784 if (NewVDstIn != -1) {
7785 int NewVDst = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vdst);
7786 Inst.tieOperands(NewVDst, NewVDstIn);
7787 }
7788 }
7789 }
7790
7791 if (VAddrDef && MRI.use_nodbg_empty(VAddrDef->getOperand(0).getReg()))
7792 VAddrDef->eraseFromParent();
7793
7794 return true;
7795}
7796
7797// FIXME: Remove this when SelectionDAG is obsoleted.
7799 MachineInstr &MI) const {
7800 if (!isSegmentSpecificFLAT(MI) && !ST.hasFlatGVSMode())
7801 return;
7802
7803 // Fixup SGPR operands in VGPRs. We only select these when the DAG divergence
7804 // thinks they are uniform, so a readfirstlane should be valid.
7805 MachineOperand *SAddr = getNamedOperand(MI, AMDGPU::OpName::saddr);
7806 if (!SAddr || RI.isSGPRClass(MRI.getRegClass(SAddr->getReg())))
7807 return;
7808
7810 return;
7811
7812 const TargetRegisterClass *DeclaredRC =
7813 getRegClass(MI.getDesc(), SAddr->getOperandNo());
7814
7815 Register ToSGPR = readlaneVGPRToSGPR(SAddr->getReg(), MI, MRI, DeclaredRC);
7816 SAddr->setReg(ToSGPR);
7817}
7818
7821 const TargetRegisterClass *DstRC,
7824 const DebugLoc &DL) const {
7825 Register OpReg = Op.getReg();
7826 unsigned OpSubReg = Op.getSubReg();
7827
7828 const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
7829 RI.getRegClassForReg(MRI, OpReg), OpSubReg);
7830
7831 // Check if operand is already the correct register class.
7832 if (DstRC == OpRC)
7833 return;
7834
7835 Register DstReg = MRI.createVirtualRegister(DstRC);
7836 auto Copy = BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg)
7837 .addReg(OpReg, {}, OpSubReg);
7838 Op.setReg(DstReg);
7839 Op.setSubReg(AMDGPU::NoSubRegister);
7840
7841 MachineInstr *Def = MRI.getVRegDef(OpReg);
7842 if (!Def)
7843 return;
7844
7845 // Try to eliminate the copy if it is copying an immediate value.
7846 if (Def->isMoveImmediate() && DstRC != &AMDGPU::VReg_1RegClass)
7847 foldImmediate(*Copy, *Def, OpReg, &MRI);
7848
7849 bool ImpDef = Def->isImplicitDef();
7850 while (!ImpDef && Def && Def->isCopy()) {
7851 if (Def->getOperand(1).getReg().isPhysical())
7852 break;
7853 Def = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
7854 ImpDef = Def && Def->isImplicitDef();
7855 }
7856 if (!RI.isSGPRClass(DstRC) && !Copy->readsRegister(AMDGPU::EXEC, &RI) &&
7857 !ImpDef)
7858 Copy.addReg(AMDGPU::EXEC, RegState::Implicit);
7859}
7860
7861// Emit the actual waterfall loop, executing the wrapped instruction for each
7862// unique value of \p ScalarOps across all lanes. In the best case we execute 1
7863// iteration, in the worst case we execute 64 (once per lane).
7866 MachineBasicBlock &LoopBB, MachineBasicBlock &BodyBB, const DebugLoc &DL,
7867 ArrayRef<MachineOperand *> ScalarOps, ArrayRef<Register> PhySGPRs = {}) {
7868 MachineFunction &MF = *LoopBB.getParent();
7870 const SIRegisterInfo *TRI = ST.getRegisterInfo();
7872 const auto *BoolXExecRC = TRI->getWaveMaskRegClass();
7873
7874 // Emit v_cmpx_eq and s_andn2_wrexec when both instructions are
7875 // available. Otherwise, use the previous pattern of v_cmp_eq,
7876 // s_and_saveexec, and s_xor.
7877 bool UseNewExecInstructions =
7878 ST.hasNoSdstCMPX() && TII.pseudoToMCOpcode(LMC.AndN2WrExecOpc) != -1;
7879
7881 Register CondReg;
7882
7883 Register PhiExec;
7884 Register NewExec;
7885
7886 if (UseNewExecInstructions) {
7887 PhiExec = MRI.createVirtualRegister(BoolXExecRC);
7888 NewExec = MRI.createVirtualRegister(BoolXExecRC);
7889 Register InitExec = MRI.createVirtualRegister(BoolXExecRC);
7890 BuildMI(PredBB, PredBB.end(), DL, TII.get(LMC.MovOpc), InitExec)
7891 .addReg(LMC.ExecReg);
7892
7893 BuildMI(LoopBB, I, DL, TII.get(TargetOpcode::PHI), PhiExec)
7894 .addReg(InitExec)
7895 .addMBB(&PredBB)
7896 .addReg(NewExec)
7897 .addMBB(&BodyBB);
7898 }
7899
7900 // Placement of v_cmpx instructions (when index is longer than 64 bit)
7901 // involves a trade-off between register pressure and latency:
7902 // (a) Defering all v_cmpx after all v_readfirstlane may increase
7903 // register pressure because arguments and results of all
7904 // v_readfirstlane instructions must stay live until deferred v_cmpx use them.
7905 // (b) Interleaving v_cmpx with v_readfirstlanes may reduce live ranges and
7906 // increase latency by placing v_readfirstlane instructions
7907 // immediately before v_cmpx instruction that directly depend on it.
7908 ///
7909 // Emitting interleaved v_cmpx and v_readfirstlane requires
7910 // block splitting because v_cmpx changes EXEC mask and therefore for safety
7911 // v_cmpx needs to be treated as terminator until after register allocation
7912 // (spill placement) and instruction reordering.
7913 //
7914 // Current implementation defers v_cmpx and leaves other instruction
7915 // scheduling decisions to later passes, where register pressure is known or
7916 // easier to approximate.
7917 // Non-terminators (V_READFIRSTLANE and REG_SEQUENCE) are inserted before I;
7918 // v_cmpx instructions are inserted at the end of LoopBB.
7919 // After the first v_cmpx is emitted, I is updated to point to it
7920 // so subsequent non-terminators are inserted before all v_cmpx instructions.
7921 for (auto [Idx, ScalarOp] : enumerate(ScalarOps)) {
7922 unsigned RegSize = TRI->getRegSizeInBits(ScalarOp->getReg(), MRI);
7923 unsigned NumSubRegs = RegSize / 32;
7924 Register VScalarOp = ScalarOp->getReg();
7925
7926 const TargetRegisterClass *RFLSrcRC =
7927 TII.getRegClass(TII.get(AMDGPU::V_READFIRSTLANE_B32), 1);
7928
7929 if (NumSubRegs == 1) {
7930 const TargetRegisterClass *VScalarOpRC = MRI.getRegClass(VScalarOp);
7931 if (const TargetRegisterClass *Common =
7932 TRI->getCommonSubClass(VScalarOpRC, RFLSrcRC);
7933 Common != VScalarOpRC) {
7934 Register VRReg = MRI.createVirtualRegister(Common);
7935 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::COPY), VRReg).addReg(VScalarOp);
7936 VScalarOp = VRReg;
7937 }
7938 Register CurReg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7939
7940 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurReg)
7941 .addReg(VScalarOp);
7942
7943 if (UseNewExecInstructions) {
7944 auto CmpxMI = BuildMI(LoopBB, LoopBB.end(), DL,
7945 TII.get(AMDGPU::V_CMPX_EQ_U32_nosdst_e32_term))
7946 .addReg(CurReg)
7947 .addReg(VScalarOp);
7948 if (I == LoopBB.end())
7949 I = CmpxMI.getInstr()->getIterator();
7950 } else {
7951 Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
7952
7953 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U32_e64), NewCondReg)
7954 .addReg(CurReg)
7955 .addReg(VScalarOp);
7956
7957 // Combine the comparison results with AND.
7958 if (!CondReg) { // First.
7959 CondReg = NewCondReg;
7960 } else { // If not the first, we create an AND.
7961 Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
7962 BuildMI(LoopBB, I, DL, TII.get(LMC.AndOpc), AndReg)
7963 .addReg(CondReg)
7964 .addReg(NewCondReg)
7965 .setOperandDead(3);
7966 CondReg = AndReg;
7967 }
7968 }
7969
7970 // Update ScalarOp operand to use the SGPR ScalarOp.
7971 if (PhySGPRs.empty() || !PhySGPRs[Idx].isValid())
7972 ScalarOp->setReg(CurReg);
7973 else {
7974 // Insert into the same block of use
7975 BuildMI(*ScalarOp->getParent()->getParent(), ScalarOp->getParent(), DL,
7976 TII.get(AMDGPU::COPY), PhySGPRs[Idx])
7977 .addReg(CurReg);
7978 ScalarOp->setReg(PhySGPRs[Idx]);
7979 }
7980 } else {
7981 SmallVector<Register, 8> ReadlanePieces;
7982 RegState VScalarOpUndef = getUndefRegState(ScalarOp->isUndef());
7983 assert(NumSubRegs % 2 == 0 && NumSubRegs <= 32 &&
7984 "Unhandled register size");
7985
7986 for (unsigned Idx = 0; Idx < NumSubRegs; Idx += 2) {
7987 Register CurRegLo =
7988 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7989 Register CurRegHi =
7990 MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
7991
7992 // Read the next variant <- also loop target.
7993 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegLo)
7994 .addReg(VScalarOp, VScalarOpUndef, TRI->getSubRegFromChannel(Idx));
7995
7996 // Read the next variant <- also loop target.
7997 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegHi)
7998 .addReg(VScalarOp, VScalarOpUndef,
7999 TRI->getSubRegFromChannel(Idx + 1));
8000
8001 ReadlanePieces.push_back(CurRegLo);
8002 ReadlanePieces.push_back(CurRegHi);
8003
8004 // Comparison is to be done as 64-bit.
8005 Register CurReg = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
8006 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), CurReg)
8007 .addReg(CurRegLo)
8008 .addImm(AMDGPU::sub0)
8009 .addReg(CurRegHi)
8010 .addImm(AMDGPU::sub1);
8011
8012 unsigned SubReg =
8013 NumSubRegs <= 2 ? 0 : TRI->getSubRegFromChannel(Idx, 2);
8014
8015 if (UseNewExecInstructions) {
8016 auto CmpxMI = BuildMI(LoopBB, LoopBB.end(), DL,
8017 TII.get(AMDGPU::V_CMPX_EQ_U64_nosdst_e32_term))
8018 .addReg(CurReg)
8019 .addReg(VScalarOp, VScalarOpUndef, SubReg);
8020 if (I == LoopBB.end())
8021 I = CmpxMI.getInstr()->getIterator();
8022 } else {
8023 Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
8024 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), NewCondReg)
8025 .addReg(CurReg)
8026 .addReg(VScalarOp, VScalarOpUndef, SubReg);
8027
8028 // Combine the comparison results with AND.
8029 if (!CondReg) { // First.
8030 CondReg = NewCondReg;
8031 } else { // If not the first, we create an AND.
8032 Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
8033 BuildMI(LoopBB, I, DL, TII.get(LMC.AndOpc), AndReg)
8034 .addReg(CondReg)
8035 .addReg(NewCondReg)
8036 .setOperandDead(3);
8037 CondReg = AndReg;
8038 }
8039 }
8040 } // End for loop.
8041
8042 const auto *SScalarOpRC =
8043 TRI->getEquivalentSGPRClass(MRI.getRegClass(VScalarOp));
8044 Register SScalarOp = MRI.createVirtualRegister(SScalarOpRC);
8045
8046 // Build scalar ScalarOp.
8047 auto Merge =
8048 BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SScalarOp);
8049 unsigned Channel = 0;
8050 for (Register Piece : ReadlanePieces) {
8051 Merge.addReg(Piece).addImm(TRI->getSubRegFromChannel(Channel++));
8052 }
8053
8054 // Update ScalarOp operand to use the SGPR ScalarOp.
8055 if (PhySGPRs.empty() || !PhySGPRs[Idx].isValid())
8056 ScalarOp->setReg(SScalarOp);
8057 else {
8058 BuildMI(*ScalarOp->getParent()->getParent(), ScalarOp->getParent(), DL,
8059 TII.get(AMDGPU::COPY), PhySGPRs[Idx])
8060 .addReg(SScalarOp);
8061 ScalarOp->setReg(PhySGPRs[Idx]);
8062 }
8063 }
8064 }
8065
8066 // AndSaveExecOpc modifies EXEC but can't be isTerminator=1: terminators
8067 // that define virtual registers aren't supported.
8068 Register SaveExec;
8069 if (!UseNewExecInstructions) {
8070 SaveExec = MRI.createVirtualRegister(BoolXExecRC);
8071 MRI.setSimpleHint(SaveExec, CondReg);
8072
8073 // Update EXEC to matching lanes, saving original to SaveExec.
8074 BuildMI(LoopBB, I, DL, TII.get(LMC.AndSaveExecOpc), SaveExec)
8075 .addReg(CondReg)
8076 .setOperandDead(3);
8077 }
8078
8079 // The original instruction is here; we insert the terminators after it.
8080 I = BodyBB.end();
8081
8082 if (UseNewExecInstructions) {
8083 // Compute the remaining lanes into a plain virtual register and write EXEC
8084 // from a terminator, so spill code for NewExec is placed before EXEC
8085 // changes. SIOptimizeExecMasking opportunistically folds the pair back
8086 // into S_ANDN2_WREXEC after register allocation.
8087 MRI.setSimpleHint(NewExec, PhiExec);
8088 BuildMI(BodyBB, I, DL, TII.get(LMC.AndN2Opc), NewExec)
8089 .addReg(PhiExec)
8090 .addReg(LMC.ExecReg)
8091 .setOperandDead(3);
8092 BuildMI(BodyBB, I, DL, TII.get(LMC.MovTermOpc), LMC.ExecReg)
8093 .addReg(NewExec);
8094 } else {
8095 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
8096 BuildMI(BodyBB, I, DL, TII.get(LMC.XorTermOpc), LMC.ExecReg)
8097 .addReg(LMC.ExecReg)
8098 .addReg(SaveExec)
8099 .setOperandDead(3);
8100 }
8101
8102 BuildMI(BodyBB, I, DL, TII.get(AMDGPU::SI_WATERFALL_LOOP)).addMBB(&LoopBB);
8103}
8104
8105// Build a waterfall loop around \p MI, replacing the VGPR \p ScalarOp register
8106// with SGPRs by iterating over all unique values across all lanes.
8107// Returns the loop basic block that now contains \p MI.
8108static MachineBasicBlock *
8112 MachineBasicBlock::iterator Begin = nullptr,
8114 ArrayRef<Register> PhySGPRs = {}) {
8115 assert((PhySGPRs.empty() || PhySGPRs.size() == ScalarOps.size()) &&
8116 "Physical SGPRs must be empty or match the number of scalar operands");
8118 MachineFunction &MF = *MBB.getParent();
8120 const SIRegisterInfo *TRI = ST.getRegisterInfo();
8122 if (!Begin.isValid())
8123 Begin = &MI;
8124 if (!End.isValid()) {
8125 End = &MI;
8126 ++End;
8127 }
8128 const DebugLoc &DL = MI.getDebugLoc();
8130 const auto *BoolXExecRC = TRI->getWaveMaskRegClass();
8131
8132 // Save SCC. Waterfall Loop may overwrite SCC.
8133 Register SaveSCCReg;
8134
8135 // FIXME: We should maintain SCC liveness while doing the FixSGPRCopies walk
8136 // rather than unlimited scan everywhere
8137 bool SCCNotDead =
8138 MBB.computeRegisterLiveness(TRI, AMDGPU::SCC, MI,
8139 std::numeric_limits<unsigned>::max()) !=
8141 if (SCCNotDead) {
8142 SaveSCCReg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
8143 BuildMI(MBB, Begin, DL, TII.get(AMDGPU::S_CSELECT_B32), SaveSCCReg)
8144 .addImm(1)
8145 .addImm(0);
8146 }
8147
8148 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
8149
8150 // Save the EXEC mask
8151 BuildMI(MBB, Begin, DL, TII.get(LMC.MovOpc), SaveExec).addReg(LMC.ExecReg);
8152
8153 // To insert the loop we need to split the block. Move everything after this
8154 // point to a new block, and insert a new empty block between the two.
8157 MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
8159 ++MBBI;
8160
8161 MF.insert(MBBI, LoopBB);
8162 MF.insert(MBBI, BodyBB);
8163 MF.insert(MBBI, RemainderBB);
8164
8165 LoopBB->addSuccessor(BodyBB);
8166 BodyBB->addSuccessor(LoopBB);
8167 BodyBB->addSuccessor(RemainderBB);
8168
8169 // Move Begin to MI to the BodyBB, and the remainder of the block to
8170 // RemainderBB.
8171 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
8172 RemainderBB->splice(RemainderBB->begin(), &MBB, End, MBB.end());
8173 BodyBB->splice(BodyBB->begin(), &MBB, Begin, MBB.end());
8174
8175 MBB.addSuccessor(LoopBB);
8176
8177 // Update dominators. We know that MBB immediately dominates LoopBB, that
8178 // LoopBB immediately dominates BodyBB, and BodyBB immediately dominates
8179 // RemainderBB. RemainderBB immediately dominates all of the successors
8180 // transferred to it from MBB that MBB used to properly dominate.
8181 if (MDT) {
8182 MDT->addNewBlock(LoopBB, &MBB);
8183 MDT->addNewBlock(BodyBB, LoopBB);
8184 MDT->addNewBlock(RemainderBB, BodyBB);
8185 for (auto &Succ : RemainderBB->successors()) {
8186 if (MDT->properlyDominates(&MBB, Succ)) {
8187 MDT->changeImmediateDominator(Succ, RemainderBB);
8188 }
8189 }
8190 }
8191
8192 emitLoadScalarOpsFromVGPRLoop(TII, MRI, MBB, *LoopBB, *BodyBB, DL, ScalarOps,
8193 PhySGPRs);
8194
8195 MachineBasicBlock::iterator First = RemainderBB->begin();
8196 // Restore SCC
8197 if (SCCNotDead) {
8198 BuildMI(*RemainderBB, First, DL, TII.get(AMDGPU::S_CMP_LG_U32))
8199 .addReg(SaveSCCReg)
8200 .addImm(0);
8201 }
8202
8203 // Restore the EXEC mask
8204 BuildMI(*RemainderBB, First, DL, TII.get(LMC.MovOpc), LMC.ExecReg)
8205 .addReg(SaveExec);
8206 return BodyBB;
8207}
8208
8209// Extract pointer from Rsrc and return a zero-value Rsrc replacement.
8210static std::tuple<unsigned, unsigned>
8212 MachineBasicBlock &MBB = *MI.getParent();
8213 MachineFunction &MF = *MBB.getParent();
8215
8216 // Extract the ptr from the resource descriptor.
8217 unsigned RsrcPtr =
8218 TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
8219 AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
8220
8221 // Create an empty resource descriptor
8222 Register Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
8223 Register SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
8224 Register SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
8225 Register NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
8226 uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
8227
8228 // Zero64 = 0
8229 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
8230 .addImm(0);
8231
8232 // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
8233 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
8234 .addImm(Lo_32(RsrcDataFormat));
8235
8236 // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
8237 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
8238 .addImm(Hi_32(RsrcDataFormat));
8239
8240 // NewSRsrc = {Zero64, SRsrcFormat}
8241 BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
8242 .addReg(Zero64)
8243 .addImm(AMDGPU::sub0_sub1)
8244 .addReg(SRsrcFormatLo)
8245 .addImm(AMDGPU::sub2)
8246 .addReg(SRsrcFormatHi)
8247 .addImm(AMDGPU::sub3);
8248
8249 return std::tuple(RsrcPtr, NewSRsrc);
8250}
8251
8254 MachineDominatorTree *MDT) const {
8255 MachineFunction &MF = *MI.getMF();
8257 MachineBasicBlock *CreatedBB = nullptr;
8258
8259 // Legalize True16
8260 if (ST.useRealTrue16Insts())
8262
8263 // Legalize VOP2
8264 if (isVOP2(MI) || isVOPC(MI)) {
8266 return CreatedBB;
8267 }
8268
8269 // Legalize VOP3
8270 if (isVOP3(MI)) {
8272 return CreatedBB;
8273 }
8274
8275 // Legalize SMRD
8276 if (isSMRD(MI)) {
8278 return CreatedBB;
8279 }
8280
8281 // Legalize FLAT
8282 if (isFLAT(MI)) {
8284 return CreatedBB;
8285 }
8286
8287 // The GPR_IDX form needs its index in an SGPR. For the movrel form, a
8288 // divergent M0 write is waterfalled where the copy into M0 is lowered.
8289 if (auto *LdStIdx = dyn_cast<AMDGPUMI::VLoadStoreIdxInst>(&MI)) {
8290 if (!LdStIdx->isGPRIdx())
8291 return CreatedBB;
8292 MachineOperand *Idx = &LdStIdx->getIdxOp();
8293 if (!RI.isSGPRReg(MRI, Idx->getReg()))
8294 CreatedBB = generateWaterFallLoop(*this, MI, {Idx}, MDT);
8295 return CreatedBB;
8296 }
8297
8298 // REG_SEQUENCE doesn't really require operand legalization, but if one has a
8299 // VGPR dest type and SGPR sources, insert copies so all operands are
8300 // VGPRs. This seems to help operand folding / the register coalescer.
8301 if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
8302 MachineBasicBlock *MBB = MI.getParent();
8303 const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
8304 if (RI.hasVGPRs(DstRC)) {
8305 // Update all the operands so they are VGPR register classes. These may
8306 // not be the same register class because REG_SEQUENCE supports mixing
8307 // subregister index types e.g. sub0_sub1 + sub2 + sub3
8308 for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
8309 MachineOperand &Op = MI.getOperand(I);
8310 if (!Op.isReg() || !Op.getReg().isVirtual())
8311 continue;
8312
8313 const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
8314 const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
8315 if (VRC == OpRC)
8316 continue;
8317
8318 legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
8319 }
8320 }
8321
8322 return CreatedBB;
8323 }
8324
8325 // Legalize INSERT_SUBREG
8326 // src0 must have the same register class as dst
8327 if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
8328 Register Dst = MI.getOperand(0).getReg();
8329 Register Src0 = MI.getOperand(1).getReg();
8330 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
8331 const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
8332 if (DstRC != Src0RC) {
8333 MachineBasicBlock *MBB = MI.getParent();
8334 MachineOperand &Op = MI.getOperand(1);
8335 legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
8336 }
8337 return CreatedBB;
8338 }
8339
8340 // Legalize SI_INIT_M0
8341 if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
8342 MachineOperand &Src = MI.getOperand(0);
8343 if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
8344 Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
8345 return CreatedBB;
8346 }
8347
8348 // Legalize S_BITREPLICATE, S_QUADMASK and S_WQM
8349 if (MI.getOpcode() == AMDGPU::S_BITREPLICATE_B64_B32 ||
8350 MI.getOpcode() == AMDGPU::S_QUADMASK_B32 ||
8351 MI.getOpcode() == AMDGPU::S_QUADMASK_B64 ||
8352 MI.getOpcode() == AMDGPU::S_WQM_B32 ||
8353 MI.getOpcode() == AMDGPU::S_WQM_B64 ||
8354 MI.getOpcode() == AMDGPU::S_INVERSE_BALLOT_U32 ||
8355 MI.getOpcode() == AMDGPU::S_INVERSE_BALLOT_U64) {
8356 MachineOperand &Src = MI.getOperand(1);
8357 if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
8358 Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
8359 return CreatedBB;
8360 }
8361
8362 // Legalize MIMG/VIMAGE/VSAMPLE and MUBUF/MTBUF for shaders.
8363 //
8364 // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
8365 // scratch memory access. In both cases, the legalization never involves
8366 // conversion to the addr64 form.
8368 (isMUBUF(MI) || isMTBUF(MI)))) {
8369 AMDGPU::OpName RSrcOpName = (isVIMAGE(MI) || isVSAMPLE(MI))
8370 ? AMDGPU::OpName::rsrc
8371 : AMDGPU::OpName::srsrc;
8372 MachineOperand *SRsrc = getNamedOperand(MI, RSrcOpName);
8373 if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg())))
8374 CreatedBB = generateWaterFallLoop(*this, MI, {SRsrc}, MDT);
8375
8376 AMDGPU::OpName SampOpName =
8377 isMIMG(MI) ? AMDGPU::OpName::ssamp : AMDGPU::OpName::samp;
8378 MachineOperand *SSamp = getNamedOperand(MI, SampOpName);
8379 if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg())))
8380 CreatedBB = generateWaterFallLoop(*this, MI, {SSamp}, MDT);
8381
8382 return CreatedBB;
8383 }
8384
8385 // Legalize SI_CALL
8386 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
8387 MachineOperand *Dest = &MI.getOperand(0);
8388 if (!RI.isSGPRClass(MRI.getRegClass(Dest->getReg()))) {
8389 createWaterFallForSiCall(&MI, MDT, {Dest});
8390 }
8391 }
8392
8393 // Legalize s_sleep_var.
8394 if (MI.getOpcode() == AMDGPU::S_SLEEP_VAR) {
8395 const DebugLoc &DL = MI.getDebugLoc();
8396 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
8397 int Src0Idx =
8398 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
8399 MachineOperand &Src0 = MI.getOperand(Src0Idx);
8400 BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
8401 .add(Src0);
8402 Src0.ChangeToRegister(Reg, false);
8403 return nullptr;
8404 }
8405
8406 // Legalize TENSOR_LOAD_TO_LDS_d2/_d4, TENSOR_STORE_FROM_LDS_d2/_d4. All their
8407 // operands are scalar.
8408 if (MI.getOpcode() == AMDGPU::TENSOR_LOAD_TO_LDS_d2 ||
8409 MI.getOpcode() == AMDGPU::TENSOR_LOAD_TO_LDS_d4 ||
8410 MI.getOpcode() == AMDGPU::TENSOR_STORE_FROM_LDS_d2 ||
8411 MI.getOpcode() == AMDGPU::TENSOR_STORE_FROM_LDS_d4) {
8412 for (MachineOperand &Src : MI.explicit_operands()) {
8413 if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
8414 Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
8415 }
8416 return CreatedBB;
8417 }
8418
8419 // Legalize MUBUF instructions.
8420 bool isSoffsetLegal = true;
8421 int SoffsetIdx =
8422 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::soffset);
8423 if (SoffsetIdx != -1) {
8424 MachineOperand *Soffset = &MI.getOperand(SoffsetIdx);
8425 if (Soffset->isReg() && Soffset->getReg().isVirtual() &&
8426 !RI.isSGPRClass(MRI.getRegClass(Soffset->getReg()))) {
8427 isSoffsetLegal = false;
8428 }
8429 }
8430
8431 bool isRsrcLegal = true;
8432 int RsrcIdx =
8433 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
8434 if (RsrcIdx != -1) {
8435 MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
8436 if (Rsrc->isReg() && !RI.isSGPRReg(MRI, Rsrc->getReg()))
8437 isRsrcLegal = false;
8438 }
8439
8440 // The operands are legal.
8441 if (isRsrcLegal && isSoffsetLegal)
8442 return CreatedBB;
8443
8444 if (!isRsrcLegal) {
8445 // Legalize a VGPR Rsrc
8446 //
8447 // If the instruction is _ADDR64, we can avoid a waterfall by extracting
8448 // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
8449 // a zero-value SRsrc.
8450 //
8451 // If the instruction is _OFFSET (both idxen and offen disabled), and we
8452 // support ADDR64 instructions, we can convert to ADDR64 and do the same as
8453 // above.
8454 //
8455 // Otherwise we are on non-ADDR64 hardware, and/or we have
8456 // idxen/offen/bothen and we fall back to a waterfall loop.
8457
8458 MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
8459 MachineBasicBlock &MBB = *MI.getParent();
8460
8461 MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
8462 if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
8463 // This is already an ADDR64 instruction so we need to add the pointer
8464 // extracted from the resource descriptor to the current value of VAddr.
8465 Register NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8466 Register NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8467 Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
8468
8469 const auto *BoolXExecRC = RI.getWaveMaskRegClass();
8470 Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
8471 Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
8472
8473 unsigned RsrcPtr, NewSRsrc;
8474 std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
8475
8476 // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
8477 const DebugLoc &DL = MI.getDebugLoc();
8478 BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_CO_U32_e64), NewVAddrLo)
8479 .addDef(CondReg0)
8480 .addReg(RsrcPtr, {}, AMDGPU::sub0)
8481 .addReg(VAddr->getReg(), {}, AMDGPU::sub0)
8482 .addImm(0);
8483
8484 // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
8485 BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e64), NewVAddrHi)
8486 .addDef(CondReg1, RegState::Dead)
8487 .addReg(RsrcPtr, {}, AMDGPU::sub1)
8488 .addReg(VAddr->getReg(), {}, AMDGPU::sub1)
8489 .addReg(CondReg0)
8490 .addImm(0);
8491
8492 // NewVaddr = {NewVaddrHi, NewVaddrLo}
8493 BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
8494 .addReg(NewVAddrLo)
8495 .addImm(AMDGPU::sub0)
8496 .addReg(NewVAddrHi)
8497 .addImm(AMDGPU::sub1);
8498
8499 VAddr->setReg(NewVAddr);
8500 Rsrc->setReg(NewSRsrc);
8501 } else if (!VAddr && ST.hasAddr64()) {
8502 // This instructions is the _OFFSET variant, so we need to convert it to
8503 // ADDR64.
8504 assert(ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
8505 "FIXME: Need to emit flat atomics here");
8506
8507 unsigned RsrcPtr, NewSRsrc;
8508 std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
8509
8510 Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
8511 MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
8512 MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
8513 MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
8514 unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
8515
8516 // Atomics with return have an additional tied operand and are
8517 // missing some of the special bits.
8518 MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
8519 MachineInstr *Addr64;
8520
8521 if (!VDataIn) {
8522 // Regular buffer load / store.
8524 BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
8525 .add(*VData)
8526 .addReg(NewVAddr)
8527 .addReg(NewSRsrc)
8528 .add(*SOffset)
8529 .add(*Offset);
8530
8531 if (const MachineOperand *CPol =
8532 getNamedOperand(MI, AMDGPU::OpName::cpol)) {
8533 MIB.addImm(CPol->getImm());
8534 }
8535
8536 if (const MachineOperand *TFE =
8537 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
8538 MIB.addImm(TFE->getImm());
8539 }
8540
8541 MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::swz));
8542
8543 MIB.cloneMemRefs(MI);
8544 Addr64 = MIB;
8545 } else {
8546 // Atomics with return.
8547 Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
8548 .add(*VData)
8549 .add(*VDataIn)
8550 .addReg(NewVAddr)
8551 .addReg(NewSRsrc)
8552 .add(*SOffset)
8553 .add(*Offset)
8554 .addImm(getNamedImmOperand(MI, AMDGPU::OpName::cpol))
8555 .cloneMemRefs(MI);
8556 }
8557
8558 MI.removeFromParent();
8559
8560 // NewVaddr = {NewVaddrHi, NewVaddrLo}
8561 BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
8562 NewVAddr)
8563 .addReg(RsrcPtr, {}, AMDGPU::sub0)
8564 .addImm(AMDGPU::sub0)
8565 .addReg(RsrcPtr, {}, AMDGPU::sub1)
8566 .addImm(AMDGPU::sub1);
8567 } else {
8568 // Legalize a VGPR Rsrc and soffset together.
8569 if (!isSoffsetLegal) {
8570 MachineOperand *Soffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
8571 CreatedBB = generateWaterFallLoop(*this, MI, {Rsrc, Soffset}, MDT);
8572 return CreatedBB;
8573 }
8574 CreatedBB = generateWaterFallLoop(*this, MI, {Rsrc}, MDT);
8575 return CreatedBB;
8576 }
8577 }
8578
8579 // Legalize a VGPR soffset.
8580 if (!isSoffsetLegal) {
8581 MachineOperand *Soffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
8582 CreatedBB = generateWaterFallLoop(*this, MI, {Soffset}, MDT);
8583 return CreatedBB;
8584 }
8585 return CreatedBB;
8586}
8587
8589 if (InSet.insert(MI).second)
8590 InstrList.push_back(MI);
8591 // Add MBUF instructiosn to deferred list.
8592 int RsrcIdx =
8593 AMDGPU::getNamedOperandIdx(MI->getOpcode(), AMDGPU::OpName::srsrc);
8594 if (RsrcIdx != -1) {
8595 DeferredList.insert(MI);
8596 }
8597}
8598
8600 return DeferredList.contains(MI);
8601}
8602
8603// Legalize size mismatches between 16bit and 32bit registers in v2s copy
8604// lowering (change sgpr to vgpr).
8605// This is mainly caused by 16bit SALU and 16bit VALU using reg with different
8606// size. Need to legalize the size of the operands during the vgpr lowering
8607// chain. This can be removed after we have sgpr16 in place
8609 MachineRegisterInfo &MRI) const {
8610 if (!ST.useRealTrue16Insts())
8611 return;
8612
8613 unsigned Opcode = MI.getOpcode();
8614 MachineBasicBlock *MBB = MI.getParent();
8615 // Legalize operands and check for size mismatch
8616 if (OpIdx >= MI.getNumExplicitOperands() ||
8617 OpIdx >= get(Opcode).getNumOperands() ||
8618 get(Opcode).operands()[OpIdx].RegClass == -1)
8619 return;
8620
8621 MachineOperand &Op = MI.getOperand(OpIdx);
8622 if (!Op.isReg() || !Op.getReg().isVirtual() || Op.isDef())
8623 return;
8624
8625 const TargetRegisterClass *CurrRC = MRI.getRegClass(Op.getReg());
8626 if (!RI.isVGPRClass(CurrRC))
8627 return;
8628
8629 int16_t RCID = getOpRegClassID(get(Opcode).operands()[OpIdx]);
8630 const TargetRegisterClass *ExpectedRC = RI.getRegClass(RCID);
8631 if (RI.getMatchingSuperRegClass(CurrRC, ExpectedRC, AMDGPU::lo16)) {
8632 // Default to the lo16 only if the subregister is not specified.
8633 if (Op.getSubReg() == AMDGPU::NoSubRegister)
8634 Op.setSubReg(AMDGPU::lo16);
8635 return;
8636 }
8637
8638 const TargetRegisterClass *CurrSRC =
8639 RI.getSubRegisterClass(CurrRC, Op.getSubReg());
8640 if (RI.getMatchingSuperRegClass(ExpectedRC, CurrSRC, AMDGPU::lo16)) {
8641 Op.setReg(buildVGPR32FromLo16(*MBB, MI, MI.getDebugLoc(), Op.getReg(),
8642 Op.getSubReg()));
8643 Op.setSubReg(AMDGPU::NoSubRegister);
8644 }
8645}
8647 MachineRegisterInfo &MRI) const {
8648 for (unsigned OpIdx = 0; OpIdx < MI.getNumExplicitOperands(); OpIdx++)
8650}
8651
8654 const DebugLoc &DL, Register Src,
8655 unsigned SrcSubReg) const {
8656 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8657 Register Dst = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
8658 Register Undef = MRI.createVirtualRegister(&AMDGPU::VGPR_16RegClass);
8659 BuildMI(MBB, I, DL, get(AMDGPU::IMPLICIT_DEF), Undef);
8660 BuildMI(MBB, I, DL, get(AMDGPU::REG_SEQUENCE), Dst)
8661 .addReg(Src, {}, SrcSubReg)
8662 .addImm(AMDGPU::lo16)
8663 .addReg(Undef)
8664 .addImm(AMDGPU::hi16);
8665 return Dst;
8666}
8667
8671 ArrayRef<Register> PhySGPRs) const {
8672 assert(MI->getOpcode() == AMDGPU::SI_CALL_ISEL &&
8673 "This only handle waterfall for SI_CALL_ISEL");
8674 // Move everything between ADJCALLSTACKUP and ADJCALLSTACKDOWN and
8675 // following copies, we also need to move copies from and to physical
8676 // registers into the loop block.
8677 // Also move the copies to physical registers into the loop block
8678 MachineBasicBlock &MBB = *MI->getParent();
8680 while (Start->getOpcode() != AMDGPU::ADJCALLSTACKUP)
8681 --Start;
8683 while (End->getOpcode() != AMDGPU::ADJCALLSTACKDOWN)
8684 ++End;
8685
8686 // Also include following copies of the return value
8687 ++End;
8688 while (End != MBB.end() && End->isCopy() &&
8689 MI->definesRegister(End->getOperand(1).getReg(), &RI))
8690 ++End;
8691
8692 generateWaterFallLoop(*this, *MI, ScalarOps, MDT, Start, End, PhySGPRs);
8693}
8694
8696 MachineDominatorTree *MDT) const {
8698 DenseMap<MachineInstr *, bool> V2SPhyCopiesToErase;
8699 while (!Worklist.empty()) {
8700 MachineInstr &Inst = *Worklist.top();
8701 Worklist.erase_top();
8702 // Skip MachineInstr in the deferred list.
8703 if (Worklist.isDeferred(&Inst))
8704 continue;
8705 moveToVALUImpl(Worklist, MDT, Inst, WaterFalls, V2SPhyCopiesToErase);
8706 }
8707
8708 // Deferred list of instructions will be processed once
8709 // all the MachineInstr in the worklist are done.
8710 for (MachineInstr *Inst : Worklist.getDeferredList()) {
8711 moveToVALUImpl(Worklist, MDT, *Inst, WaterFalls, V2SPhyCopiesToErase);
8712 assert(Worklist.empty() &&
8713 "Deferred MachineInstr are not supposed to re-populate worklist");
8714 }
8715
8716 for (auto &Entry : WaterFalls) {
8717 if (Entry.first->getOpcode() == AMDGPU::SI_CALL_ISEL)
8718 createWaterFallForSiCall(Entry.first, MDT, Entry.second.MOs,
8719 Entry.second.SGPRs);
8720 }
8721
8722 for (std::pair<MachineInstr *, bool> Entry : V2SPhyCopiesToErase)
8723 if (Entry.second)
8724 Entry.first->eraseFromParent();
8725}
8727 MachineRegisterInfo &MRI, Register DstReg, MachineInstr &Inst) const {
8728 // If it's a copy of a VGPR to a physical SGPR, insert a V_READFIRSTLANE and
8729 // hope for the best.
8730 const TargetRegisterClass *DstRC = RI.getRegClassForReg(MRI, DstReg);
8731 ArrayRef<int16_t> SubRegIndices = RI.getRegSplitParts(DstRC, 4);
8732 if (SubRegIndices.size() <= 1) {
8733 Register NewDst = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
8734 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(),
8735 get(AMDGPU::V_READFIRSTLANE_B32), NewDst)
8736 .add(Inst.getOperand(1));
8737 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(), get(AMDGPU::COPY),
8738 DstReg)
8739 .addReg(NewDst);
8740 } else {
8742 for (int16_t Indice : SubRegIndices) {
8743 Register NewDst = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
8744 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(),
8745 get(AMDGPU::V_READFIRSTLANE_B32), NewDst)
8746 .addReg(Inst.getOperand(1).getReg(), {}, Indice);
8747
8748 DstRegs.push_back(NewDst);
8749 }
8751 BuildMI(*Inst.getParent(), &Inst, Inst.getDebugLoc(),
8752 get(AMDGPU::REG_SEQUENCE), DstReg);
8753 for (unsigned i = 0; i < SubRegIndices.size(); ++i) {
8754 MIB.addReg(DstRegs[i]);
8755 MIB.addImm(RI.getSubRegFromChannel(i));
8756 }
8757 }
8758}
8759
8760// M0 holds one value, but the VGPR copied into it holds one per lane. A movrel
8761// access adds M0 to its base register, so each one that reads the copy is
8762// wrapped in a waterfall loop that puts the value of each group of lanes in M0
8763// in turn. Every other reader gets the first lane, as all of them do when no
8764// access reads the copy.
8768 MachineDominatorTree *MDT) {
8769 auto IsMovrelAccess = [](const MachineInstr *MI) {
8770 const auto *LdStIdx = dyn_cast<AMDGPUMI::VLoadStoreIdxInst>(MI);
8771 return LdStIdx && !LdStIdx->isGPRIdx();
8772 };
8773 if (none_of(Readers, IsMovrelAccess)) {
8774 TII.createReadFirstLaneFromCopyToPhysReg(MRI, AMDGPU::M0, Copy);
8775 return;
8776 }
8777
8778 assert(!Copy.getOperand(1).getSubReg() &&
8779 "selection copies a whole register into M0");
8780 Register Idx = Copy.getOperand(1).getReg();
8781 Register FirstLane;
8782 for (MachineInstr *Reader : Readers) {
8783 if (IsMovrelAccess(Reader)) {
8784 MachineOperand *M0Use =
8785 Reader->findRegisterUseOperand(AMDGPU::M0, &TII.getRegisterInfo());
8786 M0Use->setReg(Idx);
8787 generateWaterFallLoop(TII, *Reader, M0Use, MDT, nullptr, nullptr,
8788 {AMDGPU::M0});
8789 continue;
8790 }
8791
8792 if (!FirstLane) {
8793 FirstLane = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
8794 BuildMI(*Copy.getParent(), Copy, Copy.getDebugLoc(),
8795 TII.get(AMDGPU::V_READFIRSTLANE_B32), FirstLane)
8796 .addReg(Idx);
8797 }
8798 BuildMI(*Reader->getParent(), Reader, Reader->getDebugLoc(),
8799 TII.get(AMDGPU::COPY), AMDGPU::M0)
8800 .addReg(FirstLane);
8801 }
8802}
8803
8805 SIInstrWorklist &Worklist, Register DstReg, MachineInstr &Inst,
8808 DenseMap<MachineInstr *, bool> &V2SPhyCopiesToErase) const {
8809 // In SSA a copy into a physical register and its readers share a block, so
8810 // only the rest of this block is searched.
8812 for (MachineInstr &MI :
8814 Inst.getParent()->end())) {
8815 if (MI.readsRegister(DstReg, &RI))
8816 Readers.push_back(&MI);
8817
8818 if (MI.modifiesRegister(DstReg, &RI))
8819 break;
8820 }
8821
8822 if (DstReg == AMDGPU::M0) {
8823 lowerVGPRCopyToM0(*this, Inst, Readers, MRI, MDT);
8824 V2SPhyCopiesToErase.try_emplace(&Inst, true);
8825 return;
8826 }
8827
8828 Register SrcReg = Inst.getOperand(1).getReg();
8829 for (MachineInstr *UseMI : Readers) {
8830 // For SI_CALL_ISEL users, replace the phys SGPR with the VGPR source
8831 // and record the operand for later waterfall loop generation.
8832 if (UseMI->getOpcode() == AMDGPU::SI_CALL_ISEL) {
8833 for (unsigned i = 0; i < UseMI->getNumOperands(); ++i) {
8834 if (UseMI->getOperand(i).isReg() &&
8835 UseMI->getOperand(i).getReg() == DstReg) {
8836 MachineOperand *MO = &UseMI->getOperand(i);
8837 MO->setReg(SrcReg);
8838 V2PhysSCopyInfo &V2SCopyInfo = WaterFalls[UseMI];
8839 V2SCopyInfo.MOs.push_back(MO);
8840 V2SCopyInfo.SGPRs.push_back(DstReg);
8841 V2SPhyCopiesToErase.try_emplace(&Inst, true);
8842 }
8843 }
8844 } else if (UseMI->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG &&
8845 UseMI->getOperand(0).isReg() &&
8846 UseMI->getOperand(0).getReg() == DstReg) {
8848 V2SPhyCopiesToErase.try_emplace(&Inst, true);
8849 } else {
8850 // COPY cannot be erased if other type of inst uses it.
8851 V2SPhyCopiesToErase[&Inst] = false;
8852 }
8853 }
8854}
8855
8857 SIInstrWorklist &Worklist, MachineDominatorTree *MDT, MachineInstr &Inst,
8859 DenseMap<MachineInstr *, bool> &V2SPhyCopiesToErase) const {
8860
8862 if (!MBB)
8863 return;
8864 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8865 unsigned Opcode = Inst.getOpcode();
8866 unsigned NewOpcode = getVALUOp(Inst);
8867 const DebugLoc &DL = Inst.getDebugLoc();
8868
8869 // Handle some special cases
8870 switch (Opcode) {
8871 default:
8872 break;
8873 case AMDGPU::S_ADD_I32:
8874 case AMDGPU::S_SUB_I32: {
8875 // FIXME: The u32 versions currently selected use the carry.
8876 bool Changed;
8877 MachineBasicBlock *CreatedBBTmp = nullptr;
8878 std::tie(Changed, CreatedBBTmp) = moveScalarAddSub(Worklist, Inst, MDT);
8879 if (Changed)
8880 return;
8881
8882 // Default handling
8883 break;
8884 }
8885
8886 case AMDGPU::S_MUL_U64:
8887 if (ST.useVMulU64Inst()) {
8888 NewOpcode = AMDGPU::V_MUL_U64_e64;
8889 break;
8890 }
8891 // Split s_mul_u64 in 32-bit vector multiplications.
8892 splitScalarSMulU64(Worklist, Inst, MDT);
8893 Inst.eraseFromParent();
8894 return;
8895
8896 case AMDGPU::S_MUL_U64_U32_PSEUDO:
8897 case AMDGPU::S_MUL_I64_I32_PSEUDO:
8898 // This is a special case of s_mul_u64 where all the operands are either
8899 // zero extended or sign extended.
8900 splitScalarSMulPseudo(Worklist, Inst, MDT);
8901 Inst.eraseFromParent();
8902 return;
8903
8904 case AMDGPU::S_AND_B64:
8905 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
8906 Inst.eraseFromParent();
8907 return;
8908
8909 case AMDGPU::S_OR_B64:
8910 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
8911 Inst.eraseFromParent();
8912 return;
8913
8914 case AMDGPU::S_XOR_B64:
8915 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
8916 Inst.eraseFromParent();
8917 return;
8918
8919 case AMDGPU::S_NAND_B64:
8920 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
8921 Inst.eraseFromParent();
8922 return;
8923
8924 case AMDGPU::S_NOR_B64:
8925 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
8926 Inst.eraseFromParent();
8927 return;
8928
8929 case AMDGPU::S_XNOR_B64:
8930 if (ST.hasDLInsts())
8931 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
8932 else
8933 splitScalar64BitXnor(Worklist, Inst, MDT);
8934 Inst.eraseFromParent();
8935 return;
8936
8937 case AMDGPU::S_ANDN2_B64:
8938 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
8939 Inst.eraseFromParent();
8940 return;
8941
8942 case AMDGPU::S_ORN2_B64:
8943 splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
8944 Inst.eraseFromParent();
8945 return;
8946
8947 case AMDGPU::S_BREV_B64:
8948 splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_BREV_B32, true);
8949 Inst.eraseFromParent();
8950 return;
8951
8952 case AMDGPU::S_NOT_B64:
8953 splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
8954 Inst.eraseFromParent();
8955 return;
8956
8957 case AMDGPU::S_BCNT1_I32_B64:
8958 splitScalar64BitBCNT(Worklist, Inst);
8959 Inst.eraseFromParent();
8960 return;
8961
8962 case AMDGPU::S_BFE_I64:
8963 splitScalar64BitBFE(Worklist, Inst);
8964 Inst.eraseFromParent();
8965 return;
8966
8967 case AMDGPU::S_FLBIT_I32_B64:
8968 splitScalar64BitCountOp(Worklist, Inst, AMDGPU::V_FFBH_U32_e32);
8969 Inst.eraseFromParent();
8970 return;
8971 case AMDGPU::S_FF1_I32_B64:
8972 splitScalar64BitCountOp(Worklist, Inst, AMDGPU::V_FFBL_B32_e32);
8973 Inst.eraseFromParent();
8974 return;
8975
8976 case AMDGPU::S_LSHL_B32:
8977 if (ST.hasOnlyRevVALUShifts()) {
8978 NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
8979 swapOperands(Inst);
8980 }
8981 break;
8982 case AMDGPU::S_ASHR_I32:
8983 if (ST.hasOnlyRevVALUShifts()) {
8984 NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
8985 swapOperands(Inst);
8986 }
8987 break;
8988 case AMDGPU::S_LSHR_B32:
8989 if (ST.hasOnlyRevVALUShifts()) {
8990 NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
8991 swapOperands(Inst);
8992 }
8993 break;
8994 case AMDGPU::S_LSHL_B64:
8995 if (ST.hasOnlyRevVALUShifts()) {
8996 NewOpcode = ST.getGeneration() >= AMDGPUSubtarget::GFX12
8997 ? AMDGPU::V_LSHLREV_B64_pseudo_e64
8998 : AMDGPU::V_LSHLREV_B64_e64;
8999 swapOperands(Inst);
9000 }
9001 break;
9002 case AMDGPU::S_ASHR_I64:
9003 if (ST.hasOnlyRevVALUShifts()) {
9004 NewOpcode = AMDGPU::V_ASHRREV_I64_e64;
9005 swapOperands(Inst);
9006 }
9007 break;
9008 case AMDGPU::S_LSHR_B64:
9009 if (ST.hasOnlyRevVALUShifts()) {
9010 NewOpcode = AMDGPU::V_LSHRREV_B64_e64;
9011 swapOperands(Inst);
9012 }
9013 break;
9014
9015 case AMDGPU::S_ABS_I32:
9016 lowerScalarAbs(Worklist, Inst);
9017 Inst.eraseFromParent();
9018 return;
9019
9020 case AMDGPU::S_ABSDIFF_I32:
9021 lowerScalarAbsDiff(Worklist, Inst);
9022 Inst.eraseFromParent();
9023 return;
9024
9025 case AMDGPU::S_CBRANCH_SCC0:
9026 case AMDGPU::S_CBRANCH_SCC1: {
9027 // Clear unused bits of vcc
9028 Register CondReg = Inst.getOperand(1).getReg();
9029 bool IsSCC = CondReg == AMDGPU::SCC;
9031 BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(LMC.AndOpc), LMC.VccReg)
9032 .addReg(LMC.ExecReg)
9033 .addReg(IsSCC ? LMC.VccReg : CondReg)
9034 .setOperandDead(3); // implicit-def $scc
9035 Inst.removeOperand(1);
9036 } break;
9037
9038 case AMDGPU::S_BFE_U64:
9039 case AMDGPU::S_BFM_B64:
9040 llvm_unreachable("Moving this op to VALU not implemented");
9041
9042 case AMDGPU::S_PACK_LL_B32_B16:
9043 case AMDGPU::S_PACK_LH_B32_B16:
9044 case AMDGPU::S_PACK_HL_B32_B16:
9045 case AMDGPU::S_PACK_HH_B32_B16:
9046 movePackToVALU(Worklist, MRI, Inst);
9047 Inst.eraseFromParent();
9048 return;
9049
9050 case AMDGPU::S_XNOR_B32:
9051 lowerScalarXnor(Worklist, Inst);
9052 Inst.eraseFromParent();
9053 return;
9054
9055 case AMDGPU::S_NAND_B32:
9056 splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
9057 Inst.eraseFromParent();
9058 return;
9059
9060 case AMDGPU::S_NOR_B32:
9061 splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
9062 Inst.eraseFromParent();
9063 return;
9064
9065 case AMDGPU::S_ANDN2_B32:
9066 splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
9067 Inst.eraseFromParent();
9068 return;
9069
9070 case AMDGPU::S_ORN2_B32:
9071 splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
9072 Inst.eraseFromParent();
9073 return;
9074
9075 // TODO: remove as soon as everything is ready
9076 // to replace VGPR to SGPR copy with V_READFIRSTLANEs.
9077 // S_ADD/SUB_CO_PSEUDO as well as S_UADDO/USUBO_PSEUDO
9078 // can only be selected from the uniform SDNode.
9079 case AMDGPU::S_ADD_CO_PSEUDO:
9080 case AMDGPU::S_SUB_CO_PSEUDO: {
9081 unsigned Opc = (Inst.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
9082 ? AMDGPU::V_ADDC_U32_e64
9083 : AMDGPU::V_SUBB_U32_e64;
9084 const auto *CarryRC = RI.getWaveMaskRegClass();
9085
9086 Register CarryInReg = Inst.getOperand(4).getReg();
9087 if (!MRI.constrainRegClass(CarryInReg, CarryRC)) {
9088 Register NewCarryReg = MRI.createVirtualRegister(CarryRC);
9089 BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::COPY), NewCarryReg)
9090 .addReg(CarryInReg);
9091 }
9092
9093 Register CarryOutReg = Inst.getOperand(1).getReg();
9094
9095 Register DestReg = MRI.createVirtualRegister(RI.getEquivalentVGPRClass(
9096 MRI.getRegClass(Inst.getOperand(0).getReg())));
9097 MachineInstr *CarryOp =
9098 BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(Opc), DestReg)
9099 .addReg(CarryOutReg, RegState::Define)
9100 .add(Inst.getOperand(2))
9101 .add(Inst.getOperand(3))
9102 .addReg(CarryInReg)
9103 .addImm(0);
9104 legalizeOperands(*CarryOp);
9105 MRI.replaceRegWith(Inst.getOperand(0).getReg(), DestReg);
9106 addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
9107 Inst.eraseFromParent();
9108 }
9109 return;
9110 case AMDGPU::S_UADDO_PSEUDO:
9111 case AMDGPU::S_USUBO_PSEUDO: {
9112 MachineOperand &Dest0 = Inst.getOperand(0);
9113 MachineOperand &Dest1 = Inst.getOperand(1);
9114 MachineOperand &Src0 = Inst.getOperand(2);
9115 MachineOperand &Src1 = Inst.getOperand(3);
9116
9117 unsigned Opc = (Inst.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
9118 ? AMDGPU::V_ADD_CO_U32_e64
9119 : AMDGPU::V_SUB_CO_U32_e64;
9120 const TargetRegisterClass *NewRC =
9121 RI.getEquivalentVGPRClass(MRI.getRegClass(Dest0.getReg()));
9122 Register DestReg = MRI.createVirtualRegister(NewRC);
9123 MachineInstr *NewInstr = BuildMI(*MBB, &Inst, DL, get(Opc), DestReg)
9124 .addReg(Dest1.getReg(), RegState::Define)
9125 .add(Src0)
9126 .add(Src1)
9127 .addImm(0); // clamp bit
9128
9129 legalizeOperands(*NewInstr, MDT);
9130 MRI.replaceRegWith(Dest0.getReg(), DestReg);
9131 addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
9132 Inst.eraseFromParent();
9133 }
9134 return;
9135 case AMDGPU::S_LSHL1_ADD_U32:
9136 case AMDGPU::S_LSHL2_ADD_U32:
9137 case AMDGPU::S_LSHL3_ADD_U32:
9138 case AMDGPU::S_LSHL4_ADD_U32: {
9139 MachineOperand &Dest = Inst.getOperand(0);
9140 MachineOperand &Src0 = Inst.getOperand(1);
9141 MachineOperand &Src1 = Inst.getOperand(2);
9142 unsigned ShiftAmt = (Opcode == AMDGPU::S_LSHL1_ADD_U32 ? 1
9143 : Opcode == AMDGPU::S_LSHL2_ADD_U32 ? 2
9144 : Opcode == AMDGPU::S_LSHL3_ADD_U32 ? 3
9145 : 4);
9146
9147 const TargetRegisterClass *NewRC =
9148 RI.getEquivalentVGPRClass(MRI.getRegClass(Dest.getReg()));
9149 Register DestReg = MRI.createVirtualRegister(NewRC);
9150 MachineInstr *NewInstr =
9151 BuildMI(*MBB, &Inst, DL, get(AMDGPU::V_LSHL_ADD_U32_e64), DestReg)
9152 .add(Src0)
9153 .addImm(ShiftAmt)
9154 .add(Src1);
9155
9156 legalizeOperands(*NewInstr, MDT);
9157 MRI.replaceRegWith(Dest.getReg(), DestReg);
9158 addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
9159 Inst.eraseFromParent();
9160 }
9161 return;
9162 case AMDGPU::S_CSELECT_B32:
9163 case AMDGPU::S_CSELECT_B64:
9164 lowerSelect(Worklist, Inst, MDT);
9165 Inst.eraseFromParent();
9166 return;
9167 case AMDGPU::S_CMP_EQ_I32:
9168 case AMDGPU::S_CMP_LG_I32:
9169 case AMDGPU::S_CMP_GT_I32:
9170 case AMDGPU::S_CMP_GE_I32:
9171 case AMDGPU::S_CMP_LT_I32:
9172 case AMDGPU::S_CMP_LE_I32:
9173 case AMDGPU::S_CMP_EQ_U32:
9174 case AMDGPU::S_CMP_LG_U32:
9175 case AMDGPU::S_CMP_GT_U32:
9176 case AMDGPU::S_CMP_GE_U32:
9177 case AMDGPU::S_CMP_LT_U32:
9178 case AMDGPU::S_CMP_LE_U32:
9179 case AMDGPU::S_CMP_EQ_U64:
9180 case AMDGPU::S_CMP_LG_U64:
9181 case AMDGPU::S_CMP_LT_F32:
9182 case AMDGPU::S_CMP_EQ_F32:
9183 case AMDGPU::S_CMP_LE_F32:
9184 case AMDGPU::S_CMP_GT_F32:
9185 case AMDGPU::S_CMP_LG_F32:
9186 case AMDGPU::S_CMP_GE_F32:
9187 case AMDGPU::S_CMP_O_F32:
9188 case AMDGPU::S_CMP_U_F32:
9189 case AMDGPU::S_CMP_NGE_F32:
9190 case AMDGPU::S_CMP_NLG_F32:
9191 case AMDGPU::S_CMP_NGT_F32:
9192 case AMDGPU::S_CMP_NLE_F32:
9193 case AMDGPU::S_CMP_NEQ_F32:
9194 case AMDGPU::S_CMP_NLT_F32: {
9195 Register CondReg = MRI.createVirtualRegister(RI.getWaveMaskRegClass());
9196 auto NewInstr =
9197 BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(NewOpcode), CondReg)
9198 .setMIFlags(Inst.getFlags());
9199 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::src0_modifiers) >=
9200 0) {
9201 NewInstr
9202 .addImm(0) // src0_modifiers
9203 .add(Inst.getOperand(0)) // src0
9204 .addImm(0) // src1_modifiers
9205 .add(Inst.getOperand(1)) // src1
9206 .addImm(0); // clamp
9207 } else {
9208 NewInstr.add(Inst.getOperand(0)).add(Inst.getOperand(1));
9209 }
9210 legalizeOperands(*NewInstr, MDT);
9211 int SCCIdx = Inst.findRegisterDefOperandIdx(AMDGPU::SCC, /*TRI=*/nullptr);
9212 const MachineOperand &SCCOp = Inst.getOperand(SCCIdx);
9213 addSCCDefUsersToVALUWorklist(SCCOp, Inst, Worklist, CondReg);
9214 Inst.eraseFromParent();
9215 return;
9216 }
9217 case AMDGPU::S_CMP_LT_F16:
9218 case AMDGPU::S_CMP_EQ_F16:
9219 case AMDGPU::S_CMP_LE_F16:
9220 case AMDGPU::S_CMP_GT_F16:
9221 case AMDGPU::S_CMP_LG_F16:
9222 case AMDGPU::S_CMP_GE_F16:
9223 case AMDGPU::S_CMP_O_F16:
9224 case AMDGPU::S_CMP_U_F16:
9225 case AMDGPU::S_CMP_NGE_F16:
9226 case AMDGPU::S_CMP_NLG_F16:
9227 case AMDGPU::S_CMP_NGT_F16:
9228 case AMDGPU::S_CMP_NLE_F16:
9229 case AMDGPU::S_CMP_NEQ_F16:
9230 case AMDGPU::S_CMP_NLT_F16: {
9231 Register CondReg = MRI.createVirtualRegister(RI.getWaveMaskRegClass());
9232 auto NewInstr =
9233 BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(NewOpcode), CondReg)
9234 .setMIFlags(Inst.getFlags());
9235 if (AMDGPU::hasNamedOperand(NewOpcode, AMDGPU::OpName::src0_modifiers)) {
9236 NewInstr
9237 .addImm(0) // src0_modifiers
9238 .add(Inst.getOperand(0)) // src0
9239 .addImm(0) // src1_modifiers
9240 .add(Inst.getOperand(1)) // src1
9241 .addImm(0); // clamp
9242 if (AMDGPU::hasNamedOperand(NewOpcode, AMDGPU::OpName::op_sel))
9243 NewInstr.addImm(0); // op_sel0
9244 } else {
9245 NewInstr
9246 .add(Inst.getOperand(0))
9247 .add(Inst.getOperand(1));
9248 }
9249 legalizeOperands(*NewInstr, MDT);
9250 int SCCIdx = Inst.findRegisterDefOperandIdx(AMDGPU::SCC, /*TRI=*/nullptr);
9251 const MachineOperand &SCCOp = Inst.getOperand(SCCIdx);
9252 addSCCDefUsersToVALUWorklist(SCCOp, Inst, Worklist, CondReg);
9253 Inst.eraseFromParent();
9254 return;
9255 }
9256 case AMDGPU::S_CVT_HI_F32_F16: {
9257 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9258 Register NewDst = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9259 if (ST.useRealTrue16Insts()) {
9260 BuildMI(*MBB, Inst, DL, get(AMDGPU::COPY), TmpReg)
9261 .add(Inst.getOperand(1));
9262 BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
9263 .addImm(0) // src0_modifiers
9264 .addReg(TmpReg, {}, AMDGPU::hi16)
9265 .addImm(0) // clamp
9266 .addImm(0) // omod
9267 .addImm(0); // op_sel0
9268 } else {
9269 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
9270 .addImm(16)
9271 .add(Inst.getOperand(1));
9272 BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
9273 .addImm(0) // src0_modifiers
9274 .addReg(TmpReg)
9275 .addImm(0) // clamp
9276 .addImm(0); // omod
9277 }
9278
9279 MRI.replaceRegWith(Inst.getOperand(0).getReg(), NewDst);
9280 addUsersToMoveToVALUWorklist(NewDst, MRI, Worklist);
9281 Inst.eraseFromParent();
9282 return;
9283 }
9284 case AMDGPU::S_MINIMUM_F32:
9285 case AMDGPU::S_MAXIMUM_F32: {
9286 Register NewDst = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9287 MachineInstr *NewInstr = BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
9288 .addImm(0) // src0_modifiers
9289 .add(Inst.getOperand(1))
9290 .addImm(0) // src1_modifiers
9291 .add(Inst.getOperand(2))
9292 .addImm(0) // clamp
9293 .addImm(0); // omod
9294 MRI.replaceRegWith(Inst.getOperand(0).getReg(), NewDst);
9295
9296 legalizeOperands(*NewInstr, MDT);
9297 addUsersToMoveToVALUWorklist(NewDst, MRI, Worklist);
9298 Inst.eraseFromParent();
9299 return;
9300 }
9301 case AMDGPU::S_MINIMUM_F16:
9302 case AMDGPU::S_MAXIMUM_F16: {
9303 Register NewDst = MRI.createVirtualRegister(ST.useRealTrue16Insts()
9304 ? &AMDGPU::VGPR_16RegClass
9305 : &AMDGPU::VGPR_32RegClass);
9306 MachineInstr *NewInstr = BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
9307 .addImm(0) // src0_modifiers
9308 .add(Inst.getOperand(1))
9309 .addImm(0) // src1_modifiers
9310 .add(Inst.getOperand(2))
9311 .addImm(0) // clamp
9312 .addImm(0) // omod
9313 .addImm(0); // opsel0
9314 MRI.replaceRegWith(Inst.getOperand(0).getReg(), NewDst);
9315 legalizeOperands(*NewInstr, MDT);
9316 addUsersToMoveToVALUWorklist(NewDst, MRI, Worklist);
9317 Inst.eraseFromParent();
9318 return;
9319 }
9320 case AMDGPU::V_S_EXP_F16_e64:
9321 case AMDGPU::V_S_LOG_F16_e64:
9322 case AMDGPU::V_S_RCP_F16_e64:
9323 case AMDGPU::V_S_RSQ_F16_e64:
9324 case AMDGPU::V_S_SQRT_F16_e64: {
9325 Register NewDst = MRI.createVirtualRegister(ST.useRealTrue16Insts()
9326 ? &AMDGPU::VGPR_16RegClass
9327 : &AMDGPU::VGPR_32RegClass);
9328 auto NewInstr = BuildMI(*MBB, Inst, DL, get(NewOpcode), NewDst)
9329 .add(Inst.getOperand(1)) // src0_modifiers
9330 .add(Inst.getOperand(2))
9331 .add(Inst.getOperand(3)) // clamp
9332 .add(Inst.getOperand(4)) // omod
9333 .setMIFlags(Inst.getFlags());
9334 if (AMDGPU::hasNamedOperand(NewOpcode, AMDGPU::OpName::op_sel))
9335 NewInstr.addImm(0); // opsel0
9336 MRI.replaceRegWith(Inst.getOperand(0).getReg(), NewDst);
9337 legalizeOperands(*NewInstr, MDT);
9338 addUsersToMoveToVALUWorklist(NewDst, MRI, Worklist);
9339 Inst.eraseFromParent();
9340 return;
9341 }
9342 }
9343
9344 if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
9345 // We cannot move this instruction to the VALU, so we should try to
9346 // legalize its operands instead.
9347 legalizeOperands(Inst, MDT);
9348 return;
9349 }
9350 // Handle converting generic instructions like COPY-to-SGPR into
9351 // COPY-to-VGPR.
9352 if (NewOpcode == Opcode) {
9353 Register DstReg = Inst.getOperand(0).getReg();
9354 const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
9355
9356 if (Inst.isCopy() && DstReg.isPhysical() &&
9357 Inst.getOperand(1).getReg().isVirtual()) {
9358 handleCopyToPhysHelper(Worklist, DstReg, Inst, MRI, MDT, WaterFalls,
9359 V2SPhyCopiesToErase);
9360 return;
9361 }
9362
9363 if (Inst.isCopy() && Inst.getOperand(1).getReg().isVirtual()) {
9364 Register NewDstReg = Inst.getOperand(1).getReg();
9365 const TargetRegisterClass *SrcRC = RI.getRegClassForReg(MRI, NewDstReg);
9366 if (const TargetRegisterClass *CommonRC =
9367 RI.getCommonSubClass(NewDstRC, SrcRC)) {
9368 // Instead of creating a copy where src and dst are the same register
9369 // class, we just replace all uses of dst with src. These kinds of
9370 // copies interfere with the heuristics MachineSink uses to decide
9371 // whether or not to split a critical edge. Since the pass assumes
9372 // that copies will end up as machine instructions and not be
9373 // eliminated.
9374 addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
9375 unsigned SrcSubReg = Inst.getOperand(1).getSubReg();
9376 bool IsUndef = Inst.getOperand(1).isUndef();
9377 for (MachineOperand &UseMO :
9378 make_early_inc_range(MRI.use_operands(DstReg))) {
9379 UseMO.setSubReg(
9380 RI.composeSubRegIndices(SrcSubReg, UseMO.getSubReg()));
9381 UseMO.setReg(NewDstReg);
9382 if (IsUndef)
9383 UseMO.setIsUndef();
9384 }
9385
9386 if (!MRI.constrainRegClass(NewDstReg, CommonRC))
9387 llvm_unreachable("failed to constrain register");
9388
9389 Inst.eraseFromParent();
9390
9391 for (MachineOperand &UseMO :
9392 make_early_inc_range(MRI.use_operands(NewDstReg))) {
9393 MachineInstr &UseMI = *UseMO.getParent();
9394
9395 // Legalize t16 operands since replaceReg is called after
9396 // addUsersToVALU.
9398
9399 unsigned OpIdx = UseMI.getOperandNo(&UseMO);
9400 if (const TargetRegisterClass *OpRC =
9401 getRegClass(UseMI.getDesc(), OpIdx))
9402 MRI.constrainRegClass(NewDstReg, OpRC);
9403 }
9404
9405 return;
9406 }
9407 }
9408
9409 // If this is a v2s copy between 16bit and 32bit reg,
9410 // replace vgpr copy to reg_sequence/extract_subreg
9411 // This can be remove after we have sgpr16 in place
9412 if (ST.useRealTrue16Insts() && Inst.isCopy() &&
9413 Inst.getOperand(1).getReg().isVirtual() &&
9414 RI.isVGPR(MRI, Inst.getOperand(1).getReg())) {
9415 const TargetRegisterClass *SrcRegRC = getOpRegClass(Inst, 1);
9416 if (RI.getMatchingSuperRegClass(NewDstRC, SrcRegRC, AMDGPU::lo16)) {
9417 Register NewDstReg = buildVGPR32FromLo16(
9418 *Inst.getParent(), Inst, Inst.getDebugLoc(),
9419 Inst.getOperand(1).getReg(), AMDGPU::NoSubRegister);
9420 Inst.eraseFromParent();
9421 MRI.replaceRegWith(DstReg, NewDstReg);
9422 addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
9423 return;
9424 } else if (RI.getMatchingSuperRegClass(SrcRegRC, NewDstRC,
9425 AMDGPU::lo16)) {
9426 Inst.getOperand(1).setSubReg(AMDGPU::lo16);
9427 Register NewDstReg = MRI.createVirtualRegister(NewDstRC);
9428 MRI.replaceRegWith(DstReg, NewDstReg);
9429 addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
9430 return;
9431 }
9432 }
9433
9434 Register NewDstReg = MRI.createVirtualRegister(NewDstRC);
9435 MRI.replaceRegWith(DstReg, NewDstReg);
9436 legalizeOperands(Inst, MDT);
9437 addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
9438 return;
9439 }
9440
9441 // Use the new VALU Opcode.
9442 auto NewInstr = BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(NewOpcode))
9443 .setMIFlags(Inst.getFlags());
9444 if (isVOP3(NewOpcode) && !isVOP3(Opcode)) {
9445 // Intersperse VOP3 modifiers among the SALU operands.
9446 NewInstr->addOperand(Inst.getOperand(0));
9447 if (AMDGPU::getNamedOperandIdx(NewOpcode,
9448 AMDGPU::OpName::src0_modifiers) >= 0)
9449 NewInstr.addImm(0);
9450 if (AMDGPU::hasNamedOperand(NewOpcode, AMDGPU::OpName::src0)) {
9451 const MachineOperand &Src = Inst.getOperand(1);
9452 NewInstr->addOperand(Src);
9453 }
9454
9455 if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
9456 // We are converting these to a BFE, so we need to add the missing
9457 // operands for the size and offset.
9458 unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
9459 NewInstr.addImm(0);
9460 NewInstr.addImm(Size);
9461 } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
9462 // The VALU version adds the second operand to the result, so insert an
9463 // extra 0 operand.
9464 NewInstr.addImm(0);
9465 } else if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
9466 const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
9467 // If we need to move this to VGPRs, we need to unpack the second
9468 // operand back into the 2 separate ones for bit offset and width.
9469 assert(OffsetWidthOp.isImm() &&
9470 "Scalar BFE is only implemented for constant width and offset");
9471 uint32_t Imm = OffsetWidthOp.getImm();
9472
9473 uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
9474 uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
9475 NewInstr.addImm(Offset);
9476 NewInstr.addImm(BitWidth);
9477 } else {
9478 if (AMDGPU::getNamedOperandIdx(NewOpcode,
9479 AMDGPU::OpName::src1_modifiers) >= 0)
9480 NewInstr.addImm(0);
9481 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::src1) >= 0)
9482 NewInstr->addOperand(Inst.getOperand(2));
9483 if (AMDGPU::getNamedOperandIdx(NewOpcode,
9484 AMDGPU::OpName::src2_modifiers) >= 0)
9485 NewInstr.addImm(0);
9486 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::src2) >= 0)
9487 NewInstr->addOperand(Inst.getOperand(3));
9488 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::clamp) >= 0)
9489 NewInstr.addImm(0);
9490 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::omod) >= 0)
9491 NewInstr.addImm(0);
9492 if (AMDGPU::getNamedOperandIdx(NewOpcode, AMDGPU::OpName::op_sel) >= 0)
9493 NewInstr.addImm(0);
9494 }
9495 } else {
9496 // Just copy the SALU operands.
9497 for (const MachineOperand &Op : Inst.explicit_operands())
9498 NewInstr->addOperand(Op);
9499 }
9500
9501 // Remove any references to SCC. Vector instructions can't read from it, and
9502 // We're just about to add the implicit use / defs of VCC, and we don't want
9503 // both.
9504 bool DeadSCCDef = false;
9505 for (MachineOperand &Op : Inst.implicit_operands()) {
9506 if (Op.getReg() == AMDGPU::SCC) {
9507 // Only propagate through live-def of SCC.
9508 if (Op.isDef()) {
9509 if (Op.isDead())
9510 DeadSCCDef = true;
9511 else
9512 addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
9513 continue;
9514 }
9515
9516 addSCCDefsToVALUWorklist(NewInstr, Worklist);
9517 }
9518 }
9519 Inst.eraseFromParent();
9520 Register NewDstReg;
9521 if (NewInstr->getOperand(0).isReg() && NewInstr->getOperand(0).isDef()) {
9522 Register DstReg = NewInstr->getOperand(0).getReg();
9523 assert(DstReg.isVirtual());
9524 // Update the destination register class.
9525 const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(*NewInstr);
9526 assert(NewDstRC);
9527 NewDstReg = MRI.createVirtualRegister(NewDstRC);
9528 MRI.replaceRegWith(DstReg, NewDstReg);
9529 }
9530 fixImplicitOperands(*NewInstr);
9531
9532 if (DeadSCCDef) {
9533 // A scalar op with a dead SCC def lowers to a VALU op whose VCC def will
9534 // also be dead.
9535 if (MachineOperand *VCCDef =
9536 NewInstr->findRegisterDefOperand(RI.getVCC(), &RI))
9537 VCCDef->setIsDead();
9538 }
9539
9540 // Legalize the operands
9541 legalizeOperands(*NewInstr, MDT);
9542 if (NewDstReg)
9543 addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
9544}
9545
9546// Add/sub require special handling to deal with carry outs.
9547std::pair<bool, MachineBasicBlock *>
9548SIInstrInfo::moveScalarAddSub(SIInstrWorklist &Worklist, MachineInstr &Inst,
9549 MachineDominatorTree *MDT) const {
9550 if (ST.hasAddNoCarryInsts()) {
9551 // Assume there is no user of scc since we don't select this in that case.
9552 // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
9553 // is used.
9554
9555 MachineBasicBlock &MBB = *Inst.getParent();
9556 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9557
9558 Register OldDstReg = Inst.getOperand(0).getReg();
9559 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9560
9561 unsigned Opc = Inst.getOpcode();
9562 assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
9563
9564 unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
9565 AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
9566
9567 assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
9568 Inst.removeOperand(3);
9569
9570 Inst.setDesc(get(NewOpc));
9571 Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
9572 Inst.addImplicitDefUseOperands(*MBB.getParent());
9573 MRI.replaceRegWith(OldDstReg, ResultReg);
9574 MachineBasicBlock *NewBB = legalizeOperands(Inst, MDT);
9575
9576 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
9577 return std::pair(true, NewBB);
9578 }
9579
9580 return std::pair(false, nullptr);
9581}
9582
9583void SIInstrInfo::lowerSelect(SIInstrWorklist &Worklist, MachineInstr &Inst,
9584 MachineDominatorTree *MDT) const {
9585
9586 MachineBasicBlock &MBB = *Inst.getParent();
9587 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9588 MachineBasicBlock::iterator MII = Inst;
9589 const DebugLoc &DL = Inst.getDebugLoc();
9590
9591 MachineOperand &Dest = Inst.getOperand(0);
9592 MachineOperand &Src0 = Inst.getOperand(1);
9593 MachineOperand &Src1 = Inst.getOperand(2);
9594 MachineOperand &Cond = Inst.getOperand(3);
9595
9596 Register CondReg = Cond.getReg();
9597 bool IsSCC = (CondReg == AMDGPU::SCC);
9598
9599 // Remove S_CSELECT instructions that we previously inserted to feed the SCC
9600 // condition output from S_CMP into the SGPR condition input of V_CNDMASK. If
9601 // the S_CMP has been promoted to V_CMP then we can feed its SGPR condition
9602 // output directly into the V_CNDMASK.
9603 if (!IsSCC && Src0.isImm() && (Src0.getImm() == -1) && Src1.isImm() &&
9604 (Src1.getImm() == 0)) {
9605 for (MachineOperand &UseMO :
9607 MachineInstr &UseMI = *UseMO.getParent();
9608 switch (UseMI.getOpcode()) {
9609 case AMDGPU::V_CNDMASK_B16_fake16_e32:
9610 case AMDGPU::V_CNDMASK_B16_fake16_e64:
9611 case AMDGPU::V_CNDMASK_B16_t16_e32:
9612 case AMDGPU::V_CNDMASK_B16_t16_e64:
9613 case AMDGPU::V_CNDMASK_B32_e32:
9614 case AMDGPU::V_CNDMASK_B32_e64:
9615 case AMDGPU::V_CNDMASK_B64_PSEUDO:
9616 if (UseMO.isImplicit() ||
9617 &UseMO == getNamedOperand(UseMI, AMDGPU::OpName::src2))
9618 UseMO.setReg(CondReg);
9619 }
9620 }
9621 if (MRI.use_nodbg_empty(Dest.getReg()))
9622 return;
9623 }
9624
9625 Register NewCondReg = CondReg;
9626 if (IsSCC) {
9627 const TargetRegisterClass *TC = RI.getWaveMaskRegClass();
9628 NewCondReg = MRI.createVirtualRegister(TC);
9629
9630 // Now look for the closest SCC def if it is a copy
9631 // replacing the CondReg with the COPY source register
9632 bool CopyFound = false;
9633 for (MachineInstr &CandI :
9635 Inst.getParent()->rend())) {
9636 if (CandI.findRegisterDefOperandIdx(AMDGPU::SCC, &RI, false, false) !=
9637 -1) {
9638 if (CandI.isCopy() && CandI.getOperand(0).getReg() == AMDGPU::SCC) {
9639 BuildMI(MBB, MII, DL, get(AMDGPU::COPY), NewCondReg)
9640 .addReg(CandI.getOperand(1).getReg());
9641 CopyFound = true;
9642 }
9643 break;
9644 }
9645 }
9646 if (!CopyFound) {
9647 // SCC def is not a copy
9648 // Insert a trivial select instead of creating a copy, because a copy from
9649 // SCC would semantically mean just copying a single bit, but we may need
9650 // the result to be a vector condition mask that needs preserving.
9651 unsigned Opcode =
9652 ST.isWave64() ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
9653 auto NewSelect =
9654 BuildMI(MBB, MII, DL, get(Opcode), NewCondReg).addImm(-1).addImm(0);
9655 NewSelect->getOperand(3).setIsUndef(Cond.isUndef());
9656 }
9657 }
9658
9659 Register NewDestReg = MRI.createVirtualRegister(
9660 RI.getEquivalentVGPRClass(MRI.getRegClass(Dest.getReg())));
9661 MachineInstr *NewInst;
9662 if (Inst.getOpcode() == AMDGPU::S_CSELECT_B32) {
9663 NewInst = BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B32_e64), NewDestReg)
9664 .addImm(0)
9665 .add(Src1) // False
9666 .addImm(0)
9667 .add(Src0) // True
9668 .addReg(NewCondReg);
9669 } else {
9670 NewInst =
9671 BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B64_PSEUDO), NewDestReg)
9672 .add(Src1) // False
9673 .add(Src0) // True
9674 .addReg(NewCondReg);
9675 }
9676 MRI.replaceRegWith(Dest.getReg(), NewDestReg);
9677 legalizeOperands(*NewInst, MDT);
9678 addUsersToMoveToVALUWorklist(NewDestReg, MRI, Worklist);
9679}
9680
9681void SIInstrInfo::lowerScalarAbs(SIInstrWorklist &Worklist,
9682 MachineInstr &Inst) const {
9683 MachineBasicBlock &MBB = *Inst.getParent();
9684 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9685 MachineBasicBlock::iterator MII = Inst;
9686 const DebugLoc &DL = Inst.getDebugLoc();
9687
9688 MachineOperand &Dest = Inst.getOperand(0);
9689 MachineOperand &Src = Inst.getOperand(1);
9690 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9691 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9692
9693 bool HasCarryOut = !ST.hasAddNoCarryInsts();
9694 unsigned SubOp =
9695 HasCarryOut ? AMDGPU::V_SUB_CO_U32_e32 : AMDGPU::V_SUB_U32_e32;
9696
9697 MachineInstrBuilder Sub =
9698 BuildMI(MBB, MII, DL, get(SubOp), TmpReg).addImm(0).addReg(Src.getReg());
9699 if (HasCarryOut)
9700 Sub.setOperandDead(3); // Dead vcc
9701
9702 BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
9703 .addReg(Src.getReg())
9704 .addReg(TmpReg);
9705
9706 MRI.replaceRegWith(Dest.getReg(), ResultReg);
9707 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
9708}
9709
9710void SIInstrInfo::lowerScalarAbsDiff(SIInstrWorklist &Worklist,
9711 MachineInstr &Inst) const {
9712 MachineBasicBlock &MBB = *Inst.getParent();
9713 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9714 MachineBasicBlock::iterator MII = Inst;
9715 const DebugLoc &DL = Inst.getDebugLoc();
9716
9717 MachineOperand &Dest = Inst.getOperand(0);
9718 MachineOperand &Src1 = Inst.getOperand(1);
9719 MachineOperand &Src2 = Inst.getOperand(2);
9720 Register SubResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9721 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9722 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9723
9724 bool HasCarryOut = !ST.hasAddNoCarryInsts();
9725 unsigned SubOp =
9726 HasCarryOut ? AMDGPU::V_SUB_CO_U32_e32 : AMDGPU::V_SUB_U32_e32;
9727
9728 MachineInstrBuilder Sub1 = BuildMI(MBB, MII, DL, get(SubOp), SubResultReg)
9729 .addReg(Src1.getReg())
9730 .addReg(Src2.getReg());
9731
9732 MachineInstrBuilder Sub2 =
9733 BuildMI(MBB, MII, DL, get(SubOp), TmpReg).addImm(0).addReg(SubResultReg);
9734
9735 if (HasCarryOut) {
9736 Sub1.setOperandDead(3); // Dead vcc
9737 Sub2.setOperandDead(3); // Dead vcc
9738 }
9739
9740 BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
9741 .addReg(SubResultReg)
9742 .addReg(TmpReg);
9743
9744 MRI.replaceRegWith(Dest.getReg(), ResultReg);
9745 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
9746}
9747
9748void SIInstrInfo::lowerScalarXnor(SIInstrWorklist &Worklist,
9749 MachineInstr &Inst) const {
9750 MachineBasicBlock &MBB = *Inst.getParent();
9751 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9752 MachineBasicBlock::iterator MII = Inst;
9753 const DebugLoc &DL = Inst.getDebugLoc();
9754
9755 MachineOperand &Dest = Inst.getOperand(0);
9756 MachineOperand &Src0 = Inst.getOperand(1);
9757 MachineOperand &Src1 = Inst.getOperand(2);
9758
9759 if (ST.hasDLInsts()) {
9760 Register NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9761 legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
9762 legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
9763
9764 BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
9765 .add(Src0)
9766 .add(Src1);
9767
9768 MRI.replaceRegWith(Dest.getReg(), NewDest);
9769 addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
9770 } else {
9771 // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
9772 // invert either source and then perform the XOR. If either source is a
9773 // scalar register, then we can leave the inversion on the scalar unit to
9774 // achieve a better distribution of scalar and vector instructions.
9775 bool Src0IsSGPR = Src0.isReg() &&
9776 RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
9777 bool Src1IsSGPR = Src1.isReg() &&
9778 RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
9779 MachineInstr *Xor;
9780 Register Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
9781 Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
9782
9783 // Build a pair of scalar instructions and add them to the work list.
9784 // The next iteration over the work list will lower these to the vector
9785 // unit as necessary.
9786 if (Src0IsSGPR) {
9787 BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src0);
9788 Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
9789 .addReg(Temp)
9790 .add(Src1);
9791 } else if (Src1IsSGPR) {
9792 BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src1);
9793 Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
9794 .add(Src0)
9795 .addReg(Temp);
9796 } else {
9797 Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
9798 .add(Src0)
9799 .add(Src1);
9800 MachineInstr *Not =
9801 BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest).addReg(Temp);
9802 Worklist.insert(Not);
9803 }
9804
9805 MRI.replaceRegWith(Dest.getReg(), NewDest);
9806
9807 Worklist.insert(Xor);
9808
9809 addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
9810 }
9811}
9812
9813void SIInstrInfo::splitScalarNotBinop(SIInstrWorklist &Worklist,
9814 MachineInstr &Inst,
9815 unsigned Opcode) const {
9816 MachineBasicBlock &MBB = *Inst.getParent();
9817 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9818 MachineBasicBlock::iterator MII = Inst;
9819 const DebugLoc &DL = Inst.getDebugLoc();
9820
9821 MachineOperand &Dest = Inst.getOperand(0);
9822 MachineOperand &Src0 = Inst.getOperand(1);
9823 MachineOperand &Src1 = Inst.getOperand(2);
9824
9825 Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
9826 Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
9827
9828 MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
9829 .add(Src0)
9830 .add(Src1);
9831
9832 MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
9833 .addReg(Interm);
9834
9835 Worklist.insert(&Op);
9836 Worklist.insert(&Not);
9837
9838 MRI.replaceRegWith(Dest.getReg(), NewDest);
9839 addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
9840}
9841
9842void SIInstrInfo::splitScalarBinOpN2(SIInstrWorklist &Worklist,
9843 MachineInstr &Inst,
9844 unsigned Opcode) const {
9845 MachineBasicBlock &MBB = *Inst.getParent();
9846 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9847 MachineBasicBlock::iterator MII = Inst;
9848 const DebugLoc &DL = Inst.getDebugLoc();
9849
9850 MachineOperand &Dest = Inst.getOperand(0);
9851 MachineOperand &Src0 = Inst.getOperand(1);
9852 MachineOperand &Src1 = Inst.getOperand(2);
9853
9854 Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
9855 Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
9856
9857 MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
9858 .add(Src1);
9859
9860 MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
9861 .add(Src0)
9862 .addReg(Interm);
9863
9864 Worklist.insert(&Not);
9865 Worklist.insert(&Op);
9866
9867 MRI.replaceRegWith(Dest.getReg(), NewDest);
9868 addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
9869}
9870
9871void SIInstrInfo::splitScalar64BitUnaryOp(SIInstrWorklist &Worklist,
9872 MachineInstr &Inst, unsigned Opcode,
9873 bool Swap) const {
9874 MachineBasicBlock &MBB = *Inst.getParent();
9875 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9876
9877 MachineOperand &Dest = Inst.getOperand(0);
9878 MachineOperand &Src0 = Inst.getOperand(1);
9879 const DebugLoc &DL = Inst.getDebugLoc();
9880
9881 MachineBasicBlock::iterator MII = Inst;
9882
9883 const MCInstrDesc &InstDesc = get(Opcode);
9884 const TargetRegisterClass *Src0RC = Src0.isReg() ?
9885 MRI.getRegClass(Src0.getReg()) :
9886 &AMDGPU::SGPR_32RegClass;
9887
9888 const TargetRegisterClass *Src0SubRC =
9889 RI.getSubRegisterClass(Src0RC, AMDGPU::sub0);
9890
9891 MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
9892 AMDGPU::sub0, Src0SubRC);
9893
9894 const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
9895 const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
9896 const TargetRegisterClass *NewDestSubRC =
9897 RI.getSubRegisterClass(NewDestRC, AMDGPU::sub0);
9898
9899 Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
9900 MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
9901
9902 MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
9903 AMDGPU::sub1, Src0SubRC);
9904
9905 Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
9906 MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
9907
9908 if (Swap)
9909 std::swap(DestSub0, DestSub1);
9910
9911 Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
9912 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
9913 .addReg(DestSub0)
9914 .addImm(AMDGPU::sub0)
9915 .addReg(DestSub1)
9916 .addImm(AMDGPU::sub1);
9917
9918 MRI.replaceRegWith(Dest.getReg(), FullDestReg);
9919
9920 Worklist.insert(&LoHalf);
9921 Worklist.insert(&HiHalf);
9922
9923 // We don't need to legalizeOperands here because for a single operand, src0
9924 // will support any kind of input.
9925
9926 // Move all users of this moved value.
9927 addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
9928}
9929
9930// There is not a vector equivalent of s_mul_u64. For this reason, we need to
9931// split the s_mul_u64 in 32-bit vector multiplications.
9932void SIInstrInfo::splitScalarSMulU64(SIInstrWorklist &Worklist,
9933 MachineInstr &Inst,
9934 MachineDominatorTree *MDT) const {
9935 MachineBasicBlock &MBB = *Inst.getParent();
9936 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9937
9938 Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
9939 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9940 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9941
9942 MachineOperand &Dest = Inst.getOperand(0);
9943 MachineOperand &Src0 = Inst.getOperand(1);
9944 MachineOperand &Src1 = Inst.getOperand(2);
9945 const DebugLoc &DL = Inst.getDebugLoc();
9946 MachineBasicBlock::iterator MII = Inst;
9947
9948 const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
9949 const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
9950 const TargetRegisterClass *Src0SubRC =
9951 RI.getSubRegisterClass(Src0RC, AMDGPU::sub0);
9952 if (RI.isSGPRClass(Src0SubRC))
9953 Src0SubRC = RI.getEquivalentVGPRClass(Src0SubRC);
9954 const TargetRegisterClass *Src1SubRC =
9955 RI.getSubRegisterClass(Src1RC, AMDGPU::sub0);
9956 if (RI.isSGPRClass(Src1SubRC))
9957 Src1SubRC = RI.getEquivalentVGPRClass(Src1SubRC);
9958
9959 // First, we extract the low 32-bit and high 32-bit values from each of the
9960 // operands.
9961 MachineOperand Op0L =
9962 buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
9963 MachineOperand Op1L =
9964 buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
9965 MachineOperand Op0H =
9966 buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
9967 MachineOperand Op1H =
9968 buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
9969
9970 // The multilication is done as follows:
9971 //
9972 // Op1H Op1L
9973 // * Op0H Op0L
9974 // --------------------
9975 // Op1H*Op0L Op1L*Op0L
9976 // + Op1H*Op0H Op1L*Op0H
9977 // -----------------------------------------
9978 // (Op1H*Op0L + Op1L*Op0H + carry) Op1L*Op0L
9979 //
9980 // We drop Op1H*Op0H because the result of the multiplication is a 64-bit
9981 // value and that would overflow.
9982 // The low 32-bit value is Op1L*Op0L.
9983 // The high 32-bit value is Op1H*Op0L + Op1L*Op0H + carry (from Op1L*Op0L).
9984
9985 Register Op1L_Op0H_Reg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9986 MachineInstr *Op1L_Op0H =
9987 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_LO_U32_e64), Op1L_Op0H_Reg)
9988 .add(Op1L)
9989 .add(Op0H);
9990
9991 Register Op1H_Op0L_Reg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9992 MachineInstr *Op1H_Op0L =
9993 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_LO_U32_e64), Op1H_Op0L_Reg)
9994 .add(Op1H)
9995 .add(Op0L);
9996
9997 Register CarryReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
9998 MachineInstr *Carry =
9999 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_HI_U32_e64), CarryReg)
10000 .add(Op1L)
10001 .add(Op0L);
10002
10003 MachineInstr *LoHalf =
10004 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_LO_U32_e64), DestSub0)
10005 .add(Op1L)
10006 .add(Op0L);
10007
10008 Register AddReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10009 MachineInstr *Add = BuildMI(MBB, MII, DL, get(AMDGPU::V_ADD_U32_e32), AddReg)
10010 .addReg(Op1L_Op0H_Reg)
10011 .addReg(Op1H_Op0L_Reg);
10012
10013 MachineInstr *HiHalf =
10014 BuildMI(MBB, MII, DL, get(AMDGPU::V_ADD_U32_e32), DestSub1)
10015 .addReg(AddReg)
10016 .addReg(CarryReg);
10017
10018 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
10019 .addReg(DestSub0)
10020 .addImm(AMDGPU::sub0)
10021 .addReg(DestSub1)
10022 .addImm(AMDGPU::sub1);
10023
10024 MRI.replaceRegWith(Dest.getReg(), FullDestReg);
10025
10026 // Try to legalize the operands in case we need to swap the order to keep it
10027 // valid.
10028 legalizeOperands(*Op1L_Op0H, MDT);
10029 legalizeOperands(*Op1H_Op0L, MDT);
10030 legalizeOperands(*Carry, MDT);
10031 legalizeOperands(*LoHalf, MDT);
10032 legalizeOperands(*Add, MDT);
10033 legalizeOperands(*HiHalf, MDT);
10034
10035 // Move all users of this moved value.
10036 addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
10037}
10038
10039// Lower S_MUL_U64_U32_PSEUDO/S_MUL_I64_I32_PSEUDO in two 32-bit vector
10040// multiplications.
10041void SIInstrInfo::splitScalarSMulPseudo(SIInstrWorklist &Worklist,
10042 MachineInstr &Inst,
10043 MachineDominatorTree *MDT) const {
10044 MachineBasicBlock &MBB = *Inst.getParent();
10045 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
10046
10047 Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
10048 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10049 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10050
10051 MachineOperand &Dest = Inst.getOperand(0);
10052 MachineOperand &Src0 = Inst.getOperand(1);
10053 MachineOperand &Src1 = Inst.getOperand(2);
10054 const DebugLoc &DL = Inst.getDebugLoc();
10055 MachineBasicBlock::iterator MII = Inst;
10056
10057 const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
10058 const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
10059 const TargetRegisterClass *Src0SubRC =
10060 RI.getSubRegisterClass(Src0RC, AMDGPU::sub0);
10061 if (RI.isSGPRClass(Src0SubRC))
10062 Src0SubRC = RI.getEquivalentVGPRClass(Src0SubRC);
10063 const TargetRegisterClass *Src1SubRC =
10064 RI.getSubRegisterClass(Src1RC, AMDGPU::sub0);
10065 if (RI.isSGPRClass(Src1SubRC))
10066 Src1SubRC = RI.getEquivalentVGPRClass(Src1SubRC);
10067
10068 // First, we extract the low 32-bit and high 32-bit values from each of the
10069 // operands.
10070 MachineOperand Op0L =
10071 buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
10072 MachineOperand Op1L =
10073 buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
10074
10075 unsigned Opc = Inst.getOpcode();
10076 unsigned NewOpc = Opc == AMDGPU::S_MUL_U64_U32_PSEUDO
10077 ? AMDGPU::V_MUL_HI_U32_e64
10078 : AMDGPU::V_MUL_HI_I32_e64;
10079 MachineInstr *HiHalf =
10080 BuildMI(MBB, MII, DL, get(NewOpc), DestSub1).add(Op1L).add(Op0L);
10081
10082 MachineInstr *LoHalf =
10083 BuildMI(MBB, MII, DL, get(AMDGPU::V_MUL_LO_U32_e64), DestSub0)
10084 .add(Op1L)
10085 .add(Op0L);
10086
10087 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
10088 .addReg(DestSub0)
10089 .addImm(AMDGPU::sub0)
10090 .addReg(DestSub1)
10091 .addImm(AMDGPU::sub1);
10092
10093 MRI.replaceRegWith(Dest.getReg(), FullDestReg);
10094
10095 // Try to legalize the operands in case we need to swap the order to keep it
10096 // valid.
10097 legalizeOperands(*HiHalf, MDT);
10098 legalizeOperands(*LoHalf, MDT);
10099
10100 // Move all users of this moved value.
10101 addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
10102}
10103
10104void SIInstrInfo::splitScalar64BitBinaryOp(SIInstrWorklist &Worklist,
10105 MachineInstr &Inst, unsigned Opcode,
10106 MachineDominatorTree *MDT) const {
10107 MachineBasicBlock &MBB = *Inst.getParent();
10108 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
10109
10110 MachineOperand &Dest = Inst.getOperand(0);
10111 MachineOperand &Src0 = Inst.getOperand(1);
10112 MachineOperand &Src1 = Inst.getOperand(2);
10113 const DebugLoc &DL = Inst.getDebugLoc();
10114
10115 MachineBasicBlock::iterator MII = Inst;
10116
10117 const MCInstrDesc &InstDesc = get(Opcode);
10118 const TargetRegisterClass *Src0RC = Src0.isReg() ?
10119 MRI.getRegClass(Src0.getReg()) :
10120 &AMDGPU::SGPR_32RegClass;
10121
10122 const TargetRegisterClass *Src0SubRC =
10123 RI.getSubRegisterClass(Src0RC, AMDGPU::sub0);
10124 const TargetRegisterClass *Src1RC = Src1.isReg() ?
10125 MRI.getRegClass(Src1.getReg()) :
10126 &AMDGPU::SGPR_32RegClass;
10127
10128 const TargetRegisterClass *Src1SubRC =
10129 RI.getSubRegisterClass(Src1RC, AMDGPU::sub0);
10130
10131 MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
10132 AMDGPU::sub0, Src0SubRC);
10133 MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
10134 AMDGPU::sub0, Src1SubRC);
10135 MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
10136 AMDGPU::sub1, Src0SubRC);
10137 MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
10138 AMDGPU::sub1, Src1SubRC);
10139
10140 const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
10141 const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
10142 const TargetRegisterClass *NewDestSubRC =
10143 RI.getSubRegisterClass(NewDestRC, AMDGPU::sub0);
10144
10145 Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
10146 MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
10147 .add(SrcReg0Sub0)
10148 .add(SrcReg1Sub0);
10149
10150 Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
10151 MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
10152 .add(SrcReg0Sub1)
10153 .add(SrcReg1Sub1);
10154
10155 Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
10156 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
10157 .addReg(DestSub0)
10158 .addImm(AMDGPU::sub0)
10159 .addReg(DestSub1)
10160 .addImm(AMDGPU::sub1);
10161
10162 MRI.replaceRegWith(Dest.getReg(), FullDestReg);
10163
10164 Worklist.insert(&LoHalf);
10165 Worklist.insert(&HiHalf);
10166
10167 // Move all users of this moved value.
10168 addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
10169}
10170
10171void SIInstrInfo::splitScalar64BitXnor(SIInstrWorklist &Worklist,
10172 MachineInstr &Inst,
10173 MachineDominatorTree *MDT) const {
10174 MachineBasicBlock &MBB = *Inst.getParent();
10175 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
10176
10177 MachineOperand &Dest = Inst.getOperand(0);
10178 MachineOperand &Src0 = Inst.getOperand(1);
10179 MachineOperand &Src1 = Inst.getOperand(2);
10180 const DebugLoc &DL = Inst.getDebugLoc();
10181
10182 MachineBasicBlock::iterator MII = Inst;
10183
10184 const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
10185
10186 Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
10187
10188 MachineOperand* Op0;
10189 MachineOperand* Op1;
10190
10191 if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
10192 Op0 = &Src0;
10193 Op1 = &Src1;
10194 } else {
10195 Op0 = &Src1;
10196 Op1 = &Src0;
10197 }
10198
10199 BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
10200 .add(*Op0);
10201
10202 Register NewDest = MRI.createVirtualRegister(DestRC);
10203
10204 MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
10205 .addReg(Interm)
10206 .add(*Op1);
10207
10208 MRI.replaceRegWith(Dest.getReg(), NewDest);
10209
10210 Worklist.insert(&Xor);
10211}
10212
10213void SIInstrInfo::splitScalar64BitBCNT(SIInstrWorklist &Worklist,
10214 MachineInstr &Inst) const {
10215 MachineBasicBlock &MBB = *Inst.getParent();
10216 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
10217
10218 MachineBasicBlock::iterator MII = Inst;
10219 const DebugLoc &DL = Inst.getDebugLoc();
10220
10221 MachineOperand &Dest = Inst.getOperand(0);
10222 MachineOperand &Src = Inst.getOperand(1);
10223
10224 const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
10225 const TargetRegisterClass *SrcRC = Src.isReg() ?
10226 MRI.getRegClass(Src.getReg()) :
10227 &AMDGPU::SGPR_32RegClass;
10228
10229 Register MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10230 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10231
10232 const TargetRegisterClass *SrcSubRC =
10233 RI.getSubRegisterClass(SrcRC, AMDGPU::sub0);
10234
10235 MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
10236 AMDGPU::sub0, SrcSubRC);
10237 MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
10238 AMDGPU::sub1, SrcSubRC);
10239
10240 BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
10241
10242 BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
10243
10244 MRI.replaceRegWith(Dest.getReg(), ResultReg);
10245
10246 // We don't need to legalize operands here. src0 for either instruction can be
10247 // an SGPR, and the second input is unused or determined here.
10248 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
10249}
10250
10251void SIInstrInfo::splitScalar64BitBFE(SIInstrWorklist &Worklist,
10252 MachineInstr &Inst) const {
10253 MachineBasicBlock &MBB = *Inst.getParent();
10254 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
10255 MachineBasicBlock::iterator MII = Inst;
10256 const DebugLoc &DL = Inst.getDebugLoc();
10257
10258 MachineOperand &Dest = Inst.getOperand(0);
10259 uint32_t Imm = Inst.getOperand(2).getImm();
10260 uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
10261 uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
10262
10263 (void) Offset;
10264
10265 // Only sext_inreg cases handled.
10266 assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
10267 Offset == 0 && "Not implemented");
10268
10269 if (BitWidth < 32) {
10270 Register MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10271 Register MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10272 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
10273
10274 BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32_e64), MidRegLo)
10275 .addReg(Inst.getOperand(1).getReg(), {}, AMDGPU::sub0)
10276 .addImm(0)
10277 .addImm(BitWidth);
10278
10279 BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
10280 .addImm(31)
10281 .addReg(MidRegLo);
10282
10283 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
10284 .addReg(MidRegLo)
10285 .addImm(AMDGPU::sub0)
10286 .addReg(MidRegHi)
10287 .addImm(AMDGPU::sub1);
10288
10289 MRI.replaceRegWith(Dest.getReg(), ResultReg);
10290 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
10291 return;
10292 }
10293
10294 MachineOperand &Src = Inst.getOperand(1);
10295 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10296 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
10297
10298 BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
10299 .addImm(31)
10300 .addReg(Src.getReg(), {}, AMDGPU::sub0);
10301
10302 BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
10303 .addReg(Src.getReg(), {}, AMDGPU::sub0)
10304 .addImm(AMDGPU::sub0)
10305 .addReg(TmpReg)
10306 .addImm(AMDGPU::sub1);
10307
10308 MRI.replaceRegWith(Dest.getReg(), ResultReg);
10309 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
10310}
10311
10312void SIInstrInfo::splitScalar64BitCountOp(SIInstrWorklist &Worklist,
10313 MachineInstr &Inst, unsigned Opcode,
10314 MachineDominatorTree *MDT) const {
10315 // (S_FLBIT_I32_B64 hi:lo) ->
10316 // -> (umin (V_FFBH_U32_e32 hi), (or (V_FFBH_U32_e32 lo), 32))
10317 // (S_FF1_I32_B64 hi:lo) ->
10318 // ->(umin (or (V_FFBL_B32_e32 hi), 32) (V_FFBL_B32_e32 lo))
10319
10320 MachineBasicBlock &MBB = *Inst.getParent();
10321 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
10322 MachineBasicBlock::iterator MII = Inst;
10323 const DebugLoc &DL = Inst.getDebugLoc();
10324
10325 MachineOperand &Dest = Inst.getOperand(0);
10326 MachineOperand &Src = Inst.getOperand(1);
10327
10328 const MCInstrDesc &InstDesc = get(Opcode);
10329
10330 bool IsCtlz = Opcode == AMDGPU::V_FFBH_U32_e32;
10331
10332 const TargetRegisterClass *SrcRC =
10333 Src.isReg() ? MRI.getRegClass(Src.getReg()) : &AMDGPU::SGPR_32RegClass;
10334 const TargetRegisterClass *SrcSubRC =
10335 RI.getSubRegisterClass(SrcRC, AMDGPU::sub0);
10336
10337 MachineOperand SrcRegSub0 =
10338 buildExtractSubRegOrImm(MII, MRI, Src, SrcRC, AMDGPU::sub0, SrcSubRC);
10339 MachineOperand SrcRegSub1 =
10340 buildExtractSubRegOrImm(MII, MRI, Src, SrcRC, AMDGPU::sub1, SrcSubRC);
10341
10342 Register MidReg1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10343 Register MidReg2 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10344 Register MidReg3 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10345 Register MidReg4 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10346
10347 BuildMI(MBB, MII, DL, InstDesc, MidReg1).add(SrcRegSub0);
10348
10349 BuildMI(MBB, MII, DL, InstDesc, MidReg2).add(SrcRegSub1);
10350
10351 BuildMI(MBB, MII, DL, get(AMDGPU::V_OR_B32_e32), MidReg3)
10352 .addImm(32)
10353 .addReg(IsCtlz ? MidReg1 : MidReg2);
10354
10355 BuildMI(MBB, MII, DL, get(AMDGPU::V_MIN_U32_e64), MidReg4)
10356 .addReg(MidReg3)
10357 .addReg(IsCtlz ? MidReg2 : MidReg1);
10358
10359 MRI.replaceRegWith(Dest.getReg(), MidReg4);
10360
10361 addUsersToMoveToVALUWorklist(MidReg4, MRI, Worklist);
10362}
10363
10364void SIInstrInfo::addUsersToMoveToVALUWorklist(
10366 SIInstrWorklist &Worklist) const {
10367 for (MachineOperand &MO : make_early_inc_range(MRI.use_operands(DstReg))) {
10368 MachineInstr &UseMI = *MO.getParent();
10369
10370 unsigned OpNo = 0;
10371
10372 switch (UseMI.getOpcode()) {
10373 case AMDGPU::COPY:
10374 case AMDGPU::WQM:
10375 case AMDGPU::SOFT_WQM:
10376 case AMDGPU::STRICT_WWM:
10377 case AMDGPU::STRICT_WQM:
10378 case AMDGPU::REG_SEQUENCE:
10379 case AMDGPU::PHI:
10380 case AMDGPU::INSERT_SUBREG:
10381 break;
10382 default:
10383 OpNo = MO.getOperandNo();
10384 break;
10385 }
10386
10387 const TargetRegisterClass *OpRC = getOpRegClass(UseMI, OpNo);
10388 MRI.constrainRegClass(DstReg, OpRC);
10389
10390 if (!RI.hasVectorRegisters(OpRC))
10391 Worklist.insert(&UseMI);
10392 else
10393 // Legalization could change user list.
10395 }
10396}
10397
10398void SIInstrInfo::movePackToVALU(SIInstrWorklist &Worklist,
10400 MachineInstr &Inst) const {
10401 Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10402 MachineBasicBlock *MBB = Inst.getParent();
10403 MachineOperand &Src0 = Inst.getOperand(1);
10404 MachineOperand &Src1 = Inst.getOperand(2);
10405 const DebugLoc &DL = Inst.getDebugLoc();
10406
10407 if (ST.useRealTrue16Insts()) {
10408 Register SrcReg0, SrcReg1;
10409 if (!Src0.isReg() || !RI.isVGPR(MRI, Src0.getReg())) {
10410 SrcReg0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10411 BuildMI(*MBB, Inst, DL,
10412 get(Src0.isImm() ? AMDGPU::V_MOV_B32_e32 : AMDGPU::COPY), SrcReg0)
10413 .add(Src0);
10414 } else {
10415 SrcReg0 = Src0.getReg();
10416 }
10417
10418 if (!Src1.isReg() || !RI.isVGPR(MRI, Src1.getReg())) {
10419 SrcReg1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10420 BuildMI(*MBB, Inst, DL,
10421 get(Src1.isImm() ? AMDGPU::V_MOV_B32_e32 : AMDGPU::COPY), SrcReg1)
10422 .add(Src1);
10423 } else {
10424 SrcReg1 = Src1.getReg();
10425 }
10426
10427 bool isSrc0Reg16 = MRI.constrainRegClass(SrcReg0, &AMDGPU::VGPR_16RegClass);
10428 bool isSrc1Reg16 = MRI.constrainRegClass(SrcReg1, &AMDGPU::VGPR_16RegClass);
10429
10430 auto NewMI = BuildMI(*MBB, Inst, DL, get(AMDGPU::REG_SEQUENCE), ResultReg);
10431 switch (Inst.getOpcode()) {
10432 case AMDGPU::S_PACK_LL_B32_B16:
10433 NewMI
10434 .addReg(SrcReg0, {},
10435 isSrc0Reg16 ? AMDGPU::NoSubRegister : AMDGPU::lo16)
10436 .addImm(AMDGPU::lo16)
10437 .addReg(SrcReg1, {},
10438 isSrc1Reg16 ? AMDGPU::NoSubRegister : AMDGPU::lo16)
10439 .addImm(AMDGPU::hi16);
10440 break;
10441 case AMDGPU::S_PACK_LH_B32_B16:
10442 NewMI
10443 .addReg(SrcReg0, {},
10444 isSrc0Reg16 ? AMDGPU::NoSubRegister : AMDGPU::lo16)
10445 .addImm(AMDGPU::lo16)
10446 .addReg(SrcReg1, {}, AMDGPU::hi16)
10447 .addImm(AMDGPU::hi16);
10448 break;
10449 case AMDGPU::S_PACK_HL_B32_B16:
10450 NewMI.addReg(SrcReg0, {}, AMDGPU::hi16)
10451 .addImm(AMDGPU::lo16)
10452 .addReg(SrcReg1, {},
10453 isSrc1Reg16 ? AMDGPU::NoSubRegister : AMDGPU::lo16)
10454 .addImm(AMDGPU::hi16);
10455 break;
10456 case AMDGPU::S_PACK_HH_B32_B16:
10457 NewMI.addReg(SrcReg0, {}, AMDGPU::hi16)
10458 .addImm(AMDGPU::lo16)
10459 .addReg(SrcReg1, {}, AMDGPU::hi16)
10460 .addImm(AMDGPU::hi16);
10461 break;
10462 default:
10463 llvm_unreachable("unhandled s_pack_* instruction");
10464 }
10465
10466 MachineOperand &Dest = Inst.getOperand(0);
10467 MRI.replaceRegWith(Dest.getReg(), ResultReg);
10468 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
10469 return;
10470 }
10471
10472 switch (Inst.getOpcode()) {
10473 case AMDGPU::S_PACK_LL_B32_B16: {
10474 Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10475 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10476
10477 // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
10478 // 0.
10479 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
10480 .addImm(0xffff);
10481
10482 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
10483 .addReg(ImmReg)
10484 .add(Src0);
10485
10486 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
10487 .add(Src1)
10488 .addImm(16)
10489 .addReg(TmpReg);
10490 break;
10491 }
10492 case AMDGPU::S_PACK_LH_B32_B16: {
10493 Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10494 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
10495 .addImm(0xffff);
10496 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32_e64), ResultReg)
10497 .addReg(ImmReg)
10498 .add(Src0)
10499 .add(Src1);
10500 break;
10501 }
10502 case AMDGPU::S_PACK_HL_B32_B16: {
10503 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10504 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
10505 .addImm(16)
10506 .add(Src0);
10507 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
10508 .add(Src1)
10509 .addImm(16)
10510 .addReg(TmpReg);
10511 break;
10512 }
10513 case AMDGPU::S_PACK_HH_B32_B16: {
10514 Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10515 Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
10516 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
10517 .addImm(16)
10518 .add(Src0);
10519 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
10520 .addImm(0xffff0000);
10521 BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32_e64), ResultReg)
10522 .add(Src1)
10523 .addReg(ImmReg)
10524 .addReg(TmpReg);
10525 break;
10526 }
10527 default:
10528 llvm_unreachable("unhandled s_pack_* instruction");
10529 }
10530
10531 MachineOperand &Dest = Inst.getOperand(0);
10532 MRI.replaceRegWith(Dest.getReg(), ResultReg);
10533 addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
10534}
10535
10536void SIInstrInfo::addSCCDefUsersToVALUWorklist(const MachineOperand &Op,
10537 MachineInstr &SCCDefInst,
10538 SIInstrWorklist &Worklist,
10539 Register NewCond) const {
10540
10541 // Ensure that def inst defines SCC, which is still live.
10542 assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
10543 !Op.isDead() && Op.getParent() == &SCCDefInst);
10544 SmallVector<MachineInstr *, 4> CopyToDelete;
10545 // This assumes that all the users of SCC are in the same block
10546 // as the SCC def.
10547 for (MachineInstr &MI : // Skip the def inst itself.
10548 make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
10549 SCCDefInst.getParent()->end())) {
10550 // Check if SCC is used first.
10551 int SCCIdx = MI.findRegisterUseOperandIdx(AMDGPU::SCC, &RI, false);
10552 if (SCCIdx != -1) {
10553 if (MI.isCopy()) {
10554 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
10555 Register DestReg = MI.getOperand(0).getReg();
10556
10557 MRI.replaceRegWith(DestReg, NewCond);
10558 CopyToDelete.push_back(&MI);
10559 } else {
10560
10561 if (NewCond.isValid())
10562 MI.getOperand(SCCIdx).setReg(NewCond);
10563
10564 Worklist.insert(&MI);
10565 }
10566 }
10567 // Exit if we find another SCC def.
10568 if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, &RI, false, false) != -1)
10569 break;
10570 }
10571 for (auto &Copy : CopyToDelete)
10572 Copy->eraseFromParent();
10573}
10574
10575// Instructions that use SCC may be converted to VALU instructions. When that
10576// happens, the SCC register is changed to VCC_LO. The instruction that defines
10577// SCC must be changed to an instruction that defines VCC. This function makes
10578// sure that the instruction that defines SCC is added to the moveToVALU
10579// worklist.
10580void SIInstrInfo::addSCCDefsToVALUWorklist(MachineInstr *SCCUseInst,
10581 SIInstrWorklist &Worklist) const {
10582 // Look for a preceding instruction that either defines VCC or SCC. If VCC
10583 // then there is nothing to do because the defining instruction has been
10584 // converted to a VALU already. If SCC then that instruction needs to be
10585 // converted to a VALU.
10586 for (MachineInstr &MI :
10587 make_range(std::next(MachineBasicBlock::reverse_iterator(SCCUseInst)),
10588 SCCUseInst->getParent()->rend())) {
10589 if (MI.modifiesRegister(AMDGPU::VCC, &RI))
10590 break;
10591 if (MI.definesRegister(AMDGPU::SCC, &RI)) {
10592 Worklist.insert(&MI);
10593 break;
10594 }
10595 }
10596}
10597
10598const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
10599 const MachineInstr &Inst) const {
10600 const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
10601
10602 switch (Inst.getOpcode()) {
10603 // For target instructions, getOpRegClass just returns the virtual register
10604 // class associated with the operand, so we need to find an equivalent VGPR
10605 // register class in order to move the instruction to the VALU.
10606 case AMDGPU::COPY:
10607 case AMDGPU::PHI:
10608 case AMDGPU::REG_SEQUENCE:
10609 case AMDGPU::INSERT_SUBREG:
10610 case AMDGPU::WQM:
10611 case AMDGPU::SOFT_WQM:
10612 case AMDGPU::STRICT_WWM:
10613 case AMDGPU::STRICT_WQM: {
10614 const TargetRegisterClass *SrcRC = getOpRegClass(Inst, 1);
10615 if (RI.isAGPRClass(SrcRC)) {
10616 if (RI.isAGPRClass(NewDstRC))
10617 return nullptr;
10618
10619 switch (Inst.getOpcode()) {
10620 case AMDGPU::PHI:
10621 case AMDGPU::REG_SEQUENCE:
10622 case AMDGPU::INSERT_SUBREG:
10623 NewDstRC = RI.getEquivalentAGPRClass(NewDstRC);
10624 break;
10625 default:
10626 NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
10627 }
10628
10629 if (!NewDstRC)
10630 return nullptr;
10631 } else {
10632 if (!RI.isSGPRClass(NewDstRC) || NewDstRC == &AMDGPU::VReg_1RegClass)
10633 return nullptr;
10634
10635 NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
10636 if (!NewDstRC)
10637 return nullptr;
10638 }
10639
10640 return NewDstRC;
10641 }
10642 default:
10643 return NewDstRC;
10644 }
10645}
10646
10647// Find the one SGPR operand we are allowed to use.
10648Register SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
10649 int OpIndices[3]) const {
10650 const MCInstrDesc &Desc = MI.getDesc();
10651
10652 // Find the one SGPR operand we are allowed to use.
10653 //
10654 // First we need to consider the instruction's operand requirements before
10655 // legalizing. Some operands are required to be SGPRs, such as implicit uses
10656 // of VCC, but we are still bound by the constant bus requirement to only use
10657 // one.
10658 //
10659 // If the operand's class is an SGPR, we can never move it.
10660
10661 Register SGPRReg = findImplicitSGPRRead(MI);
10662 if (SGPRReg)
10663 return SGPRReg;
10664
10665 Register UsedSGPRs[3] = {Register()};
10666 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
10667
10668 for (unsigned i = 0; i < 3; ++i) {
10669 int Idx = OpIndices[i];
10670 if (Idx == -1)
10671 break;
10672
10673 const MachineOperand &MO = MI.getOperand(Idx);
10674 if (!MO.isReg())
10675 continue;
10676
10677 // Is this operand statically required to be an SGPR based on the operand
10678 // constraints?
10679 const TargetRegisterClass *OpRC =
10680 RI.getRegClass(getOpRegClassID(Desc.operands()[Idx]));
10681 bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
10682 if (IsRequiredSGPR)
10683 return MO.getReg();
10684
10685 // If this could be a VGPR or an SGPR, Check the dynamic register class.
10686 Register Reg = MO.getReg();
10687 const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
10688 if (RI.isSGPRClass(RegRC))
10689 UsedSGPRs[i] = Reg;
10690 }
10691
10692 // We don't have a required SGPR operand, so we have a bit more freedom in
10693 // selecting operands to move.
10694
10695 // Try to select the most used SGPR. If an SGPR is equal to one of the
10696 // others, we choose that.
10697 //
10698 // e.g.
10699 // V_FMA_F32 v0, s0, s0, s0 -> No moves
10700 // V_FMA_F32 v0, s0, s1, s0 -> Move s1
10701
10702 // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
10703 // prefer those.
10704
10705 if (UsedSGPRs[0]) {
10706 if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
10707 SGPRReg = UsedSGPRs[0];
10708 }
10709
10710 if (!SGPRReg && UsedSGPRs[1]) {
10711 if (UsedSGPRs[1] == UsedSGPRs[2])
10712 SGPRReg = UsedSGPRs[1];
10713 }
10714
10715 return SGPRReg;
10716}
10717
10719 AMDGPU::OpName OperandName) const {
10720 if (OperandName == AMDGPU::OpName::NUM_OPERAND_NAMES)
10721 return nullptr;
10722
10723 int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
10724 if (Idx == -1)
10725 return nullptr;
10726
10727 return &MI.getOperand(Idx);
10728}
10729
10731 if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
10732 int64_t Format = ST.getGeneration() >= AMDGPUSubtarget::GFX11
10735 return (Format << 44) |
10736 (1ULL << 56) | // RESOURCE_LEVEL = 1
10737 (3ULL << 60); // OOB_SELECT = 3
10738 }
10739
10740 uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
10741 if (ST.isAmdHsaOS()) {
10742 // Set ATC = 1. GFX9 doesn't have this bit.
10743 if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
10744 RsrcDataFormat |= (1ULL << 56);
10745
10746 // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
10747 // BTW, it disables TC L2 and therefore decreases performance.
10748 if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
10749 RsrcDataFormat |= (2ULL << 59);
10750 }
10751
10752 return RsrcDataFormat;
10753}
10754
10756 uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
10758 0xffffffff; // Size;
10759
10760 // GFX9 doesn't have ELEMENT_SIZE.
10761 if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
10762 uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize(true)) - 1;
10763 Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
10764 }
10765
10766 // IndexStride = 64 / 32.
10767 uint64_t IndexStride = ST.isWave64() ? 3 : 2;
10768 Rsrc23 |= IndexStride << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
10769
10770 // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
10771 // Clear them unless we want a huge stride.
10772 if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
10773 ST.getGeneration() <= AMDGPUSubtarget::GFX9)
10774 Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
10775
10776 return Rsrc23;
10777}
10778
10780 unsigned Opc = MI.getOpcode();
10781
10782 return isSMRD(Opc);
10783}
10784
10786 return get(Opc).mayLoad() &&
10787 (isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc) || isFLAT(Opc));
10788}
10789
10791 TypeSize &MemBytes) const {
10792 const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
10793 if (!Addr || !Addr->isFI())
10794 return Register();
10795
10796 assert(!MI.memoperands_empty() &&
10797 (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
10798
10799 FrameIndex = Addr->getIndex();
10800
10801 int VDataIdx =
10802 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
10803 MemBytes = TypeSize::getFixed(getOpSize(MI.getOpcode(), VDataIdx));
10804 return MI.getOperand(VDataIdx).getReg();
10805}
10806
10808 TypeSize &MemBytes) const {
10809 const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
10810 assert(Addr && Addr->isFI());
10811 FrameIndex = Addr->getIndex();
10812
10813 int DataIdx =
10814 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::data);
10815 MemBytes = TypeSize::getFixed(getOpSize(MI.getOpcode(), DataIdx));
10816 return MI.getOperand(DataIdx).getReg();
10817}
10818
10820 int &FrameIndex,
10821 TypeSize &MemBytes) const {
10822 if (!MI.mayLoad())
10823 return Register();
10824
10825 if (isMUBUF(MI) || isVGPRSpill(MI))
10826 return isStackAccess(MI, FrameIndex, MemBytes);
10827
10828 if (isSGPRSpill(MI))
10829 return isSGPRStackAccess(MI, FrameIndex, MemBytes);
10830
10831 return Register();
10832}
10833
10835 int &FrameIndex,
10836 TypeSize &MemBytes) const {
10837 if (!MI.mayStore())
10838 return Register();
10839
10840 if (isMUBUF(MI) || isVGPRSpill(MI))
10841 return isStackAccess(MI, FrameIndex, MemBytes);
10842
10843 if (isSGPRSpill(MI))
10844 return isSGPRStackAccess(MI, FrameIndex, MemBytes);
10845
10846 return Register();
10847}
10848
10850 unsigned Opc = MI.getOpcode();
10852 unsigned DescSize = Desc.getSize();
10853 if (Opc == AMDGPU::GLOBAL_LOAD_ASYNC_TO_LDS_B8_replay)
10854 return DescSize + 12; // Three scalar moves around the load.
10855
10856 // If we have a definitive size, we can use it. Otherwise we need to inspect
10857 // the operands to know the size.
10858 if (isFixedSize(MI)) {
10859 unsigned Size = DescSize;
10860
10861 // If we hit the buggy offset, an extra nop will be inserted in MC so
10862 // estimate the worst case.
10863 if (MI.isBranch() && ST.hasOffset3fBug())
10864 Size += 4;
10865
10866 return Size;
10867 }
10868
10869 // Instructions may have a 32-bit literal encoded after them. Check
10870 // operands that could ever be literals.
10871 if (isVALU(MI, /*AllowLDSDMA=*/false) || isSALU(MI)) {
10872 if (isDPP(MI))
10873 return DescSize;
10874 bool HasLiteral = false;
10875 unsigned LiteralSize = 4;
10876 for (int I = 0, E = MI.getNumExplicitOperands(); I != E; ++I) {
10877 const MachineOperand &Op = MI.getOperand(I);
10878 const MCOperandInfo &OpInfo = Desc.operands()[I];
10879 if (!Op.isReg() && !isInlineConstant(Op, OpInfo)) {
10880 HasLiteral = true;
10881 if (ST.has64BitLiterals()) {
10882 switch (OpInfo.OperandType) {
10883 default:
10884 break;
10887 if (!AMDGPU::isValid32BitLiteral(Op.getImm(), true))
10888 LiteralSize = 8;
10889 break;
10892 // A 32-bit literal is only valid when the value fits in BOTH signed
10893 // and unsigned 32-bit ranges [0, 2^31-1], matching the MC code
10894 // emitter's getLit64Encoding logic. This is because of the lack of
10895 // abilility to tell signedness of the literal, therefore we need to
10896 // be conservative and assume values outside this range require a
10897 // 64-bit literal encoding (8 bytes).
10898 if (!Op.isImm() || !isInt<32>(Op.getImm()) ||
10899 !isUInt<32>(Op.getImm()))
10900 LiteralSize = 8;
10901 break;
10902 }
10903 }
10904 break;
10905 }
10906 }
10907 return HasLiteral ? DescSize + LiteralSize : DescSize;
10908 }
10909
10910 // Check whether we have extra NSA words.
10911 if (isMIMG(MI)) {
10912 int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
10913 if (VAddr0Idx < 0)
10914 return 8;
10915
10916 int RSrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
10917 return 8 + 4 * ((RSrcIdx - VAddr0Idx + 2) / 4);
10918 }
10919
10920 switch (Opc) {
10921 case TargetOpcode::BUNDLE:
10922 return getInstBundleSize(MI);
10923 case TargetOpcode::INLINEASM:
10924 case TargetOpcode::INLINEASM_BR: {
10925 const MachineFunction *MF = MI.getMF();
10926 const char *AsmStr = MI.getOperand(0).getSymbolName();
10927 unsigned MaxLen = AMDGPU::getMaxInstLength(ST);
10928 return getInlineAsmLength(AsmStr, MF->getTarget().getMCAsmInfo(), MaxLen);
10929 }
10930 default:
10931 if (MI.isMetaInstruction())
10932 return 0;
10933
10934 // If D16 Pseudo inst, get correct MC code size
10935 const auto *D16Info = AMDGPU::getT16D16Helper(Opc);
10936 if (D16Info) {
10937 // Assume d16_lo/hi inst are always in same size
10938 unsigned LoInstOpcode = D16Info->LoOp;
10939 const MCInstrDesc &Desc = getMCOpcodeFromPseudo(LoInstOpcode);
10940 DescSize = Desc.getSize();
10941 }
10942
10943 // If FMA Pseudo inst, get correct MC code size
10944 if (Opc == AMDGPU::V_FMA_MIX_F16_t16 || Opc == AMDGPU::V_FMA_MIX_BF16_t16) {
10945 // All potential lowerings are the same size; arbitrarily pick one.
10946 const MCInstrDesc &Desc = getMCOpcodeFromPseudo(AMDGPU::V_FMA_MIXLO_F16);
10947 DescSize = Desc.getSize();
10948 }
10949
10950 return DescSize;
10951 }
10952}
10953
10956 if (MI.isBranch() && ST.hasOffset3fBug())
10957 return InstSizeVerifyMode::NoVerify;
10958 return InstSizeVerifyMode::ExactSize;
10959}
10960
10963 static const std::pair<int, const char *> TargetIndices[] = {
10964 {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
10965 {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
10966 {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
10967 {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
10968 {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
10969 return ArrayRef(TargetIndices);
10970}
10971
10972/// This is used by the post-RA scheduler (SchedulePostRAList.cpp). The
10973/// post-RA version of misched uses CreateTargetMIHazardRecognizer.
10976 const ScheduleDAG *DAG) const {
10977 return new GCNHazardRecognizer(DAG->MF);
10978}
10979
10980/// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
10981/// pass.
10988
10989// Called during:
10990// - pre-RA scheduling and post-RA scheduling
10993 const ScheduleDAGMI *DAG) const {
10994 // Borrowed from Arm Target
10995 // We would like to restrict this hazard recognizer to only
10996 // post-RA scheduling; we can tell that we're post-RA because we don't
10997 // track VRegLiveness.
10998 if (!DAG->hasVRegLiveness())
10999 return new GCNHazardRecognizer(DAG->MF);
11001}
11002
11003std::pair<unsigned, unsigned>
11005 return std::pair(TF & MO_MASK, TF & ~MO_MASK);
11006}
11007
11010 static const std::pair<unsigned, const char *> TargetFlags[] = {
11011 {MO_GOTPCREL, "amdgpu-gotprel"},
11012 {MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo"},
11013 {MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi"},
11014 {MO_GOTPCREL64, "amdgpu-gotprel64"},
11015 {MO_REL32_LO, "amdgpu-rel32-lo"},
11016 {MO_REL32_HI, "amdgpu-rel32-hi"},
11017 {MO_REL64, "amdgpu-rel64"},
11018 {MO_ABS32_LO, "amdgpu-abs32-lo"},
11019 {MO_ABS32_HI, "amdgpu-abs32-hi"},
11020 {MO_ABS64, "amdgpu-abs64"},
11021 };
11022
11023 return ArrayRef(TargetFlags);
11024}
11025
11028 static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
11029 {
11030 {MONoClobber, "amdgpu-noclobber"},
11031 {MOLastUse, "amdgpu-last-use"},
11032 {MOCooperative, "amdgpu-cooperative"},
11033 {MOThreadPrivate, "amdgpu-thread-private"},
11034 {MOCFSB0, "amdgpu-cfs0"},
11035 {MOCFSB1, "amdgpu-cfs1"},
11036 };
11037
11038 return ArrayRef(TargetFlags);
11039}
11040
11042 const MachineFunction &MF) const {
11044 assert(SrcReg.isVirtual());
11045 if (MFI->checkFlag(SrcReg, AMDGPU::VirtRegFlag::WWM_REG))
11046 return AMDGPU::WWM_COPY;
11047
11048 return AMDGPU::COPY;
11049}
11050
11052 uint32_t Opcode = MI.getOpcode();
11053 // Check if it is SGPR spill or wwm-register spill Opcode.
11054 if (isSGPRSpill(Opcode) || isWWMRegSpillOpcode(Opcode))
11055 return true;
11056
11057 const MachineFunction *MF = MI.getMF();
11058 const MachineRegisterInfo &MRI = MF->getRegInfo();
11060
11061 // See if this is Liverange split instruction inserted for SGPR or
11062 // wwm-register. The implicit def inserted for wwm-registers should also be
11063 // included as they can appear at the bb begin.
11064 bool IsLRSplitInst = MI.getFlag(MachineInstr::LRSplit);
11065 if (!IsLRSplitInst && Opcode != AMDGPU::IMPLICIT_DEF)
11066 return false;
11067
11068 Register Reg = MI.getOperand(0).getReg();
11069 if (RI.isSGPRClass(RI.getRegClassForReg(MRI, Reg)))
11070 return IsLRSplitInst;
11071
11072 return MFI->isWWMReg(Reg);
11073}
11074
11076 Register Reg) const {
11077 // We need to handle instructions which may be inserted during register
11078 // allocation to handle the prolog. The initial prolog instruction may have
11079 // been separated from the start of the block by spills and copies inserted
11080 // needed by the prolog. However, the insertions for scalar registers can
11081 // always be placed at the BB top as they are independent of the exec mask
11082 // value.
11083 bool IsNullOrVectorRegister = true;
11084 if (Reg) {
11085 const MachineFunction *MF = MI.getMF();
11086 const MachineRegisterInfo &MRI = MF->getRegInfo();
11087 IsNullOrVectorRegister = !RI.isSGPRClass(RI.getRegClassForReg(MRI, Reg));
11088 }
11089
11090 return IsNullOrVectorRegister &&
11091 (canAddToBBProlog(MI) ||
11092 (!MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
11093 MI.modifiesRegister(AMDGPU::EXEC, &RI)));
11094}
11095
11099 const DebugLoc &DL,
11100 Register DestReg) const {
11101 if (ST.hasAddNoCarryInsts())
11102 return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
11103
11104 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
11105 Register UnusedCarry = MRI.createVirtualRegister(RI.getBoolRC());
11106 MRI.setRegAllocationHint(UnusedCarry, 0, RI.getVCC());
11107
11108 return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
11109 .addReg(UnusedCarry, RegState::Define | RegState::Dead);
11110}
11111
11114 const DebugLoc &DL,
11115 Register DestReg,
11116 RegScavenger &RS) const {
11117 if (ST.hasAddNoCarryInsts())
11118 return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e32), DestReg);
11119
11120 // If available, prefer to use vcc.
11121 Register UnusedCarry = !RS.isRegUsed(AMDGPU::VCC)
11122 ? Register(RI.getVCC())
11123 : RS.scavengeRegisterBackwards(
11124 *RI.getBoolRC(), I, /* RestoreAfter */ false,
11125 0, /* AllowSpill */ false);
11126
11127 // TODO: Users need to deal with this.
11128 if (!UnusedCarry.isValid())
11129 return MachineInstrBuilder();
11130
11131 return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
11132 .addReg(UnusedCarry, RegState::Define | RegState::Dead);
11133}
11134
11135bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
11136 switch (Opcode) {
11137 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
11138 case AMDGPU::SI_KILL_I1_TERMINATOR:
11139 return true;
11140 default:
11141 return false;
11142 }
11143}
11144
11146 switch (Opcode) {
11147 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
11148 return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
11149 case AMDGPU::SI_KILL_I1_PSEUDO:
11150 return get(AMDGPU::SI_KILL_I1_TERMINATOR);
11151 default:
11152 llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
11153 }
11154}
11155
11157 return Imm <= getMaxMUBUFImmOffset(ST);
11158}
11159
11161 // GFX12 field is non-negative 24-bit signed byte offset.
11162 const unsigned OffsetBits =
11163 ST.getGeneration() >= AMDGPUSubtarget::GFX12 ? 23 : 12;
11164 return (1 << OffsetBits) - 1;
11165}
11166
11168 if (!ST.isWave32())
11169 return;
11170
11171 if (MI.isInlineAsm())
11172 return;
11173
11174 if (MI.getNumOperands() < MI.getDesc().getNumOperands())
11175 return;
11176
11177 for (auto &Op : MI.implicit_operands()) {
11178 if (Op.isReg() && Op.getReg() == AMDGPU::VCC)
11179 Op.setReg(AMDGPU::VCC_LO);
11180 }
11181}
11182
11184 if (!isSMRD(MI))
11185 return false;
11186
11187 // Check that it is using a buffer resource.
11188 int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
11189 if (Idx == -1) // e.g. s_memtime
11190 return false;
11191
11192 const int16_t RCID = getOpRegClassID(MI.getDesc().operands()[Idx]);
11193 return RI.getRegClass(RCID)->hasSubClassEq(&AMDGPU::SGPR_128RegClass);
11194}
11195
11196// Given Imm, split it into the values to put into the SOffset and ImmOffset
11197// fields in an MUBUF instruction. Return false if it is not possible (due to a
11198// hardware bug needing a workaround).
11199//
11200// The required alignment ensures that individual address components remain
11201// aligned if they are aligned to begin with. It also ensures that additional
11202// offsets within the given alignment can be added to the resulting ImmOffset.
11204 uint32_t &ImmOffset, Align Alignment) const {
11205 const uint64_t MaxOffset = SIInstrInfo::getMaxMUBUFImmOffset(ST);
11206 const uint32_t MaxImm = alignDown(MaxOffset, Alignment.value());
11207 uint32_t Overflow = 0;
11208
11209 if (Imm > MaxImm) {
11210 if (Imm <= MaxImm + 64) {
11211 // Use an SOffset inline constant for 4..64
11212 Overflow = Imm - MaxImm;
11213 Imm = MaxImm;
11214 } else {
11215 // Try to keep the same value in SOffset for adjacent loads, so that
11216 // the corresponding register contents can be re-used.
11217 //
11218 // Load values with all low-bits (except for alignment bits) set into
11219 // SOffset, so that a larger range of values can be covered using
11220 // s_movk_i32.
11221 //
11222 // Atomic operations fail to work correctly when individual address
11223 // components are unaligned, even if their sum is aligned.
11224 uint32_t High = (Imm + Alignment.value()) & ~MaxOffset;
11225 uint32_t Low = (Imm + Alignment.value()) & MaxOffset;
11226 Imm = Low;
11227 Overflow = High - Alignment.value();
11228 }
11229 }
11230
11231 if (Overflow > 0) {
11232 // There is a hardware bug in SI and CI which prevents address clamping in
11233 // MUBUF instructions from working correctly with SOffsets. The immediate
11234 // offset is unaffected.
11235 if (ST.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS)
11236 return false;
11237
11238 // It is not possible to set immediate in SOffset field on some targets.
11239 if (ST.hasRestrictedSOffset())
11240 return false;
11241 }
11242
11243 ImmOffset = Imm;
11244 SOffset = Overflow;
11245 return true;
11246}
11247
11248// Depending on the used address space and instructions, some immediate offsets
11249// are allowed and some are not.
11250// Pre-GFX12, flat instruction offsets can only be non-negative, global and
11251// scratch instruction offsets can also be negative. On GFX12, offsets can be
11252// negative for all variants.
11253//
11254// There are several bugs related to these offsets:
11255// On gfx10.1, flat instructions that go into the global address space cannot
11256// use an offset.
11257//
11258// For scratch instructions, the address can be either an SGPR or a VGPR.
11259// The following offsets can be used, depending on the architecture (x means
11260// cannot be used):
11261// +----------------------------+------+------+
11262// | Address-Mode | SGPR | VGPR |
11263// +----------------------------+------+------+
11264// | gfx9 | | |
11265// | negative, 4-aligned offset | x | ok |
11266// | negative, unaligned offset | x | ok |
11267// +----------------------------+------+------+
11268// | gfx10 | | |
11269// | negative, 4-aligned offset | ok | ok |
11270// | negative, unaligned offset | ok | x |
11271// +----------------------------+------+------+
11272// | gfx10.3 | | |
11273// | negative, 4-aligned offset | ok | ok |
11274// | negative, unaligned offset | ok | ok |
11275// +----------------------------+------+------+
11276//
11277// This function ignores the addressing mode, so if an offset cannot be used in
11278// one addressing mode, it is considered illegal.
11279bool SIInstrInfo::isLegalFLATOffset(int64_t Offset, unsigned AddrSpace,
11280 AMDGPU::FlatAddrSpace FlatVariant) const {
11281 // TODO: Should 0 be special cased?
11282 if (!ST.hasFlatInstOffsets())
11283 return false;
11284
11286 if (ST.hasFlatSegmentOffsetBug() && FlatVariant == FlatAddrSpace::FLAT &&
11287 (AddrSpace == AMDGPUAS::FLAT_ADDRESS ||
11289 return false;
11290
11291 if (ST.hasNegativeUnalignedScratchOffsetBug() &&
11292 FlatVariant == FlatAddrSpace::FlatScratch && Offset < 0 &&
11293 (Offset % 4) != 0) {
11294 return false;
11295 }
11296
11297 bool AllowNegative = allowNegativeFlatOffset(FlatVariant);
11298 unsigned N = AMDGPU::getNumFlatOffsetBits(ST);
11299 return isIntN(N, Offset) && (AllowNegative || Offset >= 0);
11300}
11301
11302// See comment on SIInstrInfo::isLegalFLATOffset for what is legal and what not.
11303std::pair<int64_t, int64_t>
11304SIInstrInfo::splitFlatOffset(int64_t COffsetVal, unsigned AddrSpace,
11305 AMDGPU::FlatAddrSpace FlatVariant) const {
11306 int64_t RemainderOffset = COffsetVal;
11307 int64_t ImmField = 0;
11308
11309 bool AllowNegative = allowNegativeFlatOffset(FlatVariant);
11310 const unsigned NumBits = AMDGPU::getNumFlatOffsetBits(ST) - 1;
11311
11312 if (AllowNegative) {
11313 // Use signed division by a power of two to truncate towards 0.
11314 int64_t D = 1LL << NumBits;
11315 RemainderOffset = (COffsetVal / D) * D;
11316 ImmField = COffsetVal - RemainderOffset;
11317
11318 if (ST.hasNegativeUnalignedScratchOffsetBug() &&
11319 FlatVariant == AMDGPU::FlatAddrSpace::FlatScratch && ImmField < 0 &&
11320 (ImmField % 4) != 0) {
11321 // Make ImmField a multiple of 4
11322 RemainderOffset += ImmField % 4;
11323 ImmField -= ImmField % 4;
11324 }
11325 } else if (COffsetVal >= 0) {
11326 ImmField = COffsetVal & maskTrailingOnes<uint64_t>(NumBits);
11327 RemainderOffset = COffsetVal - ImmField;
11328 }
11329
11330 assert(isLegalFLATOffset(ImmField, AddrSpace, FlatVariant));
11331 assert(RemainderOffset + ImmField == COffsetVal);
11332 return {ImmField, RemainderOffset};
11333}
11334
11336 AMDGPU::FlatAddrSpace FlatVariant) const {
11337 if (ST.hasNegativeScratchOffsetBug() &&
11339 return false;
11340
11341 return FlatVariant != AMDGPU::FlatAddrSpace::FLAT || AMDGPU::isGFX12Plus(ST);
11342}
11343
11344static unsigned subtargetEncodingFamily(const GCNSubtarget &ST) {
11345 switch (ST.getGeneration()) {
11346 default:
11347 break;
11350 return SIEncodingFamily::SI;
11352 // The GFX80 encoding family only contains buffer instructions with unpacked
11353 // D16 data; pseudoToMCOpcode falls back on VI for everything else.
11354 // TODO: remove this when we discard GFX80 encoding.
11355 return ST.hasUnpackedD16VMem() ? SIEncodingFamily::GFX80
11358 return SIEncodingFamily::VI;
11362 return ST.hasGFX11_7Insts() ? SIEncodingFamily::GFX1170
11365 return ST.hasGFX1250Insts() ? SIEncodingFamily::GFX1250
11369 }
11370 llvm_unreachable("Unknown subtarget generation!");
11371}
11372
11373bool SIInstrInfo::isAsmOnlyOpcode(int MCOp) const {
11374 switch(MCOp) {
11375 // These opcodes use indirect register addressing so
11376 // they need special handling by codegen (currently missing).
11377 // Therefore it is too risky to allow these opcodes
11378 // to be selected by dpp combiner or sdwa peepholer.
11379 case AMDGPU::V_MOVRELS_B32_dpp_gfx10:
11380 case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
11381 case AMDGPU::V_MOVRELD_B32_dpp_gfx10:
11382 case AMDGPU::V_MOVRELD_B32_sdwa_gfx10:
11383 case AMDGPU::V_MOVRELSD_B32_dpp_gfx10:
11384 case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
11385 case AMDGPU::V_MOVRELSD_2_B32_dpp_gfx10:
11386 case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
11387 return true;
11388 default:
11389 return false;
11390 }
11391}
11392
11393#define GENERATE_RENAMED_GFX9_CASES(OPCODE) \
11394 case OPCODE##_dpp: \
11395 case OPCODE##_e32: \
11396 case OPCODE##_e64:
11397
11398static bool isRenamedInGFX9(int Opcode) {
11399 switch (Opcode) {
11400 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_ADDC_U32)
11401 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_ADD_CO_U32)
11402 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_ADD_U32)
11403 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUBBREV_U32)
11404 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUBB_U32)
11405 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUBREV_CO_U32)
11406 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUBREV_U32)
11407 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUB_CO_U32)
11408 GENERATE_RENAMED_GFX9_CASES(AMDGPU::V_SUB_U32)
11409 case AMDGPU::V_DIV_FIXUP_F16_gfx9_e64:
11410 case AMDGPU::V_FMA_F16_gfx9_e64:
11411 case AMDGPU::V_INTERP_P2_F16:
11412 case AMDGPU::V_MAD_F16_e64:
11413 case AMDGPU::V_MAD_U16_e64:
11414 case AMDGPU::V_MAD_I16_e64:
11415 case AMDGPU::V_MAD_U16_gfx9_e64:
11416 case AMDGPU::V_MAD_I16_gfx9_e64:
11417 return true;
11418 default:
11419 return false;
11420 }
11421}
11422
11423int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
11424 assert(Opcode == (int)SIInstrInfo::getNonSoftWaitcntOpcode(Opcode) &&
11425 "SIInsertWaitcnts should have promoted soft waitcnt instructions!");
11426
11427 unsigned Gen = subtargetEncodingFamily(ST);
11428
11429 if (ST.getGeneration() == AMDGPUSubtarget::GFX9 && isRenamedInGFX9(Opcode))
11431
11432 if (SIInstrFlags::isSDWA(get(Opcode))) {
11433 switch (ST.getGeneration()) {
11434 default:
11436 break;
11439 break;
11442 break;
11443 }
11444 }
11445
11446 if (isMAI(Opcode)) {
11447 int MFMAOp = AMDGPU::getMFMAEarlyClobberOp(Opcode);
11448 if (MFMAOp != -1)
11449 Opcode = MFMAOp;
11450 }
11451
11452 // All export pseudos share the same real instructions.
11453 if (Opcode == AMDGPU::EXP_DONE || Opcode == AMDGPU::EXP_ROW ||
11454 Opcode == AMDGPU::EXP_ROW_DONE)
11455 Opcode = AMDGPU::EXP;
11456
11457 int32_t MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
11458
11459 // Only buffer instructions with unpacked D16 data have a GFX80 encoding.
11460 // Anything else on such a subtarget uses the plain VI encoding.
11461 // TODO: remove this when we discard GFX80 encoding.
11462 if (MCOp == AMDGPU::INSTRUCTION_LIST_END && Gen == SIEncodingFamily::GFX80)
11464
11465 if (MCOp == AMDGPU::INSTRUCTION_LIST_END && ST.hasGFX11_7Insts())
11467
11468 if (MCOp == AMDGPU::INSTRUCTION_LIST_END && ST.hasGFX1250Insts())
11470
11471 // -1 means that Opcode is already a native instruction.
11472 if (MCOp == -1)
11473 return Opcode;
11474
11475 if (ST.hasGFX90AInsts()) {
11476 uint32_t NMCOp = AMDGPU::INSTRUCTION_LIST_END;
11477 if (ST.hasGFX940Insts())
11479 if (NMCOp == AMDGPU::INSTRUCTION_LIST_END)
11481 if (NMCOp == AMDGPU::INSTRUCTION_LIST_END)
11483 if (NMCOp != AMDGPU::INSTRUCTION_LIST_END)
11484 MCOp = NMCOp;
11485 }
11486
11487 // INSTRUCTION_LIST_END means that Opcode is a pseudo instruction that has no
11488 // encoding in the given subtarget generation.
11489 if (MCOp == AMDGPU::INSTRUCTION_LIST_END)
11490 return -1;
11491
11492 if (isAsmOnlyOpcode(MCOp))
11493 return -1;
11494
11495 return MCOp;
11496}
11497
11498static
11500 assert(RegOpnd.isReg());
11501 return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
11502 getRegSubRegPair(RegOpnd);
11503}
11504
11507 assert(MI.isRegSequence());
11508 for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
11509 if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
11510 auto &RegOp = MI.getOperand(1 + 2 * I);
11511 return getRegOrUndef(RegOp);
11512 }
11514}
11515
11516// Try to find the definition of reg:subreg in subreg-manipulation pseudos
11517// Following a subreg of reg:subreg isn't supported
11520 if (!RSR.SubReg)
11521 return false;
11522 switch (MI.getOpcode()) {
11523 default: break;
11524 case AMDGPU::REG_SEQUENCE:
11525 RSR = getRegSequenceSubReg(MI, RSR.SubReg);
11526 return true;
11527 // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
11528 case AMDGPU::INSERT_SUBREG:
11529 if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
11530 // inserted the subreg we're looking for
11531 RSR = getRegOrUndef(MI.getOperand(2));
11532 else { // the subreg in the rest of the reg
11533 auto R1 = getRegOrUndef(MI.getOperand(1));
11534 if (R1.SubReg) // subreg of subreg isn't supported
11535 return false;
11536 RSR.Reg = R1.Reg;
11537 }
11538 return true;
11539 }
11540 return false;
11541}
11542
11544 const MachineRegisterInfo &MRI) {
11545 assert(MRI.isSSA());
11546 if (!P.Reg.isVirtual())
11547 return nullptr;
11548
11549 auto RSR = P;
11550 auto *DefInst = MRI.getVRegDef(RSR.Reg);
11551 while (auto *MI = DefInst) {
11552 DefInst = nullptr;
11553 switch (MI->getOpcode()) {
11554 case AMDGPU::COPY:
11555 case AMDGPU::V_MOV_B32_e32: {
11556 auto &Op1 = MI->getOperand(1);
11557 if (Op1.isReg() && Op1.getReg().isVirtual()) {
11558 if (Op1.isUndef())
11559 return nullptr;
11560 RSR = getRegSubRegPair(Op1);
11561 DefInst = MRI.getVRegDef(RSR.Reg);
11562 }
11563 break;
11564 }
11565 default:
11566 if (followSubRegDef(*MI, RSR)) {
11567 if (!RSR.Reg)
11568 return nullptr;
11569 DefInst = MRI.getVRegDef(RSR.Reg);
11570 }
11571 }
11572 if (!DefInst)
11573 return MI;
11574 }
11575 return nullptr;
11576}
11577
11579 Register VReg,
11580 const MachineInstr &DefMI,
11581 const MachineInstr &UseMI) {
11582 assert(MRI.isSSA() && "Must be run on SSA");
11583
11584 auto *TRI = MRI.getTargetRegisterInfo();
11585 auto *DefBB = DefMI.getParent();
11586
11587 // Don't bother searching between blocks, although it is possible this block
11588 // doesn't modify exec.
11589 if (UseMI.getParent() != DefBB)
11590 return true;
11591
11592 const int MaxInstScan = 20;
11593 int NumInst = 0;
11594
11595 // Stop scan at the use.
11596 auto E = UseMI.getIterator();
11597 for (auto I = std::next(DefMI.getIterator()); I != E; ++I) {
11598 if (I->isDebugInstr())
11599 continue;
11600
11601 if (++NumInst > MaxInstScan)
11602 return true;
11603
11604 if (I->modifiesRegister(AMDGPU::EXEC, TRI))
11605 return true;
11606 }
11607
11608 return false;
11609}
11610
11612 Register VReg,
11613 const MachineInstr &DefMI) {
11614 assert(MRI.isSSA() && "Must be run on SSA");
11615
11616 auto *TRI = MRI.getTargetRegisterInfo();
11617 auto *DefBB = DefMI.getParent();
11618
11619 const int MaxUseScan = 10;
11620 int NumUse = 0;
11621
11622 for (auto &Use : MRI.use_nodbg_operands(VReg)) {
11623 auto &UseInst = *Use.getParent();
11624 // Don't bother searching between blocks, although it is possible this block
11625 // doesn't modify exec.
11626 if (UseInst.getParent() != DefBB || UseInst.isPHI())
11627 return true;
11628
11629 if (++NumUse > MaxUseScan)
11630 return true;
11631 }
11632
11633 if (NumUse == 0)
11634 return false;
11635
11636 const int MaxInstScan = 20;
11637 int NumInst = 0;
11638
11639 // Stop scan when we have seen all the uses.
11640 for (auto I = std::next(DefMI.getIterator()); ; ++I) {
11641 assert(I != DefBB->end());
11642
11643 if (I->isDebugInstr())
11644 continue;
11645
11646 if (++NumInst > MaxInstScan)
11647 return true;
11648
11649 for (const MachineOperand &Op : I->operands()) {
11650 // We don't check reg masks here as they're used only on calls:
11651 // 1. EXEC is only considered const within one BB
11652 // 2. Call should be a terminator instruction if present in a BB
11653
11654 if (!Op.isReg())
11655 continue;
11656
11657 Register Reg = Op.getReg();
11658 if (Op.isUse()) {
11659 if (Reg == VReg && --NumUse == 0)
11660 return false;
11661 } else if (TRI->regsOverlap(Reg, AMDGPU::EXEC))
11662 return true;
11663 }
11664 }
11665}
11666
11669 const DebugLoc &DL, Register Src, Register Dst) const {
11670 auto Cur = MBB.begin();
11671 if (Cur != MBB.end())
11672 do {
11673 if (!Cur->isPHI() && Cur->readsRegister(Dst, /*TRI=*/nullptr))
11674 return BuildMI(MBB, Cur, DL, get(TargetOpcode::COPY), Dst).addReg(Src);
11675 ++Cur;
11676 } while (Cur != MBB.end() && Cur != LastPHIIt);
11677
11678 return TargetInstrInfo::createPHIDestinationCopy(MBB, LastPHIIt, DL, Src,
11679 Dst);
11680}
11681
11684 const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const {
11685 if (InsPt != MBB.end() &&
11686 (InsPt->getOpcode() == AMDGPU::SI_IF ||
11687 InsPt->getOpcode() == AMDGPU::SI_ELSE ||
11688 InsPt->getOpcode() == AMDGPU::SI_IF_BREAK) &&
11689 InsPt->definesRegister(Src, /*TRI=*/nullptr)) {
11690 InsPt++;
11691 return BuildMI(MBB, InsPt, DL,
11692 get(AMDGPU::LaneMaskConstants::get(ST).MovTermOpc), Dst)
11693 .addReg(Src, {}, SrcSubReg)
11694 .addReg(AMDGPU::EXEC, RegState::Implicit);
11695 }
11696 return TargetInstrInfo::createPHISourceCopy(MBB, InsPt, DL, Src, SrcSubReg,
11697 Dst);
11698}
11699
11700bool llvm::SIInstrInfo::isWave32() const { return ST.isWave32(); }
11701
11703 const MachineInstr &SecondMI) const {
11704 for (const auto &Use : SecondMI.all_uses()) {
11705 if (Use.isReg() && FirstMI.modifiesRegister(Use.getReg(), &RI))
11706 return true;
11707 }
11708 return false;
11709}
11710
11711/// If OpX is multicycle, anti-dependencies are not allowed.
11712/// isDPMACCInstruction was not designed for VOPD, but it is fit for the
11713/// purpose.
11715 const MachineInstr &OpX) const {
11717}
11718
11721 ArrayRef<unsigned> Ops, int FrameIndex,
11722 MachineInstr *&CopyMI, LiveIntervals *LIS,
11723 VirtRegMap *VRM) const {
11724 // This is a bit of a hack (copied from AArch64). Consider this instruction:
11725 //
11726 // %0:sreg_32 = COPY $m0
11727 //
11728 // We explicitly chose SReg_32 for the virtual register so such a copy might
11729 // be eliminated by RegisterCoalescer. However, that may not be possible, and
11730 // %0 may even spill. We can't spill $m0 normally (it would require copying to
11731 // a numbered SGPR anyway), and since it is in the SReg_32 register class,
11732 // TargetInstrInfo::foldMemoryOperand() is going to try.
11733 // A similar issue also exists with spilling and reloading $exec registers.
11734 //
11735 // To prevent that, constrain the %0 register class here.
11736 if (isFullCopyInstr(MI)) {
11737 Register DstReg = MI.getOperand(0).getReg();
11738 Register SrcReg = MI.getOperand(1).getReg();
11739 if ((DstReg.isVirtual() || SrcReg.isVirtual()) &&
11740 (DstReg.isVirtual() != SrcReg.isVirtual())) {
11742 Register VirtReg = DstReg.isVirtual() ? DstReg : SrcReg;
11743 const TargetRegisterClass *RC = MRI.getRegClass(VirtReg);
11744 if (RC->hasSuperClassEq(&AMDGPU::SReg_32RegClass)) {
11745 MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
11746 return nullptr;
11747 }
11748 if (RC->hasSuperClassEq(&AMDGPU::SReg_64RegClass)) {
11749 MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_64_XEXECRegClass);
11750 return nullptr;
11751 }
11752 }
11753 }
11754
11755 return nullptr;
11756}
11757
11759 const MachineInstr &MI,
11760 unsigned *PredCost) const {
11761 if (MI.isBundle()) {
11763 MachineBasicBlock::const_instr_iterator E(MI.getParent()->instr_end());
11764 unsigned Lat = 0, Count = 0;
11765 for (++I; I != E && I->isBundledWithPred(); ++I) {
11766 if (I->isMetaInstruction())
11767 continue;
11768 ++Count;
11769 Lat = std::max(Lat, SchedModel.computeInstrLatency(&*I));
11770 }
11771 return Lat + Count - 1;
11772 }
11773
11774 return SchedModel.computeInstrLatency(&MI);
11775}
11776
11778 if (!ST.hasGFX1250VALUBlockingCycles())
11779 return 0;
11781}
11782
11783unsigned
11785 if (const auto *Entry = AMDGPU::getGFX1250BlockingCyclesInfo(MI.getOpcode()))
11786 return Entry->GFX1250BlockingCycles;
11787 return 0;
11788}
11789
11790const MachineOperand &
11792 if (const MachineOperand *CallAddrOp =
11793 getNamedOperand(MI, AMDGPU::OpName::src0))
11794 return *CallAddrOp;
11796}
11797
11800 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11801 unsigned Opcode = MI.getOpcode();
11802
11803 auto HandleAddrSpaceCast = [this, &MRI](const MachineInstr &MI) {
11804 Register Dst = MI.getOperand(0).getReg();
11805 Register Src = MI.getOperand(1).getReg();
11806 LLT DstTy = MRI.getType(Dst);
11807 LLT SrcTy = MRI.getType(Src);
11808 unsigned DstAS = DstTy.getAddressSpace();
11809 unsigned SrcAS = SrcTy.getAddressSpace();
11810 return SrcAS == AMDGPUAS::PRIVATE_ADDRESS &&
11811 DstAS == AMDGPUAS::FLAT_ADDRESS &&
11812 ST.hasGloballyAddressableScratch()
11815 };
11816
11817 // If the target supports globally addressable scratch, the mapping from
11818 // scratch memory to the flat aperture changes therefore an address space cast
11819 // is no longer uniform.
11820 if (Opcode == TargetOpcode::G_ADDRSPACE_CAST)
11821 return HandleAddrSpaceCast(MI);
11822
11823 if (auto *GI = dyn_cast<GIntrinsic>(&MI)) {
11824 auto IID = GI->getIntrinsicID();
11829
11830 switch (IID) {
11831 case Intrinsic::amdgcn_if:
11832 case Intrinsic::amdgcn_else:
11833 // FIXME: Uniform if second result
11834 break;
11835 }
11836
11838 }
11839
11840 // Each lane reads its own registers, however uniform the index.
11841 if (Opcode == AMDGPU::G_AMDGPU_REG_LOAD)
11843
11844 // Loads from the private and flat address spaces are divergent, because
11845 // threads can execute the load instruction with the same inputs and get
11846 // different results. So are VGPR address space loads, before they become
11847 // G_AMDGPU_REG_LOAD.
11848 //
11849 // All other loads are not divergent, because if threads issue loads with the
11850 // same arguments, they will always get the same result.
11851 if (Opcode == AMDGPU::G_LOAD || Opcode == AMDGPU::G_ZEXTLOAD ||
11852 Opcode == AMDGPU::G_SEXTLOAD) {
11853 if (MI.memoperands_empty())
11854 return ValueUniformity::NeverUniform; // conservative assumption
11855
11856 if (llvm::any_of(MI.memoperands(), [](const MachineMemOperand *mmo) {
11857 return mmo->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
11858 mmo->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS ||
11859 mmo->getAddrSpace() == AMDGPUAS::VGPR;
11860 })) {
11861 // At least one MMO in a non-global address space.
11863 }
11865 }
11866
11867 if (SIInstrInfo::isGenericAtomicRMWOpcode(Opcode) ||
11868 Opcode == AMDGPU::G_ATOMIC_CMPXCHG ||
11869 Opcode == AMDGPU::G_ATOMIC_CMPXCHG_WITH_SUCCESS ||
11870 AMDGPU::isGenericAtomic(Opcode)) {
11872 }
11873
11874 // Result is computed from uniform SP and uniform wave-wide max size.
11875 if (Opcode == TargetOpcode::G_DYN_STACKALLOC)
11877
11878 if (Opcode == AMDGPU::G_AMDGPU_WHOLE_WAVE_FUNC_SETUP)
11880
11882}
11883
11885 if (!Formatter)
11886 Formatter = std::make_unique<AMDGPUMIRFormatter>(ST);
11887 return Formatter.get();
11888}
11889
11891
11892 if (isNeverUniform(MI))
11894
11895 unsigned opcode = MI.getOpcode();
11896 if (opcode == AMDGPU::V_READLANE_B32 ||
11897 opcode == AMDGPU::V_READFIRSTLANE_B32 ||
11898 opcode == AMDGPU::SI_RESTORE_S32_FROM_VGPR)
11900
11901 // If any of defs is divergent, report as NeverUniform. isUniformReg will
11902 // calculate in more detail for each def from its reg class, if available.
11903 if (MI.isInlineAsm()) {
11904 for (const MachineOperand &MO : MI.operands()) {
11905 if (!MO.isReg() || !MO.isDef())
11906 continue;
11907 const TargetRegisterClass *RC =
11908 MI.getRegClassConstraint(MO.getOperandNo(), this, &RI);
11909 if (!RC || !RI.isSGPRClass(RC))
11911 }
11912 }
11913
11914 if (isCopyInstr(MI)) {
11915 const MachineOperand &srcOp = MI.getOperand(1);
11916 if (srcOp.isReg() && srcOp.getReg().isPhysical()) {
11917 const TargetRegisterClass *regClass =
11918 RI.getPhysRegBaseClass(srcOp.getReg());
11919 return RI.isSGPRClass(regClass) ? ValueUniformity::AlwaysUniform
11921 }
11923 }
11924
11925 // GMIR handling
11926 if (MI.isPreISelOpcode())
11928
11929 // Atomics are divergent because they are executed sequentially: when an
11930 // atomic operation refers to the same address in each thread, then each
11931 // thread after the first sees the value written by the previous thread as
11932 // original value.
11933
11934 if (isAtomic(MI))
11936
11937 // Loads from the private and flat address spaces are divergent, because
11938 // threads can execute the load instruction with the same inputs and get
11939 // different results.
11940 if (isFLAT(MI) && MI.mayLoad()) {
11941 if (MI.memoperands_empty())
11942 return ValueUniformity::NeverUniform; // conservative assumption
11943
11944 if (llvm::any_of(MI.memoperands(), [](const MachineMemOperand *mmo) {
11945 return mmo->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
11946 mmo->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS;
11947 })) {
11948 // At least one MMO in a non-global address space.
11950 }
11951
11953 }
11954
11955 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11956 const AMDGPURegisterBankInfo *RBI = ST.getRegBankInfo();
11957
11958 // FIXME: It's conceptually broken to report this for an instruction, and not
11959 // a specific def operand. For inline asm in particular, there could be mixed
11960 // uniform and divergent results.
11961 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
11962 const MachineOperand &SrcOp = MI.getOperand(I);
11963 if (!SrcOp.isReg())
11964 continue;
11965
11966 Register Reg = SrcOp.getReg();
11967 if (!Reg || !SrcOp.readsReg())
11968 continue;
11969
11970 // If RegBank is null, this is unassigned or an unallocatable special
11971 // register, which are all scalars.
11972 const RegisterBank *RegBank = RBI->getRegBank(Reg, MRI, RI);
11973 if (RegBank && RegBank->getID() != AMDGPU::SGPRRegBankID)
11975 }
11976
11977 // TODO: Uniformity check condtions above can be rearranged for more
11978 // redability
11979
11980 // TODO: amdgcn.{ballot, [if]cmp} should be AlwaysUniform, but they are
11981 // currently turned into no-op COPYs by SelectionDAG ISel and are
11982 // therefore no longer recognizable.
11983
11985}
11986
11988 switch (MF.getFunction().getCallingConv()) {
11990 return 1;
11992 return 2;
11994 return 3;
11998 const Function &F = MF.getFunction();
11999 F.getContext().diagnose(DiagnosticInfoUnsupported(
12000 F, "ds_ordered_count unsupported for this calling conv"));
12001 [[fallthrough]];
12002 }
12005 case CallingConv::C:
12006 case CallingConv::Fast:
12007 default:
12008 // Assume other calling conventions are various compute callable functions
12009 return 0;
12010 }
12011}
12012
12014 Register &SrcReg2, int64_t &CmpMask,
12015 int64_t &CmpValue) const {
12016 if (!MI.getOperand(0).isReg() || MI.getOperand(0).getSubReg())
12017 return false;
12018
12019 switch (MI.getOpcode()) {
12020 default:
12021 break;
12022 case AMDGPU::S_CMP_EQ_U32:
12023 case AMDGPU::S_CMP_EQ_I32:
12024 case AMDGPU::S_CMP_LG_U32:
12025 case AMDGPU::S_CMP_LG_I32:
12026 case AMDGPU::S_CMP_LT_U32:
12027 case AMDGPU::S_CMP_LT_I32:
12028 case AMDGPU::S_CMP_GT_U32:
12029 case AMDGPU::S_CMP_GT_I32:
12030 case AMDGPU::S_CMP_LE_U32:
12031 case AMDGPU::S_CMP_LE_I32:
12032 case AMDGPU::S_CMP_GE_U32:
12033 case AMDGPU::S_CMP_GE_I32:
12034 case AMDGPU::S_CMP_EQ_U64:
12035 case AMDGPU::S_CMP_LG_U64:
12036 SrcReg = MI.getOperand(0).getReg();
12037 if (MI.getOperand(1).isReg()) {
12038 if (MI.getOperand(1).getSubReg())
12039 return false;
12040 SrcReg2 = MI.getOperand(1).getReg();
12041 CmpValue = 0;
12042 } else if (MI.getOperand(1).isImm()) {
12043 SrcReg2 = Register();
12044 CmpValue = MI.getOperand(1).getImm();
12045 } else {
12046 return false;
12047 }
12048 CmpMask = ~0;
12049 return true;
12050 case AMDGPU::S_CMPK_EQ_U32:
12051 case AMDGPU::S_CMPK_EQ_I32:
12052 case AMDGPU::S_CMPK_LG_U32:
12053 case AMDGPU::S_CMPK_LG_I32:
12054 case AMDGPU::S_CMPK_LT_U32:
12055 case AMDGPU::S_CMPK_LT_I32:
12056 case AMDGPU::S_CMPK_GT_U32:
12057 case AMDGPU::S_CMPK_GT_I32:
12058 case AMDGPU::S_CMPK_LE_U32:
12059 case AMDGPU::S_CMPK_LE_I32:
12060 case AMDGPU::S_CMPK_GE_U32:
12061 case AMDGPU::S_CMPK_GE_I32:
12062 SrcReg = MI.getOperand(0).getReg();
12063 SrcReg2 = Register();
12064 CmpValue = MI.getOperand(1).getImm();
12065 CmpMask = ~0;
12066 return true;
12067 }
12068
12069 return false;
12070}
12071
12073 for (MachineBasicBlock *S : MBB->successors()) {
12074 if (S->isLiveIn(AMDGPU::SCC))
12075 return false;
12076 }
12077 return true;
12078}
12079
12080// Invert all uses of SCC following SCCDef because SCCDef may be deleted and
12081// (incoming SCC) = !(SCC defined by SCCDef).
12082// Return true if all uses can be re-written, false otherwise.
12083bool SIInstrInfo::invertSCCUse(MachineInstr *SCCDef) const {
12084 MachineBasicBlock *MBB = SCCDef->getParent();
12085 SmallVector<MachineInstr *> InvertInstr;
12086 bool SCCIsDead = false;
12087
12088 // Scan instructions for SCC uses that need to be inverted until SCC is dead.
12089 constexpr unsigned ScanLimit = 12;
12090 unsigned Count = 0;
12091 for (MachineInstr &MI : instructionsWithoutDebug(
12092 std::next(MachineBasicBlock::iterator(SCCDef)), MBB->end())) {
12093 if (++Count > ScanLimit)
12094 return false;
12095 if (MI.readsRegister(AMDGPU::SCC, &RI)) {
12096 if (MI.getOpcode() == AMDGPU::S_CSELECT_B32 ||
12097 MI.getOpcode() == AMDGPU::S_CSELECT_B64 ||
12098 MI.getOpcode() == AMDGPU::S_CBRANCH_SCC0 ||
12099 MI.getOpcode() == AMDGPU::S_CBRANCH_SCC1)
12100 InvertInstr.push_back(&MI);
12101 else
12102 return false;
12103 }
12104 if (MI.definesRegister(AMDGPU::SCC, &RI)) {
12105 SCCIsDead = true;
12106 break;
12107 }
12108 }
12109 if (!SCCIsDead && isSCCDeadOnExit(MBB))
12110 SCCIsDead = true;
12111
12112 // SCC may have more uses. Can't invert all of them.
12113 if (!SCCIsDead)
12114 return false;
12115
12116 // Invert uses
12117 for (MachineInstr *MI : InvertInstr) {
12118 if (MI->getOpcode() == AMDGPU::S_CSELECT_B32 ||
12119 MI->getOpcode() == AMDGPU::S_CSELECT_B64) {
12120 swapOperands(*MI);
12121 } else if (MI->getOpcode() == AMDGPU::S_CBRANCH_SCC0 ||
12122 MI->getOpcode() == AMDGPU::S_CBRANCH_SCC1) {
12123 MI->setDesc(get(MI->getOpcode() == AMDGPU::S_CBRANCH_SCC0
12124 ? AMDGPU::S_CBRANCH_SCC1
12125 : AMDGPU::S_CBRANCH_SCC0));
12126 } else {
12127 llvm_unreachable("SCC used but no inversion handling");
12128 }
12129 }
12130 return true;
12131}
12132
12133// SCC is already valid after SCCValid.
12134// SCCRedefine will redefine SCC to the same value already available after
12135// SCCValid. If there are no intervening SCC conflicts delete SCCRedefine and
12136// update kill/dead flags if necessary.
12137bool SIInstrInfo::optimizeSCC(MachineInstr *SCCValid, MachineInstr *SCCRedefine,
12138 bool NeedInversion) const {
12139 MachineInstr *KillsSCC = nullptr;
12140 if (SCCValid->getParent() != SCCRedefine->getParent())
12141 return false;
12142 for (MachineInstr &MI : make_range(std::next(SCCValid->getIterator()),
12143 SCCRedefine->getIterator())) {
12144 if (MI.modifiesRegister(AMDGPU::SCC, &RI))
12145 return false;
12146 if (MI.killsRegister(AMDGPU::SCC, &RI))
12147 KillsSCC = &MI;
12148 }
12149 if (NeedInversion && !invertSCCUse(SCCRedefine))
12150 return false;
12151 if (MachineOperand *SccDef =
12152 SCCValid->findRegisterDefOperand(AMDGPU::SCC, /*TRI=*/nullptr))
12153 SccDef->setIsDead(false);
12154 if (KillsSCC)
12155 KillsSCC->clearRegisterKills(AMDGPU::SCC, /*TRI=*/nullptr);
12156 SCCRedefine->eraseFromParent();
12157 return true;
12158}
12159
12160/// If \p Sel is an S_CSELECT* of two different constants A and B, return them,
12161/// truncated to the width of the select.
12162static std::optional<std::pair<int64_t, int64_t>>
12164 const MachineInstr &Sel) {
12165 unsigned Opc = Sel.getOpcode();
12166 if (Opc != AMDGPU::S_CSELECT_B32 && Opc != AMDGPU::S_CSELECT_B64)
12167 return {};
12168 std::optional<int64_t> A =
12169 TII.getImmOrMaterializedImm(MRI, Sel.getOperand(1));
12170 if (!A)
12171 return {};
12172 std::optional<int64_t> B =
12173 TII.getImmOrMaterializedImm(MRI, Sel.getOperand(2));
12174 if (!B)
12175 return {};
12176 if (Opc == AMDGPU::S_CSELECT_B32) {
12177 A = Lo_32(*A);
12178 B = Lo_32(*B);
12179 }
12180 if (*A == *B)
12181 return {};
12182 return std::pair(*A, *B);
12183}
12184
12185static bool setsSCCIfResultIsZero(const MachineInstr &Def, bool &NeedInversion,
12186 unsigned &NewDefOpc) {
12187 // S_ADD_U32 X, 1 sets SCC on carryout which can only happen if result==0.
12188 // S_ADD_I32 X, 1 can be converted to S_ADD_U32 X, 1 if SCC is dead.
12189 if (Def.getOpcode() != AMDGPU::S_ADD_I32 &&
12190 Def.getOpcode() != AMDGPU::S_ADD_U32)
12191 return false;
12192 const MachineOperand &AddSrc1 = Def.getOperand(1);
12193 const MachineOperand &AddSrc2 = Def.getOperand(2);
12194 const MachineRegisterInfo &MRI = Def.getMF()->getRegInfo();
12195 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
12196 Def.getMF()->getSubtarget().getInstrInfo());
12197
12198 auto Imm1 = TII->getImmOrMaterializedImm(MRI, AddSrc1);
12199 auto Imm2 = TII->getImmOrMaterializedImm(MRI, AddSrc2);
12200 if ((!Imm1 || *Imm1 != 1) && (!Imm2 || *Imm2 != 1))
12201 return false;
12202
12203 if (Def.getOpcode() == AMDGPU::S_ADD_I32) {
12204 const MachineOperand *SccDef =
12205 Def.findRegisterDefOperand(AMDGPU::SCC, /*TRI=*/nullptr);
12206 if (!SccDef->isDead())
12207 return false;
12208 NewDefOpc = AMDGPU::S_ADD_U32;
12209 }
12210 NeedInversion = !NeedInversion;
12211 return true;
12212}
12213
12215 Register SrcReg2, int64_t CmpMask,
12216 int64_t CmpValue,
12217 const MachineRegisterInfo *MRI) const {
12218 if (!SrcReg || SrcReg.isPhysical())
12219 return false;
12220
12221 if (SrcReg2) {
12222 auto ImmOpt = getImmOrMaterializedImm(*MRI, SrcReg2);
12223 if (!ImmOpt)
12224 return false;
12225 CmpValue = *ImmOpt;
12226 }
12227
12228 const auto optimizeCmpSelect = [&CmpInstr, SrcReg, CmpValue, MRI,
12229 this](bool NeedInversion) -> bool {
12230 MachineInstr *Def = MRI->getVRegDef(SrcReg);
12231 if (!Def)
12232 return false;
12233
12234 unsigned NewDefOpc = Def->getOpcode();
12235 if (auto Consts = getSelectConstants(*this, *MRI, *Def)) {
12236 // sX = S_CSELECT* A, B with A != B, so sX == A exactly when SCC was set.
12237 // Comparing sX with A or B recomputes SCC or its inverse:
12238 //
12239 // s_cmp_eq_* sX, A => SCC s_cmp_lg_* sX, A => !SCC
12240 // s_cmp_eq_* sX, B => !SCC s_cmp_lg_* sX, B => SCC
12241 auto [A, B] = *Consts;
12242 int64_t C = Def->getOpcode() == AMDGPU::S_CSELECT_B32 ? Lo_32(CmpValue)
12243 : CmpValue;
12244 if (C == A)
12245 NeedInversion = !NeedInversion;
12246 else if (C != B)
12247 return false;
12248 } else {
12249 // For S_OP that set SCC = DST!=0, do the transformation
12250 //
12251 // s_cmp_[lg|eq]_* (S_OP ...), 0 => (S_OP ...)
12252 //
12253 // For (S_OP ...) that set SCC = DST==0, invert NeedInversion and
12254 // do the transformation:
12255 //
12256 // s_cmp_[lg|eq]_* (S_OP ...), 0 => (S_OP ...)
12257 if (CmpValue != 0 ||
12258 (!setsSCCIfResultIsNonZero(*Def) &&
12259 !setsSCCIfResultIsZero(*Def, NeedInversion, NewDefOpc)))
12260 return false;
12261 }
12262
12263 if (!optimizeSCC(Def, &CmpInstr, NeedInversion))
12264 return false;
12265
12266 if (NewDefOpc != Def->getOpcode())
12267 Def->setDesc(get(NewDefOpc));
12268
12269 // If s_or_b32 result, sY, is unused (i.e. it is effectively a 64-bit
12270 // s_cmp_lg of a register pair) and the inputs are the hi and lo-halves of a
12271 // 64-bit select then delete s_or_b32 in the sequence:
12272 // sX = s_cselect_b64 A, B (A != B, one of them 0)
12273 // sLo = copy sX.sub0
12274 // sHi = copy sX.sub1
12275 // sY = s_or_b32 sLo, sHi
12276 if (Def->getOpcode() == AMDGPU::S_OR_B32 &&
12277 MRI->use_nodbg_empty(Def->getOperand(0).getReg())) {
12278 const MachineOperand &OrOpnd1 = Def->getOperand(1);
12279 const MachineOperand &OrOpnd2 = Def->getOperand(2);
12280 if (OrOpnd1.isReg() && OrOpnd2.isReg()) {
12281 MachineInstr *Def1 = MRI->getVRegDef(OrOpnd1.getReg());
12282 MachineInstr *Def2 = MRI->getVRegDef(OrOpnd2.getReg());
12283 if (Def1 && Def1->getOpcode() == AMDGPU::COPY && Def2 &&
12284 Def2->getOpcode() == AMDGPU::COPY && Def1->getOperand(1).isReg() &&
12285 Def2->getOperand(1).isReg() &&
12286 Def1->getOperand(1).getSubReg() == AMDGPU::sub0 &&
12287 Def2->getOperand(1).getSubReg() == AMDGPU::sub1 &&
12288 Def1->getOperand(1).getReg() == Def2->getOperand(1).getReg()) {
12289 if (MachineInstr *Select =
12290 MRI->getVRegDef(Def1->getOperand(1).getReg())) {
12291 if (auto Consts = getSelectConstants(*this, *MRI, *Select)) {
12292 auto [A, B] = *Consts;
12293 if (A == 0 || B == 0)
12294 optimizeSCC(Select, Def, /*NeedInversion=*/A == 0);
12295 }
12296 }
12297 }
12298 }
12299 }
12300 return true;
12301 };
12302
12303 const auto optimizeCmpAnd = [&CmpInstr, SrcReg, CmpValue, MRI,
12304 this](int64_t ExpectedValue, unsigned SrcSize,
12305 bool IsReversible, bool IsSigned) -> bool {
12306 // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
12307 // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
12308 // s_cmp_ge_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
12309 // s_cmp_ge_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
12310 // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 1 << n => s_and_b64 $src, 1 << n
12311 // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
12312 // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
12313 // s_cmp_gt_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
12314 // s_cmp_gt_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
12315 // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 0 => s_and_b64 $src, 1 << n
12316 //
12317 // Signed ge/gt are not used for the sign bit.
12318 //
12319 // If result of the AND is unused except in the compare:
12320 // s_and_b(32|64) $src, 1 << n => s_bitcmp1_b(32|64) $src, n
12321 //
12322 // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
12323 // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
12324 // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 0 => s_bitcmp0_b64 $src, n
12325 // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
12326 // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
12327 // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 1 << n => s_bitcmp0_b64 $src, n
12328
12329 MachineInstr *Def = MRI->getVRegDef(SrcReg);
12330 if (!Def)
12331 return false;
12332
12333 if (Def->getOpcode() != AMDGPU::S_AND_B32 &&
12334 Def->getOpcode() != AMDGPU::S_AND_B64)
12335 return false;
12336
12337 int64_t Mask;
12338 const auto isMask = [&Mask, SrcSize, MRI,
12339 this](const MachineOperand *MO) -> bool {
12340 auto ImmOpt = this->getImmOrMaterializedImm(*MRI, *MO);
12341 if (!ImmOpt)
12342 return false;
12343 Mask = *ImmOpt;
12344 Mask &= maxUIntN(SrcSize);
12345 return isPowerOf2_64(Mask);
12346 };
12347
12348 MachineOperand *SrcOp = &Def->getOperand(1);
12349 if (isMask(SrcOp))
12350 SrcOp = &Def->getOperand(2);
12351 else if (isMask(&Def->getOperand(2)))
12352 SrcOp = &Def->getOperand(1);
12353 else
12354 return false;
12355
12356 // A valid Mask is required to have a single bit set, hence a non-zero and
12357 // power-of-two value. This verifies that we will not do 64-bit shift below.
12358 assert(llvm::has_single_bit<uint64_t>(Mask) && "Invalid mask.");
12359 unsigned BitNo = llvm::countr_zero((uint64_t)Mask);
12360 if (IsSigned && BitNo == SrcSize - 1)
12361 return false;
12362
12363 ExpectedValue <<= BitNo;
12364
12365 bool IsReversedCC = false;
12366 if (CmpValue != ExpectedValue) {
12367 if (!IsReversible)
12368 return false;
12369 IsReversedCC = CmpValue == (ExpectedValue ^ Mask);
12370 if (!IsReversedCC)
12371 return false;
12372 }
12373
12374 Register DefReg = Def->getOperand(0).getReg();
12375 if (IsReversedCC && !MRI->hasOneNonDBGUse(DefReg))
12376 return false;
12377
12378 if (!optimizeSCC(Def, &CmpInstr, /*NeedInversion=*/false))
12379 return false;
12380
12381 if (!MRI->use_nodbg_empty(DefReg)) {
12382 assert(!IsReversedCC);
12383 return true;
12384 }
12385
12386 // Replace AND with unused result with a S_BITCMP.
12387 MachineBasicBlock *MBB = Def->getParent();
12388
12389 unsigned NewOpc = (SrcSize == 32) ? IsReversedCC ? AMDGPU::S_BITCMP0_B32
12390 : AMDGPU::S_BITCMP1_B32
12391 : IsReversedCC ? AMDGPU::S_BITCMP0_B64
12392 : AMDGPU::S_BITCMP1_B64;
12393
12394 BuildMI(*MBB, Def, Def->getDebugLoc(), get(NewOpc))
12395 .add(*SrcOp)
12396 .addImm(BitNo);
12397 Def->eraseFromParent();
12398
12399 return true;
12400 };
12401
12402 switch (CmpInstr.getOpcode()) {
12403 default:
12404 break;
12405 case AMDGPU::S_CMP_EQ_U32:
12406 case AMDGPU::S_CMP_EQ_I32:
12407 case AMDGPU::S_CMPK_EQ_U32:
12408 case AMDGPU::S_CMPK_EQ_I32:
12409 return optimizeCmpAnd(1, 32, true, false) ||
12410 optimizeCmpSelect(/*NeedInversion=*/true);
12411 case AMDGPU::S_CMP_GE_U32:
12412 case AMDGPU::S_CMPK_GE_U32:
12413 return optimizeCmpAnd(1, 32, false, false);
12414 case AMDGPU::S_CMP_GE_I32:
12415 case AMDGPU::S_CMPK_GE_I32:
12416 return optimizeCmpAnd(1, 32, false, true);
12417 case AMDGPU::S_CMP_EQ_U64:
12418 return optimizeCmpAnd(1, 64, true, false) ||
12419 optimizeCmpSelect(/*NeedInversion=*/true);
12420 case AMDGPU::S_CMP_LG_U32:
12421 case AMDGPU::S_CMP_LG_I32:
12422 case AMDGPU::S_CMPK_LG_U32:
12423 case AMDGPU::S_CMPK_LG_I32:
12424 return optimizeCmpAnd(0, 32, true, false) ||
12425 optimizeCmpSelect(/*NeedInversion=*/false);
12426 case AMDGPU::S_CMP_GT_U32:
12427 case AMDGPU::S_CMPK_GT_U32:
12428 return optimizeCmpAnd(0, 32, false, false);
12429 case AMDGPU::S_CMP_GT_I32:
12430 case AMDGPU::S_CMPK_GT_I32:
12431 return optimizeCmpAnd(0, 32, false, true);
12432 case AMDGPU::S_CMP_LG_U64:
12433 return optimizeCmpAnd(0, 64, true, false) ||
12434 optimizeCmpSelect(/*NeedInversion=*/false);
12435 }
12436
12437 return false;
12438}
12439
12441 AMDGPU::OpName OpName) const {
12442 if (!ST.needsAlignedVGPRs())
12443 return;
12444
12445 int OpNo = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpName);
12446 if (OpNo < 0)
12447 return;
12448 MachineOperand &Op = MI.getOperand(OpNo);
12449 if (getOpSize(MI, OpNo) > 4)
12450 return;
12451
12452 // Add implicit aligned super-reg to force alignment on the data operand.
12453 const DebugLoc &DL = MI.getDebugLoc();
12454 MachineBasicBlock *BB = MI.getParent();
12456 Register DataReg = Op.getReg();
12457 bool IsAGPR = RI.isAGPR(MRI, DataReg);
12458 Register Undef = MRI.createVirtualRegister(
12459 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
12460 BuildMI(*BB, MI, DL, get(AMDGPU::IMPLICIT_DEF), Undef);
12461 Register NewVR =
12462 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
12463 : &AMDGPU::VReg_64_Align2RegClass);
12464 BuildMI(*BB, MI, DL, get(AMDGPU::REG_SEQUENCE), NewVR)
12465 .addReg(DataReg, {}, Op.getSubReg())
12466 .addImm(AMDGPU::sub0)
12467 .addReg(Undef)
12468 .addImm(AMDGPU::sub1);
12469 Op.setReg(NewVR);
12470 Op.setSubReg(AMDGPU::sub0);
12471 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
12472}
12473
12475 if (isIGLP(*MI))
12476 return false;
12477
12479}
12480
12482 if (!isWMMA(MI) && !isSWMMAC(MI))
12483 return false;
12484
12485 if (ST.hasGFX1250Insts())
12486 return AMDGPU::getWMMAIsXDL(MI.getOpcode());
12487
12488 return true;
12489}
12490
12492 unsigned Opcode = MI.getOpcode();
12493
12494 if (AMDGPU::isGFX12Plus(ST))
12495 return isDOT(MI) || isXDLWMMA(MI);
12496
12497 if (!isMAI(MI) || isDGEMM(Opcode) ||
12498 Opcode == AMDGPU::V_ACCVGPR_WRITE_B32_e64 ||
12499 Opcode == AMDGPU::V_ACCVGPR_READ_B32_e64)
12500 return false;
12501
12502 if (!ST.hasGFX940Insts())
12503 return true;
12504
12505 return AMDGPU::getMAIIsGFX940XDL(Opcode);
12506}
12507
12509 constexpr unsigned MinOrderedXDLVAVDSTVGPRs = 8;
12510 if (!AMDGPU::isGFX1250(ST) || !isXDL(MI))
12511 return false;
12512
12513 const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
12514 const TargetRegisterClass *DstRC =
12515 getRegClass(MI.getDesc(), Dst->getOperandNo());
12516 return DstRC && RI.isVGPRClass(DstRC) &&
12517 RI.getRegSizeInBits(*DstRC) >= MinOrderedXDLVAVDSTVGPRs * 32;
12518}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static const TargetRegisterClass * getRegClass(const MachineInstr &MI, Register Reg)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
Shared AMDGPU asyncmark stage definitions.
uint64_t uint64_t
uint64_t Imm
Contains the definition of a TargetInstrInfo class that is common to all AMD GPUs.
AMDGPU Register Bank Select
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
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< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
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.
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
static Register UseReg(const MachineOperand &MO)
IRTranslator LLVM IR MI
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isUndef(const MachineInstr &MI)
TargetInstrInfo::RegSubRegPair RegSubRegPair
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
R600 Clause Merge
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file declares the machine register scavenger class.
static void expandSGPRCopy(const SIInstrInfo &TII, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, const TargetRegisterClass *RC, bool Forward)
static std::optional< std::pair< int64_t, int64_t > > getSelectConstants(const SIInstrInfo &TII, const MachineRegisterInfo &MRI, const MachineInstr &Sel)
If Sel is an S_CSELECT* of two different constants A and B, return them, truncated to the width of th...
static unsigned getSrcModifiers(const MachineInstr &MI, unsigned OpIdx)
static void expandLoadStoreIdx(const SIInstrInfo &TII, MachineInstr &MI)
static void lowerVGPRCopyToM0(const SIInstrInfo &TII, MachineInstr &Copy, ArrayRef< MachineInstr * > Readers, MachineRegisterInfo &MRI, MachineDominatorTree *MDT)
static unsigned getNewFMAInst(const GCNSubtarget &ST, unsigned Opc)
static unsigned getIndirectSGPRWriteMovRelPseudo32(unsigned VecSize)
static bool compareMachineOp(const MachineOperand &Op0, const MachineOperand &Op1)
static bool isStride64(unsigned Opc)
static MachineBasicBlock * generateWaterFallLoop(const SIInstrInfo &TII, MachineInstr &MI, ArrayRef< MachineOperand * > ScalarOps, MachineDominatorTree *MDT, MachineBasicBlock::iterator Begin=nullptr, MachineBasicBlock::iterator End=nullptr, ArrayRef< Register > PhySGPRs={})
#define GENERATE_RENAMED_GFX9_CASES(OPCODE)
static std::tuple< unsigned, unsigned > extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc)
static unsigned VOP3OpIdxToSrcN(const MachineInstr &MI, unsigned OpIdx)
static bool followSubRegDef(MachineInstr &MI, TargetInstrInfo::RegSubRegPair &RSR)
static unsigned getIndirectSGPRWriteMovRelPseudo64(unsigned VecSize)
static MachineInstr * swapImmOperands(MachineInstr &MI, MachineOperand &NonRegOp1, MachineOperand &NonRegOp2)
static void copyFlagsToImplicitVCC(MachineInstr &MI, const MachineOperand &Orig)
static bool isBF16FPInlineConstant(int64_t Imm, bool HasInv2Pi)
static bool offsetsDoNotOverlap(LocationSize WidthA, int OffsetA, LocationSize WidthB, int OffsetB)
static void indirectCopyToAGPR(const SIInstrInfo &TII, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, RegScavenger &RS, bool RegsOverlap, Register ImpUseSuperReg=Register())
Handle copying from SGPR to AGPR, or from AGPR to AGPR on GFX908.
static unsigned getWWMRegSpillSaveOpcode(unsigned Size, bool IsVectorSuperClass)
static bool memOpsHaveSameBaseOperands(ArrayRef< const MachineOperand * > BaseOps1, ArrayRef< const MachineOperand * > BaseOps2)
static unsigned getWWMRegSpillRestoreOpcode(unsigned Size, bool IsVectorSuperClass)
static unsigned getSGPRSpillSaveOpcode(unsigned Size, bool NeedsCFI)
static bool setsSCCIfResultIsZero(const MachineInstr &Def, bool &NeedInversion, unsigned &NewDefOpc)
static bool isSCCDeadOnExit(MachineBasicBlock *MBB)
static bool isImmOpSelLegal(const GCNSubtarget &ST, const MachineInstr &MI, unsigned OpIdx, int64_t Imm, std::optional< unsigned > Mods=std::nullopt)
static unsigned getIndirectVGPRWriteMovRelPseudoOpc(unsigned VecSize)
static unsigned subtargetEncodingFamily(const GCNSubtarget &ST)
static void preserveCondRegFlags(MachineOperand &CondReg, const MachineOperand &OrigCond)
static Register findImplicitSGPRRead(const MachineInstr &MI)
static unsigned getNewFMAAKInst(const GCNSubtarget &ST, unsigned Opc)
static unsigned getNumOpSelBitsForMods(const GCNSubtarget &ST, const MachineInstr &MI, unsigned OpIdx, unsigned Mods)
static unsigned getAVSpillSaveOpcode(unsigned Size, bool NeedsCFI)
static const MachineOperand * getSrcModifiersOperand(const MachineInstr &MI, unsigned OpIdx)
static bool memOpsHaveSameBasePtr(const MachineInstr &MI1, ArrayRef< const MachineOperand * > BaseOps1, const MachineInstr &MI2, ArrayRef< const MachineOperand * > BaseOps2)
static unsigned getSGPRSpillRestoreOpcode(unsigned Size)
static bool isRegOrFI(const MachineOperand &MO)
static bool isVCmp(const SIInstrInfo &TII, const MachineInstr &MI)
Return true if MI is a VALU comparison, i.e.
static unsigned getVGPRSpillSaveOpcode(unsigned Size, bool NeedsCFI)
static constexpr AMDGPU::OpName ModifierOpNames[]
static void reportIllegalCopy(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, const char *Msg="illegal VGPR to SGPR copy")
static MachineInstr * swapRegAndNonRegOperand(MachineInstr &MI, MachineOperand &RegOp, MachineOperand &NonRegOp)
static bool isLegalPkF32OpSel(const SIInstrInfo &TII, const MachineInstr &MI, bool CheckSwappedSrc=false)
static bool shouldReadExec(const MachineInstr &MI)
static unsigned getOpSelHalfSize(uint8_t OpType)
static unsigned getNewFMAMKInst(const GCNSubtarget &ST, unsigned Opc)
static bool isRenamedInGFX9(int Opcode)
static TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd)
static bool isMADFMA(unsigned Opc)
static bool changesVGPRIndexingMode(const MachineInstr &MI)
static bool isSubRegOf(const SIRegisterInfo &TRI, const MachineOperand &SuperVec, const MachineOperand &SubReg)
static bool nodesHaveSameOperandValue(SDNode *N0, SDNode *N1, AMDGPU::OpName OpName)
Returns true if both nodes have the same value for the given operand Op, or if both nodes do not have...
static std::pair< unsigned, unsigned > splitGlobalAddressRelocFlags(const MachineOperand &SrcOp)
static unsigned getNumOperandsNoGlue(SDNode *Node)
static bool canRemat(const MachineInstr &MI)
static unsigned getAVSpillRestoreOpcode(unsigned Size)
static void emitLoadScalarOpsFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI, MachineBasicBlock &PredBB, MachineBasicBlock &LoopBB, MachineBasicBlock &BodyBB, const DebugLoc &DL, ArrayRef< MachineOperand * > ScalarOps, ArrayRef< Register > PhySGPRs={})
static unsigned getVGPRSpillRestoreOpcode(unsigned Size)
Interface definition for SIInstrInfo.
bool IsDead
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const LaneMaskConstants & get(const GCNSubtarget &ST)
static LLVM_ABI Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
Definition APFloat.cpp:459
Class for arbitrary precision integers.
Definition APInt.h:78
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
uint64_t getZExtValue() const
Opaque handle to a cycle within a GenericCycleInfo that wraps the cycle's preorder index.
A debug info location.
Definition DebugLoc.h:126
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Diagnostic information for unsupported feature in backend.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
void getExitingBlocks(CycleRef C, SmallVectorImpl< BlockT * > &TmpStorage) const
Return all blocks of C that have a successor outside of C.
CycleRef getParentCycle(CycleRef C) const
bool contains(CycleRef Outer, CycleRef Inner) const
Returns true iff Outer contains Inner. O(1). Non-strict.
CycleRef getCycle(const BlockT *Block) const
Find the innermost cycle containing Block.
Itinerary data supplied by a subtarget to be used by a target.
constexpr unsigned getAddressSpace() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
iterator_range< subrange_iterator > subranges()
bool hasInterval(Register Reg) const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
LiveInterval & getInterval(Register Reg)
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr, LaneBitmask SubRangeMask=LaneBitmask::getAll())
After removing some uses of a register, shrink its live range to just the remaining uses.
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
This class represents the liveness of a register, stack slot, etc.
bool hasValue() const
static LocationSize precise(uint64_t Value)
TypeSize getValue() const
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:344
static const MCBinaryExpr * createAShr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:414
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:424
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
unsigned getSize() const
Return the number of bytes in the encoding of this instruction, or zero if the encoding size cannot b...
ArrayRef< MCPhysReg > implicit_uses() const
Return a list of registers that are potentially read by any instance of this machine instruction.
unsigned getOpcode() const
Return the opcode number for this descriptor.
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition MCInstrDesc.h:88
uint8_t OperandType
Information about the type of the operand.
int16_t RegClass
This specifies the register class enumeration of the operand if the operand is a register.
Definition MCInstrDesc.h:94
bool hasSuperClassEq(const MCRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:210
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI void setVariableValue(const MCExpr *Value)
Definition MCSymbol.cpp:51
Helper class for constructing bundles of MachineInstrs.
MachineBasicBlock::instr_iterator begin() const
Return an iterator to the first bundled instruction.
MIBundleBuilder & append(MachineInstr *MI)
Insert MI into MBB by appending it to the instructions in the bundle.
MIRFormater - Interface to format MIR operand based on target.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
void push_back(MachineInstr *MI)
LLVM_ABI LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
Instructions::const_iterator const_instr_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
@ LQR_Dead
Register is known to be fully dead.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool isImmutableObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to an immutable object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void push_back(MachineBasicBlock *MBB)
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
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
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & copyImplicitOps(const MachineInstr &OtherMI) const
Copy all the implicit operands from OtherMI onto this one.
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
bool isCopy() const
const MachineBasicBlock * getParent() const
LLVM_ABI void addImplicitDefUseOperands(MachineFunction &MF)
Add all implicit def and use operands to this instruction.
bool isBundle() const
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
LLVM_ABI unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
mop_range implicit_operands()
bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
void untieRegOperand(unsigned OpIdx)
Break any tie involving OpIdx.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI void eraseFromBundle()
Unlink 'this' from its basic block and delete it.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
mop_range explicit_operands()
LLVM_ABI void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
bool isMoveImmediate(QueryType Type=IgnoreBundle) const
Return true if this instruction is a move immediate (including conditional moves) instruction.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
LLVM_ABI void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol)
Set a symbol that will be emitted just after the instruction itself.
LLVM_ABI void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo)
Clear all kill flags affecting Reg.
const MachineOperand & getOperand(unsigned i) const
uint32_t getFlags() const
Return the MI flags bitvector.
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand * findRegisterDefOperand(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false)
Wrapper for findRegisterDefOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
A description of a memory reference used in the backend.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
const GlobalValue * getGlobal() const
LLVM_ABI void ChangeToFrameIndex(int Idx, unsigned TargetFlags=0)
Replace this operand with a frame index.
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
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.
LLVM_ABI void ChangeToGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
ChangeToGA - Replace this operand with a new global address operand.
void setIsKill(bool Val=true)
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.
void setOffset(int64_t Offset)
unsigned getTargetFlags() const
static MachineOperand CreateImm(int64_t Val)
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
void setIsUndef(bool Val=true)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
bool isTargetIndex() const
isTargetIndex - Tests if this is a MO_TargetIndex operand.
void setTargetFlags(unsigned F)
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
@ MO_Immediate
Immediate operand.
@ MO_Register
Register operand.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
int64_t getOffset() const
Return the offset from the symbol in this operand.
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
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.
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
const MachineFunction & getMF() const
void setSimpleHint(Register VReg, Register PrefReg)
Specify the preferred (target independent) register allocation hint for the specified virtual registe...
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
iterator_range< use_iterator > use_operands(Register Reg) const
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
const RegisterBank & getRegBank(unsigned ID)
Get the register bank identified by ID.
This class implements the register bank concept.
unsigned getID() const
Get the identifier of this register bank.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isValid() const
Definition Register.h:109
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
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
const SDValue & getOperand(unsigned Num) const
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isLegalMUBUFImmOffset(unsigned Imm) const
bool isInlineConstant(const APInt &Imm) const
void legalizeOperandsVOP3(MachineRegisterInfo &MRI, MachineInstr &MI) const
Fix operands in MI to satisfy constant bus requirements.
bool canAddToBBProlog(const MachineInstr &MI) const
static std::optional< unsigned > extractSubregFromGlobalAddressFlags(unsigned TargetFlags, unsigned SubRegIndex)
Return the target flags for a global address operand reading subregister SubRegIndex of a 64-bit glob...
static bool isDS(const MachineInstr &MI)
MachineBasicBlock * legalizeOperands(MachineInstr &MI, MachineDominatorTree *MDT=nullptr) const
Legalize all operands in this instruction.
bool areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1, int64_t &Offset0, int64_t &Offset1) const override
unsigned getLiveRangeSplitOpcode(Register Reg, const MachineFunction &MF) const override
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
static bool isNeverUniform(const MachineInstr &MI)
bool isXDLWMMA(const MachineInstr &MI) const
void handleCopyToPhysHelper(SIInstrWorklist &Worklist, Register DstReg, MachineInstr &Inst, MachineRegisterInfo &MRI, MachineDominatorTree *MDT, DenseMap< MachineInstr *, V2PhysSCopyInfo > &WaterFalls, DenseMap< MachineInstr *, bool > &V2SPhyCopiesToErase) const
bool isBasicBlockPrologue(const MachineInstr &MI, Register Reg=Register()) const override
uint64_t getDefaultRsrcDataFormat() const
static bool isSOPP(const MachineInstr &MI)
bool mayAccessScratch(const MachineInstr &MI) const
bool isIGLP(unsigned Opcode) const
static bool isFLATScratch(const MachineInstr &MI)
Register buildVGPR32FromLo16(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register Src, unsigned SrcSubReg) const
Build a 32-bit VGPR whose low half is the 16-bit value Src.SrcSubReg and whose high half is undefined...
bool isLegalFLATOffset(int64_t Offset, unsigned AddrSpace, AMDGPU::FlatAddrSpace FlatVariant) const
Returns if Offset is legal for the subtarget as the offset to a FLAT encoded instruction with the giv...
const MCInstrDesc & getIndirectRegWriteMovRelPseudo(unsigned VecSize, unsigned EltSize, bool IsSGPR) const
MachineInstrBuilder getAddNoCarry(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DestReg) const
Return a partially built integer add instruction without carry.
bool shouldScheduleLoadsNear(SDNode *Load0, SDNode *Load1, int64_t Offset0, int64_t Offset1, unsigned NumLoads) const override
bool splitMUBUFOffset(uint32_t Imm, uint32_t &SOffset, uint32_t &ImmOffset, Align Alignment=Align(4)) const
bool isIgnorableUse(const MachineInstr &MI, unsigned OpIdx) const override
ArrayRef< std::pair< unsigned, const char * > > getSerializableDirectMachineOperandTargetFlags() const override
void moveToVALU(SIInstrWorklist &Worklist, MachineDominatorTree *MDT) const
Replace the instructions opcode with the equivalent VALU opcode.
static bool isSMRD(const MachineInstr &MI)
unsigned getGFX1250BlockingCyclesTable(const MachineInstr &MI) const
GFX1250 blocking-cycles table lookup with no occupancy subtarget gate.
void restoreExec(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, Register Reg, SlotIndexes *Indexes=nullptr) const
void storeRegToStackSlotCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC) const
bool usesConstantBus(const MachineRegisterInfo &MRI, const MachineOperand &MO, const MCOperandInfo &OpInfo) const
Returns true if this operand uses the constant bus.
static unsigned getMaxMUBUFImmOffset(const GCNSubtarget &ST)
static unsigned getFoldableCopySrcIdx(const MachineInstr &MI)
unsigned getOpSize(uint32_t Opcode, unsigned OpNo) const
Return the size in bytes of the operand OpNo on the given.
void legalizeOperandsFLAT(MachineRegisterInfo &MRI, MachineInstr &MI) const
bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask, int64_t CmpValue, const MachineRegisterInfo *MRI) const override
bool getMemOperandsWithOffsetWidth(const MachineInstr &LdSt, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const final
static std::optional< int64_t > extractSubregFromImm(int64_t ImmVal, unsigned SubRegIndex)
Return the extracted immediate value in a subregister use from a constant materialized in a super reg...
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
static bool isMTBUF(const MachineInstr &MI)
const MCInstrDesc & getIndirectGPRIDXPseudo(unsigned VecSize, bool IsIndirectSrc) const
static bool isDGEMM(unsigned Opcode)
static bool isEXP(const MachineInstr &MI)
static bool isSALU(const MachineInstr &MI)
static bool setsSCCIfResultIsNonZero(const MachineInstr &MI)
const MIRFormatter * getMIRFormatter() const override
static bool isXcntDrain(const MachineInstr &MI)
True if MI implicitly drains XCNT.
void legalizeGenericOperand(MachineBasicBlock &InsertMBB, MachineBasicBlock::iterator I, const TargetRegisterClass *DstRC, MachineOperand &Op, MachineRegisterInfo &MRI, const DebugLoc &DL) const
MachineInstr * buildShrunkInst(MachineInstr &MI, unsigned NewOpcode) const
static bool isVOP2(const MachineInstr &MI)
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
static bool isSDWA(const MachineInstr &MI)
const MCInstrDesc & getKillTerminatorFromPseudo(unsigned Opcode) const
void insertNoops(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned Quantity) const override
static bool isGather4(const MachineInstr &MI)
MachineInstr * getWholeWaveFunctionSetup(MachineFunction &MF) const
static bool isDOT(const MachineInstr &MI)
std::unique_ptr< PipelinerLoopInfo > analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const override
InstSizeVerifyMode getInstSizeVerifyMode(const MachineInstr &MI) const override
MachineInstr * createPHISourceCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const override
static bool usesTENSOR_CNT(const MachineInstr &MI)
bool hasModifiers(unsigned Opcode) const
Return true if this instruction has any modifiers.
bool shouldClusterMemOps(ArrayRef< const MachineOperand * > BaseOps1, int64_t Offset1, bool OffsetIsScalable1, ArrayRef< const MachineOperand * > BaseOps2, int64_t Offset2, bool OffsetIsScalable2, unsigned ClusterSize, unsigned NumBytes) const override
static bool isSWMMAC(const MachineInstr &MI)
ScheduleHazardRecognizer * CreateTargetMIHazardRecognizer(const InstrItineraryData *II, const ScheduleDAGMI *DAG) const override
bool isWave32() const
bool isHighLatencyDef(int Opc) const override
void legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const
Legalize the OpIndex operand of this instruction by inserting a MOV.
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
static bool isVOPC(const MachineInstr &MI)
void removeModOperands(MachineInstr &MI) const
bool isImmEquivalentToReg(const MachineInstr &MI, unsigned OpIdx, int64_t Imm) const
Return true if Imm reads the same as a register holding Imm.
unsigned getVectorRegSpillRestoreOpcode(Register Reg, const TargetRegisterClass *RC, unsigned Size, const SIMachineFunctionInfo &MFI) const
bool isLegalSingleSGPRReadInstOperand(const MachineRegisterInfo &MRI, const MachineInstr &MI, unsigned SrcN, const MachineOperand *MO=nullptr) const
Check if MO would be a legal operand for a single-SGPR-read instruction.
bool isXDL(const MachineInstr &MI) const
Register isStackAccess(const MachineInstr &MI, int &FrameIndex, TypeSize &MemBytes) const
static bool isVIMAGE(const MachineInstr &MI)
void enforceOperandRCAlignment(MachineInstr &MI, AMDGPU::OpName OpName) const
static bool isSOP2(const MachineInstr &MI)
static bool isGWS(const MachineInstr &MI)
bool hasRAWDependency(const MachineInstr &FirstMI, const MachineInstr &SecondMI) const
bool isLegalAV64PseudoImm(uint64_t Imm) const
Check if this immediate value can be used for AV_MOV_B64_IMM_PSEUDO.
bool isNeverCoissue(MachineInstr &MI) const
static bool isBUF(const MachineInstr &MI)
bool isNonCommutableDPP(const MachineInstr &MI) const
bool hasModifiersSet(const MachineInstr &MI, AMDGPU::OpName OpName) const
bool isLegalToSwap(const MachineInstr &MI, unsigned fromIdx, unsigned toIdx) const
static bool isFLATGlobal(const MachineInstr &MI)
MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const override
bool isGlobalMemoryObject(const MachineInstr *MI) const override
bool canInsertSelect(const MachineBasicBlock &MBB, ArrayRef< MachineOperand > Cond, Register DstReg, Register TrueReg, Register FalseReg, SelectExpansion &Exp) const override
static bool isVSAMPLE(const MachineInstr &MI)
bool isBufferSMRD(const MachineInstr &MI) const
static bool isKillTerminator(unsigned Opcode)
bool isVOPDAntidependencyAllowed(const MachineInstr &MI) const
If OpX is multicycle, anti-dependencies are not allowed.
bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx0, unsigned &SrcOpIdx1) const override
void insertScratchExecCopy(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, Register Reg, bool IsSCCLive, SlotIndexes *Indexes=nullptr) const
bool hasVALU32BitEncoding(unsigned Opcode) const
Return true if this 64-bit VALU instruction has a 32-bit encoding.
unsigned getBlockingCycles(const MachineInstr &MI) const
unsigned getMovOpcode(const TargetRegisterClass *DstRC) const
Register isSGPRStackAccess(const MachineInstr &MI, int &FrameIndex, TypeSize &MemBytes) const
unsigned buildExtractSubReg(MachineBasicBlock::iterator MI, MachineRegisterInfo &MRI, const MachineOperand &SuperReg, const TargetRegisterClass *SuperRC, unsigned SubIdx, const TargetRegisterClass *SubRC) const
void legalizeOperandsVOP2(MachineRegisterInfo &MRI, MachineInstr &MI) const
Legalize operands in MI by either commuting it or inserting a copy of src1.
static bool isVPermPk16(unsigned Opcode)
static bool isVALU(const MachineInstr &MI, bool AllowLDSDMA)
bool foldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, Register Reg, MachineRegisterInfo *MRI) const final
static bool isTRANS(const MachineInstr &MI)
static bool isImage(const MachineInstr &MI)
static bool isSOPK(const MachineInstr &MI)
const TargetRegisterClass * getOpRegClass(const MachineInstr &MI, unsigned OpNo) const
Return the correct register class for OpNo.
MachineBasicBlock * insertSimulatedTrap(MachineRegisterInfo &MRI, MachineBasicBlock &MBB, MachineInstr &MI, const DebugLoc &DL) const
Build instructions that simulate the behavior of a s_trap 2 instructions for hardware (namely,...
std::optional< unsigned > getImmOpSelForValue(const MachineInstr &MI, unsigned OpIdx, int64_t Imm, int64_t Value, unsigned Mods) const
Return Mods with op_sel chosen so that Imm reads Value.
static unsigned getNonSoftWaitcntOpcode(unsigned Opcode)
static unsigned getDSShaderTypeValue(const MachineFunction &MF)
static bool isFoldableCopy(const MachineInstr &MI)
static bool isMUBUF(const MachineInstr &MI)
bool expandPostRAPseudo(MachineInstr &MI) const override
bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &CmpMask, int64_t &CmpValue) const override
void createWaterFallForSiCall(MachineInstr *MI, MachineDominatorTree *MDT, ArrayRef< MachineOperand * > ScalarOps, ArrayRef< Register > PhySGPRs={}) const
Wrapper function for generating waterfall for instruction MI This function take into consideration of...
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
AMDGPU::AsyncStages getAsyncStage(const MachineInstr &MI) const
static bool isSegmentSpecificFLAT(const MachineInstr &MI)
bool isReMaterializableImpl(const MachineInstr &MI) const override
static bool isVOP3(const MCInstrDesc &Desc)
int64_t getSrcOperandValue(const MachineInstr &MI, unsigned OpIdx, int64_t Bits, unsigned Mods) const
Return the sign extended value operand OpIdx reads from Bits.
Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
bool physRegUsesConstantBus(const MachineOperand &Reg) const
void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DstReg, ArrayRef< MachineOperand > Cond, Register TrueReg, Register FalseReg) const override
bool mayAccessVMEMThroughFlat(const MachineInstr &MI) const
static bool isDPP(const MachineInstr &MI)
bool analyzeBranchImpl(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const
static bool isMFMA(const MachineInstr &MI)
bool isLowLatencyInstruction(const MachineInstr &MI) const
std::optional< DestSourcePair > isCopyInstrImpl(const MachineInstr &MI) const override
If the specific machine instruction is a instruction that moves/copies value from one register to ano...
void mutateAndCleanupImplicit(MachineInstr &MI, const MCInstrDesc &NewDesc) const
ValueUniformity getGenericValueUniformity(const MachineInstr &MI) const
static bool isMAI(const MCInstrDesc &Desc)
static bool isSrc1DPPRevOpcode(const GCNSubtarget &ST, uint32_t Opcode)
void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, unsigned SubIdx, const MachineInstr &Orig, LaneBitmask UsedLanes=LaneBitmask::getAll()) const override
static bool usesLGKM_CNT(const MachineInstr &MI)
void legalizeOperandsVALUt16(MachineInstr &Inst, MachineRegisterInfo &MRI) const
Fix operands in Inst to fix 16bit SALU to VALU lowering.
bool isImmOperandLegal(const MCInstrDesc &InstDesc, unsigned OpNo, const MachineOperand &MO) const
bool canShrink(const MachineInstr &MI, const MachineRegisterInfo &MRI) const
const MachineOperand & getCalleeOperand(const MachineInstr &MI) const override
bool isAsmOnlyOpcode(int MCOp) const
Check if this instruction should only be used by assembler.
bool isAlwaysGDS(uint32_t Opcode) const
static bool isVGPRSpill(const MachineInstr &MI)
ScheduleHazardRecognizer * CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, const ScheduleDAG *DAG) const override
This is used by the post-RA scheduler (SchedulePostRAList.cpp).
bool verifyInstruction(const MachineInstr &MI, StringRef &ErrInfo) const override
unsigned getInstrLatency(const InstrItineraryData *ItinData, const MachineInstr &MI, unsigned *PredCost=nullptr) const override
unsigned getVectorRegSpillSaveOpcode(Register Reg, const TargetRegisterClass *RC, unsigned Size, const SIMachineFunctionInfo &MFI, bool NeedsCFI) const
int64_t getNamedImmOperand(const MachineInstr &MI, AMDGPU::OpName OperandName) const
Get required immediate operand.
ArrayRef< std::pair< int, const char * > > getSerializableTargetIndices() const override
bool regUsesConstantBus(const MachineOperand &Reg, const MachineRegisterInfo &MRI) const
static bool isMIMG(const MachineInstr &MI)
MachineOperand buildExtractSubRegOrImm(MachineBasicBlock::iterator MI, MachineRegisterInfo &MRI, const MachineOperand &SuperReg, const TargetRegisterClass *SuperRC, unsigned SubIdx, const TargetRegisterClass *SubRC) const
bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const override
bool isLegalRegOperand(const MachineRegisterInfo &MRI, const MCOperandInfo &OpInfo, const MachineOperand &MO) const
Check if MO (a register operand) is a legal register for the given operand description or operand ind...
static unsigned getNumWaitStates(const MachineInstr &MI)
Return the number of wait states that result from executing this instruction.
static bool isVOP3P(const MachineInstr &MI)
bool isVAVDSTOrderedXDL(const MachineInstr &MI) const
On gfx1250, an XDL instruction whose destination spans at least eight VGPRs decrements VA_VDST only a...
unsigned getVALUOp(const MachineInstr &MI) const
static bool modifiesModeRegister(const MachineInstr &MI)
Return true if the instruction modifies the mode register.q.
Register readlaneVGPRToSGPR(Register SrcReg, MachineInstr &UseMI, MachineRegisterInfo &MRI, const TargetRegisterClass *DstRC=nullptr) const
Copy a value from a VGPR (SrcReg) to SGPR.
bool hasDivergentBranch(const MachineBasicBlock *MBB) const
Return whether the block terminate with divergent branch.
std::pair< int64_t, int64_t > splitFlatOffset(int64_t COffsetVal, unsigned AddrSpace, AMDGPU::FlatAddrSpace FlatVariant) const
Split COffsetVal into {immediate offset field, remainder offset} values.
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
void fixImplicitOperands(MachineInstr &MI) const
bool moveFlatAddrToVGPR(MachineInstr &Inst) const
Change SADDR form of a FLAT Inst to its VADDR form if saddr operand was moved to VGPR.
static bool usesASYNC_CNT(const MachineInstr &MI)
void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const override
bool isMaskedByExec(Register Reg, const MachineInstr &Use, const MachineRegisterInfo &MRI, unsigned Depth=0) const
Return true if Reg is a lane mask that already has 0 in every bit corresponding to a lane that is ina...
void createReadFirstLaneFromCopyToPhysReg(MachineRegisterInfo &MRI, Register DstReg, MachineInstr &Inst) const
bool swapSourceModifiers(MachineInstr &MI, MachineOperand &Src0, AMDGPU::OpName Src0OpName, MachineOperand &Src1, AMDGPU::OpName Src1OpName) const
MachineBasicBlock * getBranchDestBlock(const MachineInstr &MI) const override
bool isAsync(const MachineInstr &MI) const
bool memOpsHaveSameBase(ArrayRef< const MachineOperand * > BaseOps1, ArrayRef< const MachineOperand * > BaseOps2) const
Return true if the memory operations described by BaseOps1 and BaseOps2 (as returned by getMemOperand...
bool hasUnwantedEffectsWhenEXECEmpty(const MachineInstr &MI) const
This function is used to determine if an instruction can be safely executed under EXEC = 0 without ha...
bool getConstValDefinedInReg(const MachineInstr &MI, const Register Reg, int64_t &ImmVal) const override
static bool isAtomic(const MachineInstr &MI)
bool isLiteralOperandLegal(const MCInstrDesc &InstDesc, const MCOperandInfo &OpInfo) const
static bool isWWMRegSpillOpcode(uint32_t Opcode)
static bool sopkIsZext(unsigned Opcode)
static bool isSGPRSpill(const MachineInstr &MI)
static bool isWMMA(const MachineInstr &MI)
ArrayRef< std::pair< MachineMemOperand::Flags, const char * > > getSerializableMachineMemOperandTargetFlags() const override
bool mayReadEXEC(const MachineRegisterInfo &MRI, const MachineInstr &MI) const
Returns true if the instruction could potentially depend on the value of exec.
void legalizeOperandsSMRD(MachineRegisterInfo &MRI, MachineInstr &MI) const
bool isBranchOffsetInRange(unsigned BranchOpc, int64_t BrOffset) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
std::pair< MachineInstr *, MachineInstr * > expandMovDPP64(MachineInstr &MI) const
static bool isSOPC(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
bool isBarrier(unsigned Opcode) const
MachineInstr * commuteInstructionImpl(MachineInstr &MI, bool NewMI, unsigned OpIdx0, unsigned OpIdx1) const override
bool mayAccessLDSThroughFlat(const MachineInstr &MI, bool TgSplit) const
int pseudoToMCOpcode(int Opcode) const
Return a target-specific opcode if Opcode is a pseudo instruction.
const MCInstrDesc & getMCOpcodeFromPseudo(unsigned Opcode) const
Return the descriptor of the target-specific machine instruction that corresponds to the specified ps...
bool isImmOperandLegalWithMods(const MachineInstr &MI, unsigned OpNo, int64_t ImmVal, unsigned Mods) const
Return true if ImmVal is legal for OpNo with modifiers Mods.
static bool usesVM_CNT(const MachineInstr &MI)
MachineInstr * createPHIDestinationCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, Register Dst) const override
static bool isFixedSize(const MachineInstr &MI)
bool isSafeToSink(MachineInstr &MI, MachineBasicBlock *SuccToSinkTo, MachineCycleInfo *CI) const override
LLVM_READONLY int commuteOpcode(unsigned Opc) const
unsigned getNumOpSelBits(const MachineInstr &MI, unsigned OpIdx) const
Return how many op_sel bits select a half of source operand OpIdx.
ValueUniformity getValueUniformity(const MachineInstr &MI) const final
uint64_t getScratchRsrcWords23() const
LLVM_READONLY MachineOperand * getNamedOperand(MachineInstr &MI, AMDGPU::OpName OperandName) const
Returns the operand named Op.
MachineInstr * convertToThreeAddress(MachineInstr &MI, LiveIntervals *LIS) const override
std::pair< unsigned, unsigned > decomposeMachineOperandsTargetFlags(unsigned TF) const override
bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const override
bool isOperandLegal(const MachineInstr &MI, unsigned OpIdx, const MachineOperand *MO=nullptr) const
Check if MO is a legal operand if it was the OpIdx Operand for MI.
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
bool allowNegativeFlatOffset(AMDGPU::FlatAddrSpace FlatVariant) const
Returns true if negative offsets are allowed for the given FlatVariant.
void moveToVALUImpl(SIInstrWorklist &Worklist, MachineDominatorTree *MDT, MachineInstr &Inst, DenseMap< MachineInstr *, V2PhysSCopyInfo > &WaterFalls, DenseMap< MachineInstr *, bool > &V2SPhyCopiesToErase) const
static bool isLDSDMA(const MachineInstr &MI)
static bool isVOP1(const MachineInstr &MI)
SIInstrInfo(const GCNSubtarget &ST)
std::optional< int64_t > getImmOrMaterializedImm(const MachineRegisterInfo &MRI, const MachineOperand &Op, MachineInstr **DefMI=nullptr) const
void insertIndirectBranch(MachineBasicBlock &MBB, MachineBasicBlock &NewDestBB, MachineBasicBlock &RestoreBB, const DebugLoc &DL, int64_t BrOffset, RegScavenger *RS) const override
bool hasAnyModifiersSet(const MachineInstr &MI) const
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
void setHasSpilledVGPRs(bool Spill=true)
bool isWWMReg(Register Reg) const
bool checkFlag(Register Reg, uint8_t Flag) const
void setHasSpilledSGPRs(bool Spill=true)
unsigned getScratchReservedForDynamicVGPRs() const
ArrayRef< int16_t > getRegSplitParts(const TargetRegisterClass *RC, unsigned EltSize) const
unsigned getHWRegIndex(MCRegister Reg) const
static unsigned getSubRegFromChannel(uint64_t Channel, uint64_t NumRegs=1)
bool isSGPRReg(const MachineRegisterInfo &MRI, Register Reg) const
unsigned getRegPressureLimit(const TargetRegisterClass *RC, MachineFunction &MF) const override
unsigned getChannelFromSubReg(unsigned SubReg) const
static bool isSGPRClass(const TargetRegisterClass *RC)
static bool isAGPRClass(const TargetRegisterClass *RC)
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
virtual bool hasVRegLiveness() const
Return true if this DAG supports VReg liveness and RegPressure.
MachineFunction & MF
Machine function.
HazardRecognizer - This determines whether or not an instruction can be issued this cycle,...
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndexes pass.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
int64_t getImm() const
Register getReg() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Object returned by analyzeLoopForPipelining.
virtual ScheduleHazardRecognizer * CreateTargetMIHazardRecognizer(const InstrItineraryData *, const ScheduleDAGMI *DAG) const
Allocate and return a hazard recognizer to use for this target when scheduling the machine instructio...
virtual MachineInstr * createPHIDestinationCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual const MachineOperand & getCalleeOperand(const MachineInstr &MI) const
Returns the callee operand from the given MI.
virtual void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, unsigned SubIdx, const MachineInstr &Orig, LaneBitmask UsedLanes=LaneBitmask::getAll()) const
Re-issue the specified 'original' instruction at the specific location targeting a new destination re...
virtual MachineInstr * createPHISourceCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual MachineInstr * commuteInstructionImpl(MachineInstr &MI, bool NewMI, unsigned OpIdx1, unsigned OpIdx2) const
This method commutes the operands of the given machine instruction MI.
virtual bool isGlobalMemoryObject(const MachineInstr *MI) const
Returns true if MI is an instruction we are unable to reason about (like a call or something with unm...
virtual bool expandPostRAPseudo(MachineInstr &MI) const
This function is called for all pseudo instructions that remain after register allocation.
const MCAsmInfo & getMCAsmInfo() const
Return target specific asm information.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ FLAT_ADDRESS
Address space for flat memory.
@ PRIVATE_ADDRESS
Address space for private memory.
unsigned encodeFieldSaSdst(unsigned Encoded, unsigned SaSdst)
const uint64_t RSRC_DATA_FORMAT
bool isPKFMACF16InlineConstant(uint32_t Literal, bool IsGFX11Plus)
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
bool isInlinableLiteralFP16(int16_t Literal, bool HasInv2Pi)
bool getWMMAIsXDL(unsigned Opc)
unsigned mapWMMA2AddrTo3AddrOpcode(unsigned Opc)
bool isInlinableLiteralV2I16(uint32_t Literal)
bool isDPMACCInstruction(unsigned Opc)
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
bool isInlinableLiteralV2BF16(uint32_t Literal)
LLVM_READONLY int32_t getCommuteRev(uint32_t Opcode)
LLVM_READONLY int32_t getCommuteOrig(uint32_t Opcode)
unsigned getNumFlatOffsetBits(const MCSubtargetInfo &ST)
For pre-GFX12 FLAT instructions the offset must be positive; MSB is ignored and forced to zero.
bool isGFX12Plus(const MCSubtargetInfo &STI)
bool isInlinableLiteralV2F16(uint32_t Literal)
constexpr bool isValidAsyncStageMask(int64_t Mask)
AsyncStages
Bit mask of the async stages tracked by the asyncmark / wait_asyncmark intrinsics.
unsigned getRegBitWidth(unsigned RCID)
Get the size in bits of a register from the register class RC.
bool isValid32BitLiteral(uint64_t Val, bool IsFP64)
LLVM_READONLY int32_t getGlobalVaddrOp(uint32_t Opcode)
LLVM_READNONE bool isLegalDPALU_DPPControl(const MCSubtargetInfo &ST, unsigned DC)
LLVM_READONLY int32_t getMFMAEarlyClobberOp(uint32_t Opcode)
bool getMAIIsGFX940XDL(unsigned Opc)
bool isVOP3DPPSrc1RevOpc(const MCSubtargetInfo &STI, unsigned Opc)
const uint64_t RSRC_ELEMENT_SIZE_SHIFT
bool isIntrinsicAlwaysUniform(unsigned IntrID)
bool isPackedSingleSGPR64BitInst(unsigned Opc)
The opcode is a packed 64-bit instruction which only reads low 64 bits of a scalar operand and propag...
LLVM_READONLY bool hasNamedOperand(uint32_t Opcode, OpName NamedIdx)
LLVM_READONLY int32_t getIfAddr64Inst(uint32_t Opcode)
Check if Opcode is an Addr64 opcode.
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfoByEncoding(uint8_t DimEnc)
bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi)
const uint64_t RSRC_TID_ENABLE
LLVM_READONLY int32_t getVOPe32(uint32_t Opcode)
bool isIntrinsicSourceOfDivergence(unsigned IntrID)
constexpr bool isSISrcOperand(const MCOperandInfo &OpInfo)
Is this an AMDGPU specific source operand?
bool isGenericAtomic(unsigned Opc)
LLVM_READNONE bool isInlinableIntLiteral(int64_t Literal)
Is this literal inlinable, and not one of the values intended for floating point values.
bool isInlinableLiteralBF16(int16_t Literal, bool HasInv2Pi, bool *IsBF16)
unsigned getAddrSizeMIMGOp(const MIMGBaseOpcodeInfo *BaseOpcode, const MIMGDimInfo *Dim, bool IsA16, bool IsG16Supported)
LLVM_READONLY int32_t getAddr64Inst(uint32_t Opcode)
int32_t getMCOpcode(uint32_t Opcode, unsigned Gen)
@ OPERAND_REG_IMM_V2FP64
Definition SIDefines.h:447
@ OPERAND_KIMM32
Operand with 32-bit immediate that uses the constant bus.
Definition SIDefines.h:465
@ OPERAND_REG_IMM_INT64
Definition SIDefines.h:432
@ OPERAND_REG_IMM_V2FP16
Definition SIDefines.h:440
@ OPERAND_REG_INLINE_C_FP64
Definition SIDefines.h:456
@ OPERAND_REG_IMM_NOINLINE_FP16
Definition SIDefines.h:438
@ OPERAND_REG_INLINE_C_BF16
Definition SIDefines.h:453
@ OPERAND_REG_INLINE_C_V2BF16
Definition SIDefines.h:458
@ OPERAND_REG_IMM_V2INT64
Definition SIDefines.h:443
@ OPERAND_REG_IMM_V2INT16
Definition SIDefines.h:442
@ OPERAND_REG_IMM_BF16
Definition SIDefines.h:436
@ OPERAND_REG_IMM_INT32
Operands with register, 32-bit, or 64-bit immediate.
Definition SIDefines.h:431
@ OPERAND_REG_IMM_V2BF16
Definition SIDefines.h:439
@ OPERAND_REG_IMM_FP16
Definition SIDefines.h:437
@ OPERAND_REG_IMM_V2FP16_SPLAT
Definition SIDefines.h:441
@ OPERAND_REG_INLINE_C_INT64
Definition SIDefines.h:452
@ OPERAND_REG_INLINE_C_INT16
Operands with register or inline constant.
Definition SIDefines.h:450
@ OPERAND_REG_IMM_NOINLINE_V2FP16
Definition SIDefines.h:444
@ OPERAND_REG_IMM_FP64
Definition SIDefines.h:435
@ OPERAND_REG_INLINE_C_V2FP16
Definition SIDefines.h:459
@ OPERAND_REG_INLINE_AC_INT32
Operands with an AccVGPR register or inline constant.
Definition SIDefines.h:470
@ OPERAND_REG_INLINE_AC_FP32
Definition SIDefines.h:471
@ OPERAND_REG_IMM_V2INT32
Definition SIDefines.h:445
@ OPERAND_SDWA_VOPC_DST
Definition SIDefines.h:482
@ OPERAND_REG_IMM_FP32
Definition SIDefines.h:434
@ OPERAND_REG_INLINE_C_FP32
Definition SIDefines.h:455
@ OPERAND_REG_INLINE_C_INT32
Definition SIDefines.h:451
@ OPERAND_REG_INLINE_C_V2INT16
Definition SIDefines.h:457
@ OPERAND_INLINE_C_AV64_PSEUDO
Definition SIDefines.h:476
@ OPERAND_REG_IMM_V2FP32
Definition SIDefines.h:446
@ OPERAND_REG_INLINE_AC_FP64
Definition SIDefines.h:472
@ OPERAND_REG_INLINE_C_FP16
Definition SIDefines.h:454
@ OPERAND_REG_IMM_INT16
Definition SIDefines.h:433
@ OPERAND_INLINE_SPLIT_BARRIER_INT32
Definition SIDefines.h:462
LLVM_READONLY int32_t getBasicFromSDWAOp(uint32_t Opcode)
bool isDPALU_DPP(const MCInstrDesc &OpDesc, const MCInstrInfo &MII, const MCSubtargetInfo &ST)
@ TI_SCRATCH_RSRC_DWORD1
Definition AMDGPU.h:677
@ TI_SCRATCH_RSRC_DWORD3
Definition AMDGPU.h:679
@ TI_SCRATCH_RSRC_DWORD0
Definition AMDGPU.h:676
@ TI_SCRATCH_RSRC_DWORD2
Definition AMDGPU.h:678
@ TI_CONSTDATA_START
Definition AMDGPU.h:675
bool isGFX1250(const MCSubtargetInfo &STI)
bool isSingleSGPRReadInst(unsigned Opc)
Packed instructions that read a single SGPR for SGPR operands, except for 64-bit elements which read ...
unsigned getMaxInstLength(const MCSubtargetInfo &STI)
bool isExtendedGlobalAddrSpace(unsigned AS)
bool supportsScaleOffset(const MCInstrInfo &MII, unsigned Opcode)
const uint64_t RSRC_INDEX_STRIDE_SHIFT
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
LLVM_READONLY int32_t getFlatScratchInstSVfromSS(uint32_t Opcode)
bool isInlinableLiteralI16(int32_t Literal, bool HasInv2Pi)
LLVM_READNONE constexpr bool isGraphics(CallingConv::ID CC)
bool isInlinableLiteral64(int64_t Literal, bool HasInv2Pi)
Is this literal inlinable.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ OPERAND_GENERIC_4
Definition MCInstrDesc.h:71
@ OPERAND_GENERIC_2
Definition MCInstrDesc.h:69
@ OPERAND_GENERIC_1
Definition MCInstrDesc.h:68
@ OPERAND_GENERIC_3
Definition MCInstrDesc.h:70
@ OPERAND_IMMEDIATE
Definition MCInstrDesc.h:61
@ OPERAND_GENERIC_0
Definition MCInstrDesc.h:67
@ OPERAND_GENERIC_5
Definition MCInstrDesc.h:72
Not(const Pred &P) -> Not< Pred >
constexpr bool isSDWA(const T &...O)
Definition SIDefines.h:252
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
TargetInstrInfo::RegSubRegPair getRegSubRegPair(const MachineOperand &O)
Create RegSubRegPair from a register MachineOperand.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:208
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
bool execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI, Register VReg, const MachineInstr &DefMI, const MachineInstr &UseMI)
Return false if EXEC is not changed between the def of VReg at DefMI and the use at UseMI.
RegState
Flags to represent properties of register accesses.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
@ Define
Register definition.
@ NoFlags
No Specific Flags.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
static const MachineMemOperand::Flags MOCFSB1
Definition SIInstrInfo.h:75
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
Op::Description Desc
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
TargetInstrInfo::RegSubRegPair getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg)
Return the SubReg component from REG_SEQUENCE.
static const MachineMemOperand::Flags MONoClobber
Mark the MMO of a uniform load if there are no potentially clobbering stores on any path from the sta...
Definition SIInstrInfo.h:49
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
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
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
MachineInstr * getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P, const MachineRegisterInfo &MRI)
Return the defining instruction for a given reg:subreg pair skipping copy like instructions and subre...
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI VirtRegInfo AnalyzeVirtRegInBundle(MachineInstr &MI, Register Reg, SmallVectorImpl< std::pair< MachineInstr *, unsigned > > *Ops=nullptr)
AnalyzeVirtRegInBundle - Analyze how the current instruction or bundle uses a virtual register.
static const MachineMemOperand::Flags MOCooperative
Mark the MMO of cooperative load/store atomics.
Definition SIInstrInfo.h:57
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Xor
Bitwise or logical XOR of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
bool isTargetSpecificOpcode(unsigned Opcode)
Check whether the given Opcode is a target-specific opcode.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned DefaultMemoryClusterDWordsLimit
Definition SIInstrInfo.h:45
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
static const MachineMemOperand::Flags MOLastUse
Mark the MMO of a load as the last use.
Definition SIInstrInfo.h:53
constexpr T reverseBits(T Val)
Reverse the bits in Val.
Definition MathExtras.h:119
static const MachineMemOperand::Flags MOCFSB0
Use two MMO flags to encode the 2-bit cache fill size field for GFX13+.
Definition SIInstrInfo.h:72
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
constexpr RegState getUndefRegState(bool B)
ValueUniformity
Enum describing how values behave with respect to uniformity and divergence, to answer the question: ...
Definition Uniformity.h:18
@ AlwaysUniform
The result value is always uniform.
Definition Uniformity.h:23
@ NeverUniform
The result value can never be assumed to be uniform.
Definition Uniformity.h:26
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
constexpr uint64_t Make_64(uint32_t High, uint32_t Low)
Make a 64-bit integer from a high / low pair of 32-bit integers.
Definition MathExtras.h:161
static const MachineMemOperand::Flags MOThreadPrivate
Mark the MMO of accesses to memory locations that are never written to by other threads.
Definition SIInstrInfo.h:68
bool execMayBeModifiedBeforeAnyUse(const MachineRegisterInfo &MRI, Register VReg, const MachineInstr &DefMI)
Return false if EXEC is not changed between the def of VReg at DefMI and all its uses.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
Helper struct for the implementation of 3-address conversion to communicate updates made to instructi...
MachineInstr * RemoveMIUse
Other instruction whose def is no longer used by the converted instruction.
static constexpr uint64_t encode(Fields... Values)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr bool all() const
Definition LaneBitmask.h:54
This represents a simple continuous liveness interval for a value.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
Utility to store machine instructions worklist.
Definition SIInstrInfo.h:79
MachineInstr * top() const
Definition SIInstrInfo.h:84
bool isDeferred(MachineInstr *MI)
SetVector< MachineInstr * > & getDeferredList()
void insert(MachineInstr *MI)
A pair composed of a register and a sub-register index.
VirtRegInfo - Information about a virtual register used by a set of operands.
bool Reads
Reads - One of the operands read the virtual register.
bool Writes
Writes - One of the operands writes the virtual register.