LLVM 24.0.0git
SIFoldOperands.cpp
Go to the documentation of this file.
1//===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===//
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/// \file
8//===----------------------------------------------------------------------===//
9//
10
11#include "SIFoldOperands.h"
12#include "AMDGPU.h"
13#include "AMDGPULaneMaskUtils.h"
14#include "GCNSubtarget.h"
15#include "SIInstrInfo.h"
17#include "SIRegisterInfo.h"
24
25#define DEBUG_TYPE "si-fold-operands"
26using namespace llvm;
27
28namespace {
29
30/// Track a value we may want to fold into downstream users, applying
31/// subregister extracts along the way.
32struct FoldableDef {
33 union {
34 MachineOperand *OpToFold = nullptr;
35 uint64_t ImmToFold;
36 int FrameIndexToFold;
37 };
38
39 /// Register class of the originally defined value.
40 const TargetRegisterClass *DefRC = nullptr;
41
42 /// Track the original defining instruction for the value.
43 const MachineInstr *DefMI = nullptr;
44
45 /// Subregister to apply to the value at the use point.
46 unsigned DefSubReg = AMDGPU::NoSubRegister;
47
48 /// Kind of value stored in the union.
50
51 FoldableDef() = delete;
52 FoldableDef(MachineOperand &FoldOp, const TargetRegisterClass *DefRC,
53 unsigned DefSubReg = AMDGPU::NoSubRegister)
54 : DefRC(DefRC), DefSubReg(DefSubReg), Kind(FoldOp.getType()) {
55
56 if (FoldOp.isImm()) {
57 ImmToFold = FoldOp.getImm();
58 } else if (FoldOp.isFI()) {
59 FrameIndexToFold = FoldOp.getIndex();
60 } else {
61 assert(FoldOp.isReg() || FoldOp.isGlobal());
62 OpToFold = &FoldOp;
63 }
64
65 DefMI = FoldOp.getParent();
66 }
67
68 FoldableDef(int64_t FoldImm, const TargetRegisterClass *DefRC,
69 unsigned DefSubReg = AMDGPU::NoSubRegister)
70 : ImmToFold(FoldImm), DefRC(DefRC), DefSubReg(DefSubReg),
72
73 /// Copy the current def and apply \p SubReg to the value.
74 FoldableDef getWithSubReg(const SIRegisterInfo &TRI, unsigned SubReg) const {
75 FoldableDef Copy(*this);
76 Copy.DefSubReg = TRI.composeSubRegIndices(DefSubReg, SubReg);
77 return Copy;
78 }
79
80 bool isReg() const { return Kind == MachineOperand::MO_Register; }
81
82 Register getReg() const {
83 assert(isReg());
84 return OpToFold->getReg();
85 }
86
87 unsigned getSubReg() const {
88 assert(isReg());
89 return OpToFold->getSubReg();
90 }
91
92 bool isImm() const { return Kind == MachineOperand::MO_Immediate; }
93
94 bool isFI() const {
95 return Kind == MachineOperand::MO_FrameIndex;
96 }
97
98 int getFI() const {
99 assert(isFI());
100 return FrameIndexToFold;
101 }
102
103 bool isGlobal() const { return Kind == MachineOperand::MO_GlobalAddress; }
104
105 /// Return the effective immediate value defined by this instruction, after
106 /// application of any subregister extracts which may exist between the use
107 /// and def instruction.
108 std::optional<int64_t> getEffectiveImmVal() const {
109 assert(isImm());
110 return SIInstrInfo::extractSubregFromImm(ImmToFold, DefSubReg);
111 }
112
113 /// Check if it is legal to fold this effective value into \p MI's \p OpNo
114 /// operand.
115 bool isOperandLegal(const SIInstrInfo &TII, const MachineInstr &MI,
116 unsigned OpIdx) const {
117 switch (Kind) {
119 std::optional<int64_t> ImmToFold = getEffectiveImmVal();
120 if (!ImmToFold)
121 return false;
122
123 if (!TII.isImmEquivalentToReg(MI, OpIdx, *ImmToFold))
124 return false;
125
126 // TODO: Should verify the subregister index is supported by the class
127 // TODO: Avoid the temporary MachineOperand
128 MachineOperand TmpOp = MachineOperand::CreateImm(*ImmToFold);
129 return TII.isOperandLegal(MI, OpIdx, &TmpOp);
130 }
132 if (DefSubReg != AMDGPU::NoSubRegister)
133 return false;
134 MachineOperand TmpOp = MachineOperand::CreateFI(FrameIndexToFold);
135 return TII.isOperandLegal(MI, OpIdx, &TmpOp);
136 }
137 default:
138 // TODO: Try to apply DefSubReg, for global address we can extract
139 // low/high.
140 if (DefSubReg != AMDGPU::NoSubRegister)
141 return false;
142 return TII.isOperandLegal(MI, OpIdx, OpToFold);
143 }
144
145 llvm_unreachable("covered MachineOperand kind switch");
146 }
147};
148
149struct FoldCandidate {
151 FoldableDef Def;
152 int ShrinkOpcode;
153 unsigned UseOpNo;
154 bool Commuted;
155
156 FoldCandidate(MachineInstr *MI, unsigned OpNo, FoldableDef Def,
157 bool Commuted = false, int ShrinkOp = -1)
158 : UseMI(MI), Def(Def), ShrinkOpcode(ShrinkOp), UseOpNo(OpNo),
159 Commuted(Commuted) {}
160
161 bool isFI() const { return Def.isFI(); }
162
163 int getFI() const {
164 assert(isFI());
165 return Def.FrameIndexToFold;
166 }
167
168 bool isImm() const { return Def.isImm(); }
169
170 bool isReg() const { return Def.isReg(); }
171
172 Register getReg() const { return Def.getReg(); }
173
174 bool isGlobal() const { return Def.isGlobal(); }
175
176 bool needsShrink() const { return ShrinkOpcode != -1; }
177};
178
179class SIFoldOperandsImpl {
180public:
181 MachineFunction *MF;
183 const SIInstrInfo *TII;
184 const SIRegisterInfo *TRI;
185 const GCNSubtarget *ST;
186 const SIMachineFunctionInfo *MFI;
187 const MachineLoopInfo *MLI;
188
189 bool frameIndexMayFold(const MachineInstr &UseMI, int OpNo,
190 const FoldableDef &OpToFold) const;
191
192 // TODO: Just use TII::getVALUOp
193 unsigned convertToVALUOp(unsigned Opc, bool UseVOP3 = false) const {
194 switch (Opc) {
195 case AMDGPU::S_ADD_I32: {
196 if (ST->hasAddNoCarryInsts())
197 return UseVOP3 ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_U32_e32;
198 return UseVOP3 ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
199 }
200 case AMDGPU::S_OR_B32:
201 return UseVOP3 ? AMDGPU::V_OR_B32_e64 : AMDGPU::V_OR_B32_e32;
202 case AMDGPU::S_AND_B32:
203 return UseVOP3 ? AMDGPU::V_AND_B32_e64 : AMDGPU::V_AND_B32_e32;
204 case AMDGPU::S_MUL_I32:
205 return AMDGPU::V_MUL_LO_U32_e64;
206 default:
207 return AMDGPU::INSTRUCTION_LIST_END;
208 }
209 }
210
211 bool foldCopyToVGPROfScalarAddOfFrameIndex(Register DstReg, Register SrcReg,
212 MachineInstr &MI) const;
213
214 bool updateOperand(FoldCandidate &Fold) const;
215
216 bool canUseImmWithOpSel(const MachineInstr *MI, unsigned UseOpNo,
217 int64_t ImmVal) const;
218
219 /// Fold inline constant \p NewImm into \p OpNo so that it reads \p Value.
220 bool tryFoldInlineWithOpSel(MachineInstr &MI, unsigned OpNo, unsigned ModIdx,
221 int64_t NewImm, int64_t Value) const;
222
223 /// Try to shuffle the halves of \p Imm around and leverage op_sel to fold it
224 /// into \p OpNo as an inline constant.
225 bool tryFoldShuffledHalves(MachineInstr &MI, unsigned OpNo, unsigned ModIdx,
226 int64_t Imm) const;
227
228 /// Try to fold immediate \p ImmVal into \p MI's operand at index \p OpNo.
229 bool tryFoldImmWithOpSel(MachineInstr *MI, int OpNo, int64_t ImmVal) const;
230
231 bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
232 MachineInstr *MI, unsigned OpNo,
233 const FoldableDef &OpToFold) const;
234 bool isUseSafeToFold(const MachineInstr &MI,
235 const MachineOperand &UseMO) const;
236 bool isTemporallyDivergentUse(const FoldableDef &OpToFold,
237 const MachineInstr &UseMI) const;
238
239 const TargetRegisterClass *getRegSeqInit(
240 MachineInstr &RegSeq,
241 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs) const;
242
243 const TargetRegisterClass *
244 getRegSeqInit(SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
245 Register UseReg) const;
246
247 std::pair<int64_t, const TargetRegisterClass *>
248 isRegSeqSplat(MachineInstr &RegSeg) const;
249
250 bool tryFoldRegSeqSplat(MachineInstr *UseMI, unsigned UseOpIdx,
251 int64_t SplatVal,
252 const TargetRegisterClass *SplatRC) const;
253
254 bool tryToFoldACImm(const FoldableDef &OpToFold, MachineInstr *UseMI,
255 unsigned UseOpIdx,
256 SmallVectorImpl<FoldCandidate> &FoldList) const;
257 bool foldOperand(FoldableDef OpToFold, MachineInstr *UseMI, int UseOpIdx,
259 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
260
261 struct ANDMaskResult {
262 int64_t Mask;
264 };
265
266 std::optional<ANDMaskResult> getANDMaskRegOperand(MachineInstr &AndMI) const;
267
268 bool tryConstantFoldOp(MachineInstr *MI) const;
269 bool tryFoldCndMask(MachineInstr &MI) const;
270 bool tryFoldRedundantAND(MachineInstr &ChildMI) const;
271 bool tryFoldAndExec(MachineInstr &MI) const;
272 bool tryFoldAndCSelectExec(MachineInstr &MI) const;
273 bool foldInstOperand(MachineInstr &MI, const FoldableDef &OpToFold) const;
274
275 bool foldCopyToAGPRRegSequence(MachineInstr *CopyMI) const;
276 bool tryFoldFoldableCopy(MachineInstr &MI,
277 MachineOperand *&CurrentKnownM0Val) const;
278
279 const MachineOperand *isClamp(const MachineInstr &MI) const;
280 bool tryFoldClamp(MachineInstr &MI);
281
282 std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
283 bool tryFoldOMod(MachineInstr &MI);
284 bool tryFoldSGPRSplatRegSequence(MachineInstr &MI);
285 bool tryFoldRegSequence(MachineInstr &MI);
286 bool tryFoldPhiAGPR(MachineInstr &MI);
287 bool tryFoldLoad(MachineInstr &MI);
288
289 bool tryOptimizeAGPRPhis(MachineBasicBlock &MBB);
290
291public:
292 SIFoldOperandsImpl() = default;
293
294 bool run(MachineFunction &MF, const MachineLoopInfo *MLI);
295};
296
297class SIFoldOperandsLegacy : public MachineFunctionPass {
298public:
299 static char ID;
300
301 SIFoldOperandsLegacy() : MachineFunctionPass(ID) {}
302
303 bool runOnMachineFunction(MachineFunction &MF) override {
304 if (skipFunction(MF.getFunction()))
305 return false;
306 const MachineLoopInfo *MLI =
307 &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
308 return SIFoldOperandsImpl().run(MF, MLI);
309 }
310
311 StringRef getPassName() const override { return "SI Fold Operands"; }
312
313 void getAnalysisUsage(AnalysisUsage &AU) const override {
314 AU.setPreservesCFG();
318 }
319
320 MachineFunctionProperties getRequiredProperties() const override {
321 return MachineFunctionProperties().setIsSSA();
322 }
323};
324
325} // End anonymous namespace.
326
327INITIALIZE_PASS_BEGIN(SIFoldOperandsLegacy, DEBUG_TYPE, "SI Fold Operands",
328 false, false)
330INITIALIZE_PASS_END(SIFoldOperandsLegacy, DEBUG_TYPE, "SI Fold Operands", false,
331 false)
332
333char SIFoldOperandsLegacy::ID = 0;
334
335char &llvm::SIFoldOperandsLegacyID = SIFoldOperandsLegacy::ID;
336
339 const MachineOperand &MO) {
340 const TargetRegisterClass *RC = MRI.getRegClass(MO.getReg());
341 if (const TargetRegisterClass *SubRC =
342 TRI.getSubRegisterClass(RC, MO.getSubReg()))
343 RC = SubRC;
344 return RC;
345}
346
347// Map multiply-accumulate opcode to corresponding multiply-add opcode if any.
348static unsigned macToMad(unsigned Opc) {
349 switch (Opc) {
350 case AMDGPU::V_MAC_F32_e64:
351 return AMDGPU::V_MAD_F32_e64;
352 case AMDGPU::V_MAC_F16_e64:
353 return AMDGPU::V_MAD_F16_e64;
354 case AMDGPU::V_FMAC_F32_e64:
355 return AMDGPU::V_FMA_F32_e64;
356 case AMDGPU::V_FMAC_F16_e64:
357 return AMDGPU::V_FMA_F16_gfx9_e64;
358 case AMDGPU::V_FMAC_F16_t16_e64:
359 return AMDGPU::V_FMA_F16_gfx9_t16_e64;
360 case AMDGPU::V_FMAC_F16_fake16_e64:
361 return AMDGPU::V_FMA_F16_gfx9_fake16_e64;
362 case AMDGPU::V_FMAC_LEGACY_F32_e64:
363 return AMDGPU::V_FMA_LEGACY_F32_e64;
364 case AMDGPU::V_FMAC_F64_e64:
365 return AMDGPU::V_FMA_F64_e64;
366 }
367 return AMDGPU::INSTRUCTION_LIST_END;
368}
369
370// TODO: Add heuristic that the frame index might not fit in the addressing mode
371// immediate offset to avoid materializing in loops.
372bool SIFoldOperandsImpl::frameIndexMayFold(const MachineInstr &UseMI, int OpNo,
373 const FoldableDef &OpToFold) const {
374 if (!OpToFold.isFI())
375 return false;
376
377 const unsigned Opc = UseMI.getOpcode();
378 switch (Opc) {
379 case AMDGPU::S_ADD_I32:
380 case AMDGPU::S_ADD_U32:
381 case AMDGPU::V_ADD_U32_e32:
382 case AMDGPU::V_ADD_CO_U32_e32:
383 // TODO: Possibly relax hasOneUse. It matters more for mubuf, since we have
384 // to insert the wave size shift at every point we use the index.
385 // TODO: Fix depending on visit order to fold immediates into the operand
386 return UseMI.getOperand(OpNo == 1 ? 2 : 1).isImm() &&
387 MRI->hasOneNonDBGUse(UseMI.getOperand(OpNo).getReg());
388 case AMDGPU::V_ADD_U32_e64:
389 case AMDGPU::V_ADD_CO_U32_e64:
390 return UseMI.getOperand(OpNo == 2 ? 3 : 2).isImm() &&
391 MRI->hasOneNonDBGUse(UseMI.getOperand(OpNo).getReg());
392 default:
393 break;
394 }
395
396 if (TII->isMUBUF(UseMI))
397 return OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
398 if (!TII->isFLATScratch(UseMI))
399 return false;
400
401 int SIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
402 if (OpNo == SIdx)
403 return true;
404
405 int VIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
406 return OpNo == VIdx && SIdx == -1;
407}
408
409/// Fold %vgpr = COPY (S_ADD_I32 x, frameindex)
410///
411/// => %vgpr = V_ADD_U32 x, frameindex
412bool SIFoldOperandsImpl::foldCopyToVGPROfScalarAddOfFrameIndex(
413 Register DstReg, Register SrcReg, MachineInstr &MI) const {
414 if (!SrcReg.isVirtual())
415 return false;
416
417 if (TRI->isVGPR(*MRI, DstReg) && TRI->isSGPRReg(*MRI, SrcReg) &&
418 MRI->hasOneNonDBGUse(SrcReg)) {
419 MachineInstr *Def = MRI->getVRegDef(SrcReg);
420 if (!Def || Def->getNumOperands() != 4)
421 return false;
422
423 MachineOperand *Src0 = &Def->getOperand(1);
424 MachineOperand *Src1 = &Def->getOperand(2);
425
426 // TODO: This is profitable with more operand types, and for more
427 // opcodes. But ultimately this is working around poor / nonexistent
428 // regbankselect.
429 if (!Src0->isFI() && !Src1->isFI())
430 return false;
431
432 if (Src0->isFI())
433 std::swap(Src0, Src1);
434
435 const bool UseVOP3 = !Src0->isImm() || TII->isInlineConstant(*Src0);
436 unsigned NewOp = convertToVALUOp(Def->getOpcode(), UseVOP3);
437 if (NewOp == AMDGPU::INSTRUCTION_LIST_END ||
438 !Def->getOperand(3).isDead()) // Check if scc is dead
439 return false;
440
441 MachineBasicBlock *MBB = Def->getParent();
442 const DebugLoc &DL = Def->getDebugLoc();
443 if (NewOp != AMDGPU::V_ADD_CO_U32_e32) {
444 MachineInstrBuilder Add =
445 BuildMI(*MBB, *Def, DL, TII->get(NewOp), DstReg);
446
447 if (Add->getDesc().getNumDefs() == 2) {
448 Register CarryOutReg = MRI->createVirtualRegister(TRI->getBoolRC());
449 Add.addDef(CarryOutReg, RegState::Dead);
450 MRI->setRegAllocationHint(CarryOutReg, 0, TRI->getVCC());
451 }
452
453 Add.add(*Src0).add(*Src1).setMIFlags(Def->getFlags());
454 if (AMDGPU::hasNamedOperand(NewOp, AMDGPU::OpName::clamp))
455 Add.addImm(0);
456
457 Def->eraseFromParent();
458 MI.eraseFromParent();
459 return true;
460 }
461
462 assert(NewOp == AMDGPU::V_ADD_CO_U32_e32);
463
465 MBB->computeRegisterLiveness(TRI, AMDGPU::VCC, *Def, 16);
466 if (Liveness == MachineBasicBlock::LQR_Dead) {
467 // TODO: If src1 satisfies operand constraints, use vop3 version.
468 BuildMI(*MBB, *Def, DL, TII->get(NewOp), DstReg)
469 .add(*Src0)
470 .add(*Src1)
471 .setOperandDead(3) // implicit-def $vcc
472 .setMIFlags(Def->getFlags());
473 Def->eraseFromParent();
474 MI.eraseFromParent();
475 return true;
476 }
477 }
478
479 return false;
480}
481
482bool SIFoldOperandsImpl::canUseImmWithOpSel(const MachineInstr *MI,
483 unsigned UseOpNo,
484 int64_t ImmVal) const {
488 return false;
489
490 if (!TII->getNumOpSelBits(*MI, UseOpNo))
491 return false;
492
493 unsigned Opcode = MI->getOpcode();
494 uint8_t OpType = TII->get(Opcode).operands()[UseOpNo].OperandType;
495
496 if (OpType == AMDGPU::OPERAND_REG_IMM_BF16 ||
498 int16_t Half = TII->getSrcOperandValue(*MI, UseOpNo, ImmVal);
499 return AMDGPU::isInlinableLiteralBF16(Half, ST->hasInv2PiInlineImm());
500 }
501
503 return false;
504
505 switch (OpType) {
506 default:
507 return false;
515 // VOP3 packed instructions ignore op_sel source modifiers, we cannot encode
516 // two different constants.
518 static_cast<uint16_t>(ImmVal) != static_cast<uint16_t>(ImmVal >> 16))
519 return false;
520 break;
521 }
522
523 return true;
524}
525
526bool SIFoldOperandsImpl::tryFoldInlineWithOpSel(MachineInstr &MI, unsigned OpNo,
527 unsigned ModIdx, int64_t NewImm,
528 int64_t Value) const {
529 uint8_t OpType = MI.getDesc().operands()[OpNo].OperandType;
530 if (!TII->isInlineConstant(NewImm, OpType))
531 return false;
532
533 MachineOperand &Mod = MI.getOperand(ModIdx);
534 std::optional<unsigned> NewModVal =
535 TII->getImmOpSelForValue(MI, OpNo, NewImm, Value, Mod.getImm());
536 if (!NewModVal ||
537 !TII->isImmOperandLegalWithMods(MI, OpNo, NewImm, *NewModVal))
538 return false;
539
540 Mod.setImm(*NewModVal);
541 MI.getOperand(OpNo).ChangeToImmediate(NewImm);
542 return true;
543}
544
545bool SIFoldOperandsImpl::tryFoldShuffledHalves(MachineInstr &MI, unsigned OpNo,
546 unsigned ModIdx,
547 int64_t Imm) const {
548 uint16_t Lo = static_cast<uint16_t>(Imm);
549 uint16_t Hi = static_cast<uint16_t>(Imm >> 16);
550 if (tryFoldInlineWithOpSel(MI, OpNo, ModIdx, Imm, Imm))
551 return true;
552
553 if (Lo != Hi) {
554 int64_t Swapped = SignExtend64<32>((static_cast<uint32_t>(Lo) << 16) | Hi);
555 return tryFoldInlineWithOpSel(MI, OpNo, ModIdx, Swapped, Imm);
556 }
557
558 if (tryFoldInlineWithOpSel(MI, OpNo, ModIdx, Lo, Imm))
559 return true;
560
561 if (static_cast<int16_t>(Lo) < 0 &&
562 tryFoldInlineWithOpSel(MI, OpNo, ModIdx, static_cast<int16_t>(Lo), Imm))
563 return true;
564
565 int64_t HiOnly = SignExtend64<32>(static_cast<uint32_t>(Lo) << 16);
566 return tryFoldInlineWithOpSel(MI, OpNo, ModIdx, HiOnly, Imm);
567}
568
569bool SIFoldOperandsImpl::tryFoldImmWithOpSel(MachineInstr *MI, int OpNo,
570 int64_t ImmVal) const {
571 unsigned Opcode = MI->getOpcode();
572
573 // Refer to op_sel/op_sel_hi and check if we can change the immediate and
574 // op_sel in a way that allows an inline constant.
575 AMDGPU::OpName ModName = AMDGPU::OpName::NUM_OPERAND_NAMES;
576 unsigned SrcIdx = ~0;
577 if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0)) {
578 ModName = AMDGPU::OpName::src0_modifiers;
579 SrcIdx = 0;
580 } else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1)) {
581 ModName = AMDGPU::OpName::src1_modifiers;
582 SrcIdx = 1;
583 } else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2)) {
584 ModName = AMDGPU::OpName::src2_modifiers;
585 SrcIdx = 2;
586 }
587 assert(ModName != AMDGPU::OpName::NUM_OPERAND_NAMES);
588 int ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModName);
589 if (ModIdx == -1)
590 return false;
591
592 unsigned ModVal = MI->getOperand(ModIdx).getImm();
593 int64_t Imm = TII->getSrcOperandValue(*MI, OpNo, ImmVal, ModVal);
594
595 // Prefer the original immediate, keeping its op_sel if possible. The main
596 // motivation for this is to avoid unintuitive uses of opsel.
597 if (tryFoldInlineWithOpSel(*MI, OpNo, ModIdx, ImmVal, Imm))
598 return true;
599
600 if (tryFoldShuffledHalves(*MI, OpNo, ModIdx, Imm))
601 return true;
602
603 // Replace integer addition by subtraction and vice versa if it allows
604 // folding the immediate to an inline constant.
605 //
606 // We should only ever get here for SrcIdx == 1 due to canonicalization
607 // earlier in the pipeline, but we double-check here to be safe / fully
608 // general.
609 bool IsUAdd = Opcode == AMDGPU::V_PK_ADD_U16;
610 bool IsUSub = Opcode == AMDGPU::V_PK_SUB_U16;
611 if (SrcIdx == 1 && (IsUAdd || IsUSub)) {
612 unsigned ClampIdx =
613 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::clamp);
614 bool Clamp = MI->getOperand(ClampIdx).getImm() != 0;
615
616 if (!Clamp) {
617 uint16_t NegLo = -static_cast<uint16_t>(Imm);
618 uint16_t NegHi = -static_cast<uint16_t>(Imm >> 16);
619 int64_t NegImm =
620 SignExtend64<32>((static_cast<uint32_t>(NegHi) << 16) | NegLo);
621
622 if (tryFoldShuffledHalves(*MI, OpNo, ModIdx, NegImm)) {
623 unsigned NegOpcode =
624 IsUAdd ? AMDGPU::V_PK_SUB_U16 : AMDGPU::V_PK_ADD_U16;
625 MI->setDesc(TII->get(NegOpcode));
626 return true;
627 }
628 }
629 }
630
631 return false;
632}
633
634bool SIFoldOperandsImpl::updateOperand(FoldCandidate &Fold) const {
635 MachineInstr *MI = Fold.UseMI;
636 MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
637 assert(Old.isReg());
638
639 std::optional<int64_t> ImmVal;
640 if (Fold.isImm())
641 ImmVal = Fold.Def.getEffectiveImmVal();
642
643 if (ImmVal && canUseImmWithOpSel(Fold.UseMI, Fold.UseOpNo, *ImmVal)) {
644 if (tryFoldImmWithOpSel(Fold.UseMI, Fold.UseOpNo, *ImmVal))
645 return true;
646
647 // We can't represent the candidate as an inline constant. Try as a literal
648 // with the original opsel, checking constant bus limitations.
649 if (!Fold.Def.isOperandLegal(*TII, *MI, Fold.UseOpNo))
650 return false;
651
652 Old.ChangeToImmediate(*ImmVal);
653 return true;
654 }
655
656 if ((Fold.isImm() || Fold.isFI() || Fold.isGlobal()) && Fold.needsShrink()) {
657 MachineBasicBlock *MBB = MI->getParent();
658 auto Liveness = MBB->computeRegisterLiveness(TRI, AMDGPU::VCC, MI, 16);
659 if (Liveness != MachineBasicBlock::LQR_Dead) {
660 LLVM_DEBUG(dbgs() << "Not shrinking due to live vcc: " << *MI);
661 return false;
662 }
663
664 int Op32 = Fold.ShrinkOpcode;
665 MachineOperand &Dst0 = MI->getOperand(0);
666 MachineOperand &Dst1 = MI->getOperand(1);
667 assert(Dst0.isDef() && Dst1.isDef());
668
669 bool HaveNonDbgCarryUse = !MRI->use_nodbg_empty(Dst1.getReg());
670
671 const TargetRegisterClass *Dst0RC = MRI->getRegClass(Dst0.getReg());
672 Register NewReg0 = MRI->createVirtualRegister(Dst0RC);
673
674 MachineInstr *Inst32 = TII->buildShrunkInst(*MI, Op32);
675
676 if (HaveNonDbgCarryUse) {
677 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(AMDGPU::COPY),
678 Dst1.getReg())
679 .addReg(AMDGPU::VCC, RegState::Kill);
680 } else {
681 // We only reach here when the carry-out vcc is dead so propagate the dead
682 // flag.
683 Inst32->getOperand(3).setIsDead();
684 }
685
686 // Keep the old instruction around to avoid breaking iterators, but
687 // replace it with a dummy instruction to remove uses.
688 //
689 // FIXME: We should not invert how this pass looks at operands to avoid
690 // this. Should track set of foldable movs instead of looking for uses
691 // when looking at a use.
692 Dst0.setReg(NewReg0);
693 for (unsigned I = MI->getNumOperands() - 1; I > 0; --I)
694 MI->removeOperand(I);
695 MI->setDesc(TII->get(AMDGPU::IMPLICIT_DEF));
696
697 if (Fold.Commuted)
698 TII->commuteInstruction(*Inst32, false);
699 return true;
700 }
701
702 assert(!Fold.needsShrink() && "not handled");
703
704 if (ImmVal) {
705 if (Old.isTied()) {
706 int NewMFMAOpc = AMDGPU::getMFMAEarlyClobberOp(MI->getOpcode());
707 if (NewMFMAOpc == -1)
708 return false;
709 MI->setDesc(TII->get(NewMFMAOpc));
710 MI->untieRegOperand(0);
711 const MCInstrDesc &MCID = MI->getDesc();
712 for (unsigned I = 0; I < MI->getNumDefs(); ++I)
714 MI->getOperand(I).setIsEarlyClobber(true);
715 }
716
717 // TODO: Should we try to avoid adding this to the candidate list?
718 MachineOperand New = MachineOperand::CreateImm(*ImmVal);
719 int OpNo = MI->getOperandNo(&Old);
720 if (!TII->isOperandLegal(*MI, OpNo, &New))
721 return false;
722
723 Old.ChangeToImmediate(*ImmVal);
724 return true;
725 }
726
727 if (Fold.isGlobal()) {
728 Old.ChangeToGA(Fold.Def.OpToFold->getGlobal(),
729 Fold.Def.OpToFold->getOffset(),
730 Fold.Def.OpToFold->getTargetFlags());
731 return true;
732 }
733
734 if (Fold.isFI()) {
735 Old.ChangeToFrameIndex(Fold.getFI());
736 return true;
737 }
738
739 MachineOperand *New = Fold.Def.OpToFold;
740
741 // Verify the register is compatible with the operand.
742 if (const TargetRegisterClass *OpRC =
743 TII->getRegClass(MI->getDesc(), Fold.UseOpNo)) {
744 const TargetRegisterClass *NewRC =
745 TRI->getRegClassForReg(*MRI, New->getReg());
746
747 const TargetRegisterClass *ConstrainRC = OpRC;
748 if (New->getSubReg()) {
749 ConstrainRC =
750 TRI->getMatchingSuperRegClass(NewRC, OpRC, New->getSubReg());
751
752 if (!ConstrainRC)
753 return false;
754 }
755
756 if (New->getReg().isVirtual() &&
757 !MRI->constrainRegClass(New->getReg(), ConstrainRC)) {
758 LLVM_DEBUG(dbgs() << "Cannot constrain " << printReg(New->getReg(), TRI)
759 << TRI->getRegClassName(ConstrainRC) << '\n');
760 return false;
761 }
762 }
763
764 // Rework once the VS_16 register class is updated to include proper
765 // 16-bit SGPRs instead of 32-bit ones.
766 if (Old.getSubReg() == AMDGPU::lo16 && TRI->isSGPRReg(*MRI, New->getReg()))
767 Old.setSubReg(AMDGPU::NoSubRegister);
768 if (New->getReg().isPhysical()) {
769 Old.substPhysReg(New->getReg(), *TRI);
770 } else {
771 Register OldReg = Old.getReg();
772 Old.substVirtReg(New->getReg(), New->getSubReg(), *TRI);
773 Old.setIsUndef(New->isUndef());
774
775 // If MI is in a BUNDLE, also update header's matching implicit use.
776 if (MI->isBundledWithPred()) {
777 MachineInstr &Header = *getBundleStart(MI->getIterator());
778 for (MachineOperand &MO : Header.operands()) {
779 if (MO.getReg() == OldReg) {
780 MO.setReg(New->getReg());
781 MO.setSubReg(New->getSubReg());
782 }
783 }
784 }
785 }
786 return true;
787}
788
790 FoldCandidate &&Entry) {
791 // Skip additional folding on the same operand.
792 for (FoldCandidate &Fold : FoldList)
793 if (Fold.UseMI == Entry.UseMI && Fold.UseOpNo == Entry.UseOpNo)
794 return;
795 LLVM_DEBUG(dbgs() << "Append " << (Entry.Commuted ? "commuted" : "normal")
796 << " operand " << Entry.UseOpNo << "\n " << *Entry.UseMI);
797 FoldList.push_back(Entry);
798}
799
801 MachineInstr *MI, unsigned OpNo,
802 const FoldableDef &FoldOp,
803 bool Commuted = false, int ShrinkOp = -1) {
804 appendFoldCandidate(FoldList,
805 FoldCandidate(MI, OpNo, FoldOp, Commuted, ShrinkOp));
806}
807
808bool SIFoldOperandsImpl::tryAddToFoldList(
809 SmallVectorImpl<FoldCandidate> &FoldList, MachineInstr *MI, unsigned OpNo,
810 const FoldableDef &OpToFold) const {
811 const unsigned Opc = MI->getOpcode();
812
813 auto tryToFoldAsFMAAKorMK = [&]() {
814 if (!OpToFold.isImm())
815 return false;
816
817 const bool TryAK = OpNo == 3;
818 const unsigned NewOpc = TryAK ? AMDGPU::S_FMAAK_F32 : AMDGPU::S_FMAMK_F32;
819 MI->setDesc(TII->get(NewOpc));
820
821 // We have to fold into operand which would be Imm not into OpNo.
822 bool FoldAsFMAAKorMK =
823 tryAddToFoldList(FoldList, MI, TryAK ? 3 : 2, OpToFold);
824 if (FoldAsFMAAKorMK) {
825 // Untie Src2 of fmac.
826 MI->untieRegOperand(3);
827 // For fmamk swap operands 1 and 2 if OpToFold was meant for operand 1.
828 if (OpNo == 1) {
829 MachineOperand &Op1 = MI->getOperand(1);
830 MachineOperand &Op2 = MI->getOperand(2);
831 Register OldReg = Op1.getReg();
832 // Operand 2 might be an inlinable constant
833 if (Op2.isImm()) {
834 Op1.ChangeToImmediate(Op2.getImm());
835 Op2.ChangeToRegister(OldReg, false);
836 } else {
837 Op1.setReg(Op2.getReg());
838 Op2.setReg(OldReg);
839 }
840 }
841 return true;
842 }
843 MI->setDesc(TII->get(Opc));
844 return false;
845 };
846
847 bool IsLegal = OpToFold.isOperandLegal(*TII, *MI, OpNo);
848 if (!IsLegal && OpToFold.isImm()) {
849 if (std::optional<int64_t> ImmVal = OpToFold.getEffectiveImmVal())
850 IsLegal = canUseImmWithOpSel(MI, OpNo, *ImmVal);
851 }
852
853 if (!IsLegal) {
854 // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
855 unsigned NewOpc = macToMad(Opc);
856 if (NewOpc != AMDGPU::INSTRUCTION_LIST_END) {
857 // Check if changing this to a v_mad_{f16, f32} instruction will allow us
858 // to fold the operand.
859 MI->setDesc(TII->get(NewOpc));
860 bool AddOpSel = !AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel) &&
861 AMDGPU::hasNamedOperand(NewOpc, AMDGPU::OpName::op_sel);
862 if (AddOpSel)
863 MI->addOperand(MachineOperand::CreateImm(0));
864 bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold);
865 if (FoldAsMAD) {
866 MI->untieRegOperand(OpNo);
867 return true;
868 }
869 if (AddOpSel)
870 MI->removeOperand(MI->getNumExplicitOperands() - 1);
871 MI->setDesc(TII->get(Opc));
872 }
873
874 // Special case for s_fmac_f32 if we are trying to fold into Src2.
875 // By transforming into fmaak we can untie Src2 and make folding legal.
876 if (Opc == AMDGPU::S_FMAC_F32 && OpNo == 3) {
877 if (tryToFoldAsFMAAKorMK())
878 return true;
879 }
880
881 // Inlineable constant might have been folded into Imm operand of fmaak or
882 // fmamk and we are trying to fold a non-inlinable constant.
883 if ((Opc == AMDGPU::S_FMAAK_F32 || Opc == AMDGPU::S_FMAMK_F32) &&
884 OpToFold.isImm()) {
885 std::optional<int64_t> ImmVal = OpToFold.getEffectiveImmVal();
886 if (ImmVal && !TII->isInlineConstant(*MI, OpNo, *ImmVal)) {
887 unsigned ImmIdx = Opc == AMDGPU::S_FMAAK_F32 ? 3 : 2;
888 MachineOperand &OpImm = MI->getOperand(ImmIdx);
889 if (!OpImm.isReg() &&
890 TII->isInlineConstant(*MI, MI->getOperand(OpNo), OpImm))
891 return tryToFoldAsFMAAKorMK();
892 }
893 }
894
895 // Special case for s_setreg_b32
896 if (OpToFold.isImm()) {
897 unsigned ImmOpc = 0;
898 if (Opc == AMDGPU::S_SETREG_B32)
899 ImmOpc = AMDGPU::S_SETREG_IMM32_B32;
900 else if (Opc == AMDGPU::S_SETREG_B32_mode)
901 ImmOpc = AMDGPU::S_SETREG_IMM32_B32_mode;
902 if (ImmOpc) {
903 MI->setDesc(TII->get(ImmOpc));
904 appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
905 return true;
906 }
907 }
908
909 // Operand is not legal, so try to commute the instruction to
910 // see if this makes it possible to fold.
911 unsigned CommuteOpNo = TargetInstrInfo::CommuteAnyOperandIndex;
912 bool CanCommute = TII->findCommutedOpIndices(*MI, OpNo, CommuteOpNo);
913 if (!CanCommute)
914 return false;
915
916 MachineOperand &Op = MI->getOperand(OpNo);
917 MachineOperand &CommutedOp = MI->getOperand(CommuteOpNo);
918
919 // One of operands might be an Imm operand, and OpNo may refer to it after
920 // the call of commuteInstruction() below. Such situations are avoided
921 // here explicitly as OpNo must be a register operand to be a candidate
922 // for memory folding.
923 if (!Op.isReg() || !CommutedOp.isReg())
924 return false;
925
926 // The same situation with an immediate could reproduce if both inputs are
927 // the same register.
928 if (Op.isReg() && CommutedOp.isReg() &&
929 (Op.getReg() == CommutedOp.getReg() &&
930 Op.getSubReg() == CommutedOp.getSubReg()))
931 return false;
932
933 if (!TII->commuteInstruction(*MI, false, OpNo, CommuteOpNo))
934 return false;
935
936 int Op32 = -1;
937 if (!OpToFold.isOperandLegal(*TII, *MI, CommuteOpNo)) {
938 if ((Opc != AMDGPU::V_ADD_CO_U32_e64 && Opc != AMDGPU::V_SUB_CO_U32_e64 &&
939 Opc != AMDGPU::V_SUBREV_CO_U32_e64) || // FIXME
940 (!OpToFold.isImm() && !OpToFold.isFI() && !OpToFold.isGlobal())) {
941 TII->commuteInstruction(*MI, false, OpNo, CommuteOpNo);
942 return false;
943 }
944
945 // Verify the other operand is a VGPR, otherwise we would violate the
946 // constant bus restriction.
947 MachineOperand &OtherOp = MI->getOperand(OpNo);
948 if (!OtherOp.isReg() ||
949 !TII->getRegisterInfo().isVGPR(*MRI, OtherOp.getReg()))
950 return false;
951
952 assert(MI->getOperand(1).isDef());
953
954 // Make sure to get the 32-bit version of the commuted opcode.
955 unsigned MaybeCommutedOpc = MI->getOpcode();
956 Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc);
957 }
958
959 appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, /*Commuted=*/true,
960 Op32);
961 return true;
962 }
963
964 // Special case for s_fmac_f32 if we are trying to fold into Src0 or Src1.
965 // By changing into fmamk we can untie Src2.
966 // If folding for Src0 happens first and it is identical operand to Src1 we
967 // should avoid transforming into fmamk which requires commuting as it would
968 // cause folding into Src1 to fail later on due to wrong OpNo used.
969 if (Opc == AMDGPU::S_FMAC_F32 &&
970 (OpNo != 1 || !MI->getOperand(1).isIdenticalTo(MI->getOperand(2)))) {
971 if (tryToFoldAsFMAAKorMK())
972 return true;
973 }
974
975 appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
976 return true;
977}
978
979bool SIFoldOperandsImpl::isUseSafeToFold(const MachineInstr &MI,
980 const MachineOperand &UseMO) const {
981 // Operands of SDWA instructions must be registers.
982 return !TII->isSDWA(MI);
983}
984
985// Returns true if any instruction in \p L modifies EXEC.
986static bool loopModifiesExec(const MachineLoop &L, const SIRegisterInfo &TRI) {
987 for (const MachineBasicBlock *MBB : L.getBlocks())
988 for (const MachineInstr &MI : *MBB)
989 if (MI.modifiesRegister(TRI.getExec(), &TRI))
990 return true;
991 return false;
992}
993
994// An SGPR->VGPR copy inside a divergent loop latches each lane value as it
995// exits. Folding its scalar source into a use after the loop would make every
996// lane read the same reconverged value, so do not fold across the loop exit.
997bool SIFoldOperandsImpl::isTemporallyDivergentUse(
998 const FoldableDef &OpToFold, const MachineInstr &UseMI) const {
999 if (!OpToFold.isReg())
1000 return false;
1001 const MachineInstr *DefMI = OpToFold.DefMI;
1002 if (!DefMI || !DefMI->isCopy() ||
1003 TRI->isSGPRReg(*MRI, DefMI->getOperand(0).getReg()) ||
1004 !TRI->isSGPRReg(*MRI, OpToFold.getReg()))
1005 return false;
1006 const MachineLoop *DefLoop = MLI->getLoopFor(DefMI->getParent());
1007 return DefLoop && !DefLoop->contains(UseMI.getParent()) &&
1008 loopModifiesExec(*DefLoop, *TRI);
1009}
1010
1012 const MachineRegisterInfo &MRI,
1013 Register SrcReg) {
1014 MachineOperand *Sub = nullptr;
1015 for (MachineInstr *SubDef = MRI.getVRegDef(SrcReg);
1016 SubDef && TII.isFoldableCopy(*SubDef);
1017 SubDef = MRI.getVRegDef(Sub->getReg())) {
1018 unsigned SrcIdx = TII.getFoldableCopySrcIdx(*SubDef);
1019 MachineOperand &SrcOp = SubDef->getOperand(SrcIdx);
1020
1021 if (SrcOp.isImm())
1022 return &SrcOp;
1023 if (!SrcOp.isReg() || SrcOp.getReg().isPhysical())
1024 break;
1025 Sub = &SrcOp;
1026 // TODO: Support compose
1027 if (SrcOp.getSubReg())
1028 break;
1029 }
1030
1031 return Sub;
1032}
1033
1034const TargetRegisterClass *SIFoldOperandsImpl::getRegSeqInit(
1035 MachineInstr &RegSeq,
1036 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs) const {
1037
1038 assert(RegSeq.isRegSequence());
1039
1040 const TargetRegisterClass *RC = nullptr;
1041
1042 for (unsigned I = 1, E = RegSeq.getNumExplicitOperands(); I != E; I += 2) {
1043 MachineOperand &SrcOp = RegSeq.getOperand(I);
1044 if (SrcOp.getReg().isPhysical())
1045 return nullptr;
1046 unsigned SubRegIdx = RegSeq.getOperand(I + 1).getImm();
1047
1048 // Only accept reg_sequence with uniform reg class inputs for simplicity.
1049 const TargetRegisterClass *OpRC = getRegOpRC(*MRI, *TRI, SrcOp);
1050 if (!RC)
1051 RC = OpRC;
1052 else if (!TRI->getCommonSubClass(RC, OpRC))
1053 return nullptr;
1054
1055 if (SrcOp.getSubReg()) {
1056 // TODO: Handle subregister compose
1057 Defs.emplace_back(&SrcOp, SubRegIdx);
1058 continue;
1059 }
1060
1061 MachineOperand *DefSrc = lookUpCopyChain(*TII, *MRI, SrcOp.getReg());
1062 if (DefSrc && (DefSrc->isReg() || DefSrc->isImm())) {
1063 Defs.emplace_back(DefSrc, SubRegIdx);
1064 continue;
1065 }
1066
1067 Defs.emplace_back(&SrcOp, SubRegIdx);
1068 }
1069
1070 return RC;
1071}
1072
1073// Find a def of the UseReg, check if it is a reg_sequence and find initializers
1074// for each subreg, tracking it to an immediate if possible. Returns the
1075// register class of the inputs on success.
1076const TargetRegisterClass *SIFoldOperandsImpl::getRegSeqInit(
1077 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
1078 Register UseReg) const {
1079 MachineInstr *Def = MRI->getVRegDef(UseReg);
1080 if (!Def || !Def->isRegSequence())
1081 return nullptr;
1082
1083 return getRegSeqInit(*Def, Defs);
1084}
1085
1086std::pair<int64_t, const TargetRegisterClass *>
1087SIFoldOperandsImpl::isRegSeqSplat(MachineInstr &RegSeq) const {
1089 const TargetRegisterClass *SrcRC = getRegSeqInit(RegSeq, Defs);
1090 if (!SrcRC)
1091 return {};
1092
1093 bool TryToMatchSplat64 = false;
1094
1095 std::optional<int64_t> Imm;
1096 for (unsigned I = 0, E = Defs.size(); I != E; ++I) {
1097 const MachineOperand *Op = Defs[I].first;
1098 if (!Op->isImm()) {
1099 if (Op->isReg()) {
1100 MachineInstr *Def = MRI->getVRegDef(Op->getReg());
1101 if (!Def || Def->isImplicitDef())
1102 continue;
1103 }
1104 return {};
1105 }
1106
1107 int64_t SubImm = Op->getImm();
1108 if (!Imm) {
1109 Imm = SubImm;
1110 continue;
1111 }
1112
1113 if (Imm != SubImm) {
1114 if (I == 1 && (E & 1) == 0) {
1115 // If we have an even number of inputs, there's a chance this is a
1116 // 64-bit element splat broken into 32-bit pieces.
1117 TryToMatchSplat64 = true;
1118 break;
1119 }
1120
1121 return {}; // Can only fold splat constants
1122 }
1123 }
1124
1125 if (!TryToMatchSplat64) {
1126 if (Imm)
1127 return {*Imm, SrcRC};
1128 return {};
1129 }
1130
1131 // Fallback to recognizing 64-bit splats broken into 32-bit pieces
1132 // (i.e. recognize every other other element is 0 for 64-bit immediates)
1133 int64_t SplatVal64;
1134 for (unsigned I = 0, E = Defs.size(); I != E; I += 2) {
1135 const MachineOperand *Op0 = Defs[I].first;
1136 const MachineOperand *Op1 = Defs[I + 1].first;
1137
1138 if (!Op0->isImm() || !Op1->isImm())
1139 return {};
1140
1141 unsigned SubReg0 = Defs[I].second;
1142 unsigned SubReg1 = Defs[I + 1].second;
1143
1144 // Assume we're going to generally encounter reg_sequences with sorted
1145 // subreg indexes, so reject any that aren't consecutive.
1146 if (TRI->getChannelFromSubReg(SubReg0) + 1 !=
1147 TRI->getChannelFromSubReg(SubReg1))
1148 return {};
1149
1150 if (TRI->getSubRegIdxSize(SubReg0) != 32)
1151 return {};
1152
1153 int64_t MergedVal = Make_64(Op1->getImm(), Op0->getImm());
1154 if (I == 0)
1155 SplatVal64 = MergedVal;
1156 else if (SplatVal64 != MergedVal)
1157 return {};
1158 }
1159
1160 const TargetRegisterClass *RC64 = TRI->getSubRegisterClass(
1161 MRI->getRegClass(RegSeq.getOperand(0).getReg()), AMDGPU::sub0_sub1);
1162
1163 return {SplatVal64, RC64};
1164}
1165
1166bool SIFoldOperandsImpl::tryFoldRegSeqSplat(
1167 MachineInstr *UseMI, unsigned UseOpIdx, int64_t SplatVal,
1168 const TargetRegisterClass *SplatRC) const {
1169 const MCInstrDesc &Desc = UseMI->getDesc();
1170 if (UseOpIdx >= Desc.getNumOperands())
1171 return false;
1172
1173 // Filter out unhandled pseudos.
1174 if (!AMDGPU::isSISrcOperand(Desc, UseOpIdx))
1175 return false;
1176
1177 int16_t RCID = TII->getOpRegClassID(Desc.operands()[UseOpIdx]);
1178 if (RCID == -1)
1179 return false;
1180
1181 const TargetRegisterClass *OpRC = TRI->getRegClass(RCID);
1182
1183 // Special case 0/-1, since when interpreted as a 64-bit element both halves
1184 // have the same bits. These are the only cases where a splat has the same
1185 // interpretation for 32-bit and 64-bit splats.
1186 if (SplatVal != 0 && SplatVal != -1) {
1187 // We need to figure out the scalar type read by the operand. e.g. the MFMA
1188 // operand will be AReg_128, and we want to check if it's compatible with an
1189 // AReg_32 constant.
1190 uint8_t OpTy = Desc.operands()[UseOpIdx].OperandType;
1191 switch (OpTy) {
1197 OpRC = TRI->getSubRegisterClass(OpRC, AMDGPU::sub0);
1198 break;
1204 OpRC = TRI->getSubRegisterClass(OpRC, AMDGPU::sub0_sub1);
1205 break;
1206 default:
1207 return false;
1208 }
1209
1210 if (!TRI->getCommonSubClass(OpRC, SplatRC))
1211 return false;
1212 }
1213
1214 MachineOperand TmpOp = MachineOperand::CreateImm(SplatVal);
1215 if (!TII->isOperandLegal(*UseMI, UseOpIdx, &TmpOp))
1216 return false;
1217
1218 return true;
1219}
1220
1221bool SIFoldOperandsImpl::tryToFoldACImm(
1222 const FoldableDef &OpToFold, MachineInstr *UseMI, unsigned UseOpIdx,
1223 SmallVectorImpl<FoldCandidate> &FoldList) const {
1224 const MCInstrDesc &Desc = UseMI->getDesc();
1225 if (UseOpIdx >= Desc.getNumOperands())
1226 return false;
1227
1228 // Filter out unhandled pseudos.
1229 if (!AMDGPU::isSISrcOperand(Desc, UseOpIdx))
1230 return false;
1231
1232 if (OpToFold.isImm() && OpToFold.isOperandLegal(*TII, *UseMI, UseOpIdx)) {
1233 appendFoldCandidate(FoldList, UseMI, UseOpIdx, OpToFold);
1234 return true;
1235 }
1236
1237 return false;
1238}
1239
1240bool SIFoldOperandsImpl::foldOperand(
1241 FoldableDef OpToFold, MachineInstr *UseMI, int UseOpIdx,
1242 SmallVectorImpl<FoldCandidate> &FoldList,
1243 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
1244 bool Changed = false;
1245 const MachineOperand *UseOp = &UseMI->getOperand(UseOpIdx);
1246
1247 if (!isUseSafeToFold(*UseMI, *UseOp))
1248 return Changed;
1249
1250 if (isTemporallyDivergentUse(OpToFold, *UseMI))
1251 return Changed;
1252
1253 // FIXME: Fold operands with subregs.
1254 if (UseOp->isReg() && OpToFold.isReg()) {
1255 if (UseOp->isImplicit())
1256 return Changed;
1257 // Allow folding from SGPRs to 16-bit VGPRs.
1258 if (UseOp->getSubReg() != AMDGPU::NoSubRegister &&
1259 (UseOp->getSubReg() != AMDGPU::lo16 ||
1260 !TRI->isSGPRReg(*MRI, OpToFold.getReg())))
1261 return Changed;
1262 }
1263
1264 // Special case for REG_SEQUENCE: We can't fold literals into
1265 // REG_SEQUENCE instructions, so we have to fold them into the
1266 // uses of REG_SEQUENCE.
1267 if (UseMI->isRegSequence()) {
1268 Register RegSeqDstReg = UseMI->getOperand(0).getReg();
1269 unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
1270
1271 int64_t SplatVal;
1272 const TargetRegisterClass *SplatRC;
1273 std::tie(SplatVal, SplatRC) = isRegSeqSplat(*UseMI);
1274
1275 // Grab the use operands first
1278 for (unsigned I = 0; I != UsesToProcess.size(); ++I) {
1279 MachineOperand *RSUse = UsesToProcess[I];
1280 MachineInstr *RSUseMI = RSUse->getParent();
1281 unsigned OpNo = RSUseMI->getOperandNo(RSUse);
1282
1283 if (SplatRC) {
1284 if (RSUseMI->isCopy()) {
1285 Register DstReg = RSUseMI->getOperand(0).getReg();
1286 append_range(UsesToProcess,
1288 continue;
1289 }
1290 if (tryFoldRegSeqSplat(RSUseMI, OpNo, SplatVal, SplatRC)) {
1291 FoldableDef SplatDef(SplatVal, SplatRC);
1292 appendFoldCandidate(FoldList, RSUseMI, OpNo, SplatDef);
1293 Changed = true;
1294 continue;
1295 }
1296 }
1297
1298 // TODO: Handle general compose
1299 if (RSUse->getSubReg() != RegSeqDstSubReg)
1300 continue;
1301
1302 // FIXME: We should avoid recursing here. There should be a cleaner split
1303 // between the in-place mutations and adding to the fold list.
1304 Changed |= foldOperand(OpToFold, RSUseMI, RSUseMI->getOperandNo(RSUse),
1305 FoldList, CopiesToReplace);
1306 }
1307
1308 return Changed;
1309 }
1310
1311 if (tryToFoldACImm(OpToFold, UseMI, UseOpIdx, FoldList))
1312 return true;
1313
1314 if (frameIndexMayFold(*UseMI, UseOpIdx, OpToFold)) {
1315 // Verify that this is a stack access.
1316 // FIXME: Should probably use stack pseudos before frame lowering.
1317
1318 if (TII->isMUBUF(*UseMI)) {
1319 if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() !=
1320 MFI->getScratchRSrcReg())
1321 return Changed;
1322
1323 // Ensure this is either relative to the current frame or the current
1324 // wave.
1325 MachineOperand &SOff =
1326 *TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset);
1327 if (!SOff.isImm() || SOff.getImm() != 0)
1328 return Changed;
1329 }
1330
1331 const unsigned Opc = UseMI->getOpcode();
1332 if (TII->isFLATScratch(*UseMI) &&
1333 AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::vaddr) &&
1334 !AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::saddr)) {
1335 unsigned NewOpc = AMDGPU::getFlatScratchInstSSfromSV(Opc);
1336 unsigned CPol =
1337 TII->getNamedOperand(*UseMI, AMDGPU::OpName::cpol)->getImm();
1338 if ((CPol & AMDGPU::CPol::SCAL) &&
1340 return Changed;
1341
1342 UseMI->setDesc(TII->get(NewOpc));
1343 }
1344
1345 // A frame index will resolve to a positive constant, so it should always be
1346 // safe to fold the addressing mode, even pre-GFX9.
1347 UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getFI());
1348
1349 return true;
1350 }
1351
1352 bool FoldingImmLike =
1353 OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1354
1355 if (FoldingImmLike && UseMI->isCopy()) {
1356 Register DestReg = UseMI->getOperand(0).getReg();
1357 Register SrcReg = UseMI->getOperand(1).getReg();
1358 unsigned UseSubReg = UseMI->getOperand(1).getSubReg();
1359 assert(SrcReg.isVirtual());
1360
1361 const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
1362
1363 // Don't fold into a copy to a physical register with the same class. Doing
1364 // so would interfere with the register coalescer's logic which would avoid
1365 // redundant initializations.
1366 if (DestReg.isPhysical() && SrcRC->contains(DestReg))
1367 return Changed;
1368
1369 const TargetRegisterClass *DestRC = TRI->getRegClassForReg(*MRI, DestReg);
1370 // In order to fold immediates into copies, we need to change the copy to a
1371 // MOV. Find a compatible mov instruction with the value.
1372 for (unsigned MovOp :
1373 {AMDGPU::S_MOV_B32, AMDGPU::V_MOV_B32_e32, AMDGPU::S_MOV_B64,
1374 AMDGPU::V_MOV_B64_PSEUDO, AMDGPU::V_MOV_B16_t16_e64,
1375 AMDGPU::V_ACCVGPR_WRITE_B32_e64, AMDGPU::AV_MOV_B32_IMM_PSEUDO,
1376 AMDGPU::AV_MOV_B64_IMM_PSEUDO}) {
1377 const MCInstrDesc &MovDesc = TII->get(MovOp);
1378 const TargetRegisterClass *MovDstRC =
1379 TRI->getRegClass(TII->getOpRegClassID(MovDesc.operands()[0]));
1380
1381 // Fold if the destination register class of the MOV instruction (ResRC)
1382 // is a superclass of (or equal to) the destination register class of the
1383 // COPY (DestRC). If this condition fails, folding would be illegal.
1384 if (!DestRC->hasSuperClassEq(MovDstRC))
1385 continue;
1386
1387 const int SrcIdx = MovOp == AMDGPU::V_MOV_B16_t16_e64 ? 2 : 1;
1388
1389 int16_t RegClassID = TII->getOpRegClassID(MovDesc.operands()[SrcIdx]);
1390 if (RegClassID != -1) {
1391 const TargetRegisterClass *MovSrcRC = TRI->getRegClass(RegClassID);
1392
1393 if (UseSubReg)
1394 MovSrcRC = TRI->getMatchingSuperRegClass(SrcRC, MovSrcRC, UseSubReg);
1395
1396 // FIXME: We should be able to directly check immediate operand legality
1397 // for all cases, but gfx908 hacks break.
1398 if (MovOp == AMDGPU::AV_MOV_B32_IMM_PSEUDO &&
1399 (!OpToFold.isImm() ||
1400 !TII->isImmOperandLegal(MovDesc, SrcIdx,
1401 *OpToFold.getEffectiveImmVal())))
1402 break;
1403
1404 if (!MRI->constrainRegClass(SrcReg, MovSrcRC))
1405 break;
1406
1407 // FIXME: This is mutating the instruction only and deferring the actual
1408 // fold of the immediate
1409 } else {
1410 // For the _IMM_PSEUDO cases, there can be value restrictions on the
1411 // immediate to verify. Technically we should always verify this, but it
1412 // only matters for these concrete cases.
1413 // TODO: Handle non-imm case if it's useful.
1414 if (!OpToFold.isImm() ||
1415 !TII->isImmOperandLegal(MovDesc, 1, *OpToFold.getEffectiveImmVal()))
1416 break;
1417 }
1418
1421 while (ImpOpI != ImpOpE) {
1422 MachineInstr::mop_iterator Tmp = ImpOpI;
1423 ImpOpI++;
1425 }
1426 UseMI->setDesc(MovDesc);
1427
1428 if (MovOp == AMDGPU::V_MOV_B16_t16_e64) {
1429 const auto &SrcOp = UseMI->getOperand(UseOpIdx);
1430 MachineOperand NewSrcOp(SrcOp);
1431 UseMI->removeOperand(1);
1432 UseMI->addOperand(*MF, MachineOperand::CreateImm(0)); // src0_modifiers
1433 UseMI->addOperand(NewSrcOp); // src0
1434 UseMI->addOperand(*MF, MachineOperand::CreateImm(0)); // op_sel
1435 UseOpIdx = SrcIdx;
1436 UseOp = &UseMI->getOperand(UseOpIdx);
1437 }
1438 CopiesToReplace.push_back(UseMI);
1439 Changed = true;
1440 break;
1441 }
1442
1443 // We failed to replace the copy, so give up.
1444 if (UseMI->getOpcode() == AMDGPU::COPY)
1445 return Changed;
1446
1447 } else {
1448 if (UseMI->isCopy() && OpToFold.isReg() &&
1449 UseMI->getOperand(0).getReg().isVirtual() &&
1450 !UseMI->getOperand(1).getSubReg() &&
1451 OpToFold.DefMI->implicit_operands().empty()) {
1452 LLVM_DEBUG(dbgs() << "Folding " << *OpToFold.OpToFold << "\n into "
1453 << *UseMI);
1454 unsigned Size = TII->getOpSize(*UseMI, 1);
1455 Register UseReg = OpToFold.getReg();
1457 unsigned SubRegIdx = OpToFold.getSubReg();
1458 // Hack to allow 32-bit SGPRs to be folded into True16 instructions
1459 // Remove this if 16-bit SGPRs (i.e. SGPR_LO16) are added to the
1460 // VS_16RegClass
1461 if (Size == 2 && TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) &&
1462 TRI->isSGPRReg(*MRI, UseReg) && SubRegIdx != AMDGPU::NoSubRegister) {
1463 // SGPRs only have lo16 subregisters, so the value is in the low half
1464 // of a 32-bit SGPR. Use that whole 32-bit SGPR instead.
1465 unsigned Channel = TRI->getChannelFromSubReg(SubRegIdx);
1466 const TargetRegisterClass *UseRC = TRI->getRegClassForReg(*MRI, UseReg);
1467 SubRegIdx = TRI->getRegSizeInBits(*UseRC) == 32
1468 ? AMDGPU::NoSubRegister
1470 }
1471 UseMI->getOperand(1).setSubReg(SubRegIdx);
1472 UseMI->getOperand(1).setIsKill(false);
1473 CopiesToReplace.push_back(UseMI);
1474 OpToFold.OpToFold->setIsKill(false);
1475 Changed = true;
1476
1477 if (foldCopyToAGPRRegSequence(UseMI))
1478 return true;
1479 }
1480
1481 unsigned UseOpc = UseMI->getOpcode();
1482 if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
1483 (UseOpc == AMDGPU::V_READLANE_B32 &&
1484 (int)UseOpIdx ==
1485 AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) {
1486 // %vgpr = V_MOV_B32 imm
1487 // %sgpr = V_READFIRSTLANE_B32 %vgpr
1488 // =>
1489 // %sgpr = S_MOV_B32 imm
1490 if (FoldingImmLike) {
1492 UseMI->getOperand(UseOpIdx).getReg(),
1493 *OpToFold.DefMI, *UseMI))
1494 return Changed;
1495
1496 UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32));
1498
1499 if (OpToFold.isImm()) {
1501 *OpToFold.getEffectiveImmVal());
1502 } else if (OpToFold.isFI())
1503 UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getFI());
1504 else {
1505 assert(OpToFold.isGlobal());
1506 UseMI->getOperand(1).ChangeToGA(OpToFold.OpToFold->getGlobal(),
1507 OpToFold.OpToFold->getOffset(),
1508 OpToFold.OpToFold->getTargetFlags());
1509 }
1510 UseMI->removeOperand(2); // Remove exec read (or src1 for readlane)
1511 return true;
1512 }
1513
1514 if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) {
1516 UseMI->getOperand(UseOpIdx).getReg(),
1517 *OpToFold.DefMI, *UseMI))
1518 return Changed;
1519
1520 // %vgpr = COPY %sgpr0
1521 // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
1522 // =>
1523 // %sgpr1 = COPY %sgpr0
1524 UseMI->setDesc(TII->get(AMDGPU::COPY));
1525 UseMI->getOperand(1).setReg(OpToFold.getReg());
1526 UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
1527 UseMI->getOperand(1).setIsKill(false);
1528 UseMI->removeOperand(2); // Remove exec read (or src1 for readlane)
1530 return true;
1531 }
1532 }
1533
1534 const MCInstrDesc &UseDesc = UseMI->getDesc();
1535
1536 // Don't fold into target independent nodes. Target independent opcodes
1537 // don't have defined register classes.
1538 if (UseDesc.isVariadic() || UseOp->isImplicit() ||
1539 UseDesc.operands()[UseOpIdx].RegClass == -1)
1540 return Changed;
1541 }
1542
1543 // FIXME: We could try to change the instruction from 64-bit to 32-bit
1544 // to enable more folding opportunities. The shrink operands pass
1545 // already does this.
1546
1547 Changed |= tryAddToFoldList(FoldList, UseMI, UseOpIdx, OpToFold);
1548 return Changed;
1549}
1550
1551static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
1553 switch (Opcode) {
1554 case AMDGPU::S_ADD_I32:
1555 case AMDGPU::S_ADD_U32:
1556 Result = LHS + RHS;
1557 return true;
1558 case AMDGPU::S_SUB_I32:
1559 case AMDGPU::S_SUB_U32:
1560 Result = LHS - RHS;
1561 return true;
1562 case AMDGPU::V_AND_B32_e64:
1563 case AMDGPU::V_AND_B32_e32:
1564 case AMDGPU::S_AND_B32:
1565 Result = LHS & RHS;
1566 return true;
1567 case AMDGPU::V_OR_B32_e64:
1568 case AMDGPU::V_OR_B32_e32:
1569 case AMDGPU::S_OR_B32:
1570 Result = LHS | RHS;
1571 return true;
1572 case AMDGPU::V_XOR_B32_e64:
1573 case AMDGPU::V_XOR_B32_e32:
1574 case AMDGPU::S_XOR_B32:
1575 Result = LHS ^ RHS;
1576 return true;
1577 case AMDGPU::S_XNOR_B32:
1578 Result = ~(LHS ^ RHS);
1579 return true;
1580 case AMDGPU::S_NAND_B32:
1581 Result = ~(LHS & RHS);
1582 return true;
1583 case AMDGPU::S_NOR_B32:
1584 Result = ~(LHS | RHS);
1585 return true;
1586 case AMDGPU::S_ANDN2_B32:
1587 Result = LHS & ~RHS;
1588 return true;
1589 case AMDGPU::S_ORN2_B32:
1590 Result = LHS | ~RHS;
1591 return true;
1592 case AMDGPU::V_LSHL_B32_e64:
1593 case AMDGPU::V_LSHL_B32_e32:
1594 case AMDGPU::S_LSHL_B32:
1595 // The instruction ignores the high bits for out of bounds shifts.
1596 Result = LHS << (RHS & 31);
1597 return true;
1598 case AMDGPU::V_LSHLREV_B32_e64:
1599 case AMDGPU::V_LSHLREV_B32_e32:
1600 Result = RHS << (LHS & 31);
1601 return true;
1602 case AMDGPU::V_LSHR_B32_e64:
1603 case AMDGPU::V_LSHR_B32_e32:
1604 case AMDGPU::S_LSHR_B32:
1605 Result = LHS >> (RHS & 31);
1606 return true;
1607 case AMDGPU::V_LSHRREV_B32_e64:
1608 case AMDGPU::V_LSHRREV_B32_e32:
1609 Result = RHS >> (LHS & 31);
1610 return true;
1611 case AMDGPU::V_ASHR_I32_e64:
1612 case AMDGPU::V_ASHR_I32_e32:
1613 case AMDGPU::S_ASHR_I32:
1614 Result = static_cast<int32_t>(LHS) >> (RHS & 31);
1615 return true;
1616 case AMDGPU::V_ASHRREV_I32_e64:
1617 case AMDGPU::V_ASHRREV_I32_e32:
1618 Result = static_cast<int32_t>(RHS) >> (LHS & 31);
1619 return true;
1620 default:
1621 return false;
1622 }
1623}
1624
1625static unsigned getMovOpc(bool IsScalar) {
1626 return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1627}
1628
1629// Try to simplify operations with a constant that may appear after instruction
1630// selection.
1631// TODO: See if a frame index with a fixed offset can fold.
1632bool SIFoldOperandsImpl::tryConstantFoldOp(MachineInstr *MI) const {
1633 if (!MI->allImplicitDefsAreDead())
1634 return false;
1635
1636 unsigned Opc = MI->getOpcode();
1637
1638 // (src0 << src1) + 0 -> src0 << src1
1639 if (Opc == AMDGPU::V_LSHL_ADD_U32_e64) {
1640 int DataIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1641 int AddIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
1642 std::optional<int64_t> Addend =
1643 TII->getImmOrMaterializedImm(*MRI, MI->getOperand(AddIdx));
1644
1645 if (Addend && static_cast<uint32_t>(*Addend) == 0) {
1646 MachineOperand Data = MI->getOperand(DataIdx);
1647 MI->removeOperand(AddIdx);
1648 MI->removeOperand(DataIdx);
1649 MI->addOperand(*MF, Data);
1650 TII->mutateAndCleanupImplicit(*MI, TII->get(AMDGPU::V_LSHLREV_B32_e64));
1651 return true;
1652 }
1653 }
1654
1655 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1656 if (Src0Idx == -1)
1657 return false;
1658
1659 MachineOperand *Src0 = &MI->getOperand(Src0Idx);
1660 std::optional<int64_t> Src0Imm = TII->getImmOrMaterializedImm(*MRI, *Src0);
1661
1662 if ((Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
1663 Opc == AMDGPU::S_NOT_B32) &&
1664 Src0Imm) {
1665 MI->getOperand(1).ChangeToImmediate(~*Src0Imm);
1666 TII->mutateAndCleanupImplicit(
1667 *MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
1668 return true;
1669 }
1670
1671 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1672 if (Src1Idx == -1)
1673 return false;
1674
1675 MachineOperand *Src1 = &MI->getOperand(Src1Idx);
1676 std::optional<int64_t> Src1Imm = TII->getImmOrMaterializedImm(*MRI, *Src1);
1677
1678 if (!Src0Imm && !Src1Imm)
1679 return false;
1680
1681 // and k0, k1 -> v_mov_b32 (k0 & k1)
1682 // or k0, k1 -> v_mov_b32 (k0 | k1)
1683 // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
1684 if (Src0Imm && Src1Imm) {
1685 int32_t NewImm;
1686 if (!evalBinaryInstruction(Opc, NewImm, *Src0Imm, *Src1Imm))
1687 return false;
1688
1689 bool IsSGPR = TRI->isSGPRReg(*MRI, MI->getOperand(0).getReg());
1690
1691 // Be careful to change the right operand, src0 may belong to a different
1692 // instruction.
1693 MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
1694 MI->removeOperand(Src1Idx);
1695 TII->mutateAndCleanupImplicit(*MI, TII->get(getMovOpc(IsSGPR)));
1696 return true;
1697 }
1698
1699 // S_SUB_* is not commutable, so handle it before the commutability gate.
1700 // Only `x - 0 -> copy x` is valid; `0 - x` is a negation, not a copy.
1701 if (Opc == AMDGPU::S_SUB_I32 || Opc == AMDGPU::S_SUB_U32) {
1702 if (Src1Imm && static_cast<int32_t>(*Src1Imm) == 0) {
1703 // y = sub x, 0 => y = copy x
1704 MI->removeOperand(Src1Idx);
1705 TII->mutateAndCleanupImplicit(*MI, TII->get(AMDGPU::COPY));
1706 return true;
1707 }
1708 return false;
1709 }
1710
1711 if (!MI->isCommutable())
1712 return false;
1713
1714 if (Src0Imm && !Src1Imm) {
1715 std::swap(Src0, Src1);
1716 std::swap(Src0Idx, Src1Idx);
1717 std::swap(Src0Imm, Src1Imm);
1718 }
1719
1720 int32_t Src1Val = static_cast<int32_t>(*Src1Imm);
1721 if (Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_ADD_U32) {
1722 if (Src1Val == 0) {
1723 // y = add x, 0 => y = copy x
1724 MI->removeOperand(Src1Idx);
1725 TII->mutateAndCleanupImplicit(*MI, TII->get(AMDGPU::COPY));
1726 return true;
1727 }
1728 return false;
1729 }
1730
1731 if (Opc == AMDGPU::V_OR_B32_e64 ||
1732 Opc == AMDGPU::V_OR_B32_e32 ||
1733 Opc == AMDGPU::S_OR_B32) {
1734 if (Src1Val == 0) {
1735 // y = or x, 0 => y = copy x
1736 MI->removeOperand(Src1Idx);
1737 TII->mutateAndCleanupImplicit(*MI, TII->get(AMDGPU::COPY));
1738 } else if (Src1Val == -1) {
1739 // y = or x, -1 => y = v_mov_b32 -1
1740 MI->removeOperand(Src0Idx);
1741 TII->mutateAndCleanupImplicit(
1742 *MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
1743 } else
1744 return false;
1745
1746 return true;
1747 }
1748
1749 if (Opc == AMDGPU::V_AND_B32_e64 || Opc == AMDGPU::V_AND_B32_e32 ||
1750 Opc == AMDGPU::S_AND_B32 || Opc == AMDGPU::S_AND_B64) {
1751 int64_t C = Opc == AMDGPU::S_AND_B64 ? *Src1Imm : Src1Val;
1752 if (C == 0) {
1753 // y = and x, 0 => y = mov 0
1754 MI->removeOperand(Src0Idx);
1755 TII->mutateAndCleanupImplicit(
1756 *MI, TII->get(TII->getMovOpcode(TII->getOpRegClass(*MI, 0))));
1757 } else if (C == -1) {
1758 // y = and x, -1 => y = copy x
1759 MI->removeOperand(Src1Idx);
1760 TII->mutateAndCleanupImplicit(*MI, TII->get(AMDGPU::COPY));
1761 } else
1762 return false;
1763
1764 return true;
1765 }
1766
1767 if (Opc == AMDGPU::V_XOR_B32_e64 || Opc == AMDGPU::V_XOR_B32_e32 ||
1768 Opc == AMDGPU::S_XOR_B32) {
1769 if (Src1Val == 0) {
1770 // y = xor x, 0 => y = copy x
1771 MI->removeOperand(Src1Idx);
1772 TII->mutateAndCleanupImplicit(*MI, TII->get(AMDGPU::COPY));
1773 return true;
1774 }
1775 }
1776
1777 return false;
1778}
1779
1780// Fold a select whose two sources are the same value into a copy or move.
1781bool SIFoldOperandsImpl::tryFoldCndMask(MachineInstr &MI) const {
1782 unsigned Opc = MI.getOpcode();
1783 if (Opc != AMDGPU::V_CNDMASK_B32_e32 && Opc != AMDGPU::V_CNDMASK_B32_e64 &&
1784 Opc != AMDGPU::S_CSELECT_B32 && Opc != AMDGPU::S_CSELECT_B64)
1785 return false;
1786
1787 MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1788 MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1789 if (!Src1->isIdenticalTo(*Src0)) {
1790 std::optional<int64_t> Src1Imm = TII->getImmOrMaterializedImm(*MRI, *Src1);
1791 if (!Src1Imm)
1792 return false;
1793
1794 std::optional<int64_t> Src0Imm = TII->getImmOrMaterializedImm(*MRI, *Src0);
1795 if (!Src0Imm || *Src0Imm != *Src1Imm)
1796 return false;
1797 }
1798
1799 int Src1ModIdx =
1800 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
1801 int Src0ModIdx =
1802 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
1803 if ((Src1ModIdx != -1 && MI.getOperand(Src1ModIdx).getImm() != 0) ||
1804 (Src0ModIdx != -1 && MI.getOperand(Src0ModIdx).getImm() != 0))
1805 return false;
1806
1807 unsigned NewOpc;
1808 if (Src0->isReg()) {
1809 NewOpc = AMDGPU::COPY;
1810 } else {
1811 switch (Opc) {
1812 case AMDGPU::S_CSELECT_B32:
1813 NewOpc = AMDGPU::S_MOV_B32;
1814 break;
1815 case AMDGPU::S_CSELECT_B64:
1816 NewOpc = AMDGPU::S_MOV_B64;
1817 break;
1818 default:
1819 NewOpc = AMDGPU::V_MOV_B32_e32;
1820 break;
1821 }
1822 }
1823
1824 LLVM_DEBUG(dbgs() << "Folded " << MI << " into ");
1825 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
1826 if (Src2Idx != -1)
1827 MI.removeOperand(Src2Idx);
1828 MI.removeOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
1829 if (Src1ModIdx != -1)
1830 MI.removeOperand(Src1ModIdx);
1831 if (Src0ModIdx != -1)
1832 MI.removeOperand(Src0ModIdx);
1833 TII->mutateAndCleanupImplicit(MI, TII->get(NewOpc));
1834 LLVM_DEBUG(dbgs() << MI);
1835 return true;
1836}
1837
1838// Extract mask and register from an AND instruction.
1839// Immediate can be in operand 1 or 2.
1840std::optional<SIFoldOperandsImpl::ANDMaskResult>
1841SIFoldOperandsImpl::getANDMaskRegOperand(MachineInstr &AndMI) const {
1842 unsigned Opc = AndMI.getOpcode();
1843 if (Opc != AMDGPU::V_AND_B32_e64 && Opc != AMDGPU::V_AND_B32_e32 &&
1844 Opc != AMDGPU::S_AND_B32)
1845 return std::nullopt;
1846
1847 std::optional<int64_t> MaskImm =
1848 TII->getImmOrMaterializedImm(*MRI, AndMI.getOperand(1));
1849 if (MaskImm && AndMI.getOperand(2).isReg())
1850 return ANDMaskResult{*MaskImm, AndMI.getOperand(2).getReg()};
1851
1852 MaskImm = TII->getImmOrMaterializedImm(*MRI, AndMI.getOperand(2));
1853 if (MaskImm && AndMI.getOperand(1).isReg())
1854 return ANDMaskResult{*MaskImm, AndMI.getOperand(1).getReg()};
1855
1856 return std::nullopt;
1857}
1858
1859// Operands of an op_sel instruction that are not present in the equivalent
1860// legacy instruction, in operand order.
1861static constexpr AMDGPU::OpName OpSelOnlyOpNames[] = {
1862 AMDGPU::OpName::src0_modifiers, AMDGPU::OpName::src1_modifiers,
1863 AMDGPU::OpName::src2_modifiers, AMDGPU::OpName::op_sel};
1864
1865// If MI is an op_sel instruction on GFX9 that does not use op_sel, return the
1866// opcode of the equivalent legacy instruction, which zeros the high 16 bits of
1867// the destination. Otherwise return 0.
1868static unsigned getZeroHi16LegacyOpcode(const GCNSubtarget &ST,
1869 const MachineInstr &MI) {
1870 if (ST.getGeneration() != AMDGPUSubtarget::GFX9)
1871 return 0;
1872
1873 unsigned LegacyOpc;
1874 switch (MI.getOpcode()) {
1875 case AMDGPU::V_MAD_U16_gfx9_e64:
1876 LegacyOpc = AMDGPU::V_MAD_U16_e64;
1877 break;
1878 case AMDGPU::V_MAD_I16_gfx9_e64:
1879 LegacyOpc = AMDGPU::V_MAD_I16_e64;
1880 break;
1881 default:
1882 return 0;
1883 }
1884
1885 for (AMDGPU::OpName OpName : OpSelOnlyOpNames) {
1886 if (MI.getOperand(AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpName))
1887 .getImm() != 0)
1888 return 0;
1889 }
1890
1891 return LegacyOpc;
1892}
1893
1894// Eliminate redundant 32-bit AND operations by detecting when ChildMI's mask
1895// contains ParentMI's mask.
1896//
1897// For example:
1898// ParentMI: %1 = AND %0, 0x7fff
1899// ChildMI: %2 = AND %1, 0xffff
1900//
1901// This also handles cases where ParentMI implicitly zeros high bits (e.g., f16
1902// operations that write 16-bit results into 32-bit registers), making a
1903// subsequent AND with 0xffff redundant. On GFX9, ParentMI may be switched to a
1904// legacy opcode that zeros the high bits for this purpose.
1905bool SIFoldOperandsImpl::tryFoldRedundantAND(MachineInstr &ChildMI) const {
1906 // Ensure implicit defs (e.g., $scc) are not live.
1907 if (!ChildMI.allImplicitDefsAreDead())
1908 return false;
1909
1910 std::optional<ANDMaskResult> ChildResult = getANDMaskRegOperand(ChildMI);
1911 if (!ChildResult)
1912 return false;
1913
1914 if (!ChildResult->Reg.isVirtual())
1915 return false;
1916
1917 MachineInstr *ParentMI = MRI->getVRegDef(ChildResult->Reg);
1918 if (!ParentMI)
1919 return false;
1920
1921 int64_t ParentMask = 0;
1922 unsigned LegacyOpc = 0;
1923 std::optional<ANDMaskResult> ParentResult = getANDMaskRegOperand(*ParentMI);
1924 if (ParentResult) {
1925 // Parent is an AND - extract its mask.
1926 ParentMask = ParentResult->Mask;
1927 } else if (ST->zeroesHigh16BitsOfDest(ParentMI->getOpcode())) {
1928 // Parent instruction implicitly zeros high 16 bits.
1929 ParentMask = 0xffff;
1930 } else if ((LegacyOpc = getZeroHi16LegacyOpcode(*ST, *ParentMI))) {
1931 // Parent instruction can be switched to a legacy opcode that implicitly
1932 // zeros high 16 bits.
1933 ParentMask = 0xffff;
1934 } else {
1935 return false;
1936 }
1937
1938 // Check if ChildMI is not redundant.
1939 if ((ParentMask & ChildResult->Mask) != ParentMask)
1940 return false;
1941
1942 Register Dst = ChildMI.getOperand(0).getReg();
1943 Register Src = ChildResult->Reg;
1944
1945 // Src must be legal in every use of Dst. An S_AND_B32 parent with a
1946 // V_AND_B32 child defines Src in the scalar bank, and a use that requires a
1947 // VGPR does not accept it.
1948 if (!Dst.isVirtual() || !MRI->constrainRegClass(Src, MRI->getRegClass(Dst)))
1949 return false;
1950
1951 if (LegacyOpc) {
1952 unsigned Opc = ParentMI->getOpcode();
1953 for (AMDGPU::OpName OpName : reverse(OpSelOnlyOpNames))
1954 ParentMI->removeOperand(AMDGPU::getNamedOperandIdx(Opc, OpName));
1955 TII->mutateAndCleanupImplicit(*ParentMI, TII->get(LegacyOpc));
1956 }
1957
1958 MRI->replaceRegWith(Dst, Src);
1959
1960 ChildMI.eraseFromParent();
1961 return true;
1962}
1963
1964/// Remove S_AND of a lane mask with EXEC, when the lane mask is already known
1965/// to have 0 in the bits of all inactive lanes.
1966///
1967/// Instruction selection inserts these unconditionally because it has not
1968/// analysed what produced the lane mask.
1969bool SIFoldOperandsImpl::tryFoldAndExec(MachineInstr &MI) const {
1970 const AMDGPU::LaneMaskConstants &LMC = AMDGPU::LaneMaskConstants::get(*ST);
1971 if (MI.getOpcode() != LMC.AndOpc)
1972 return false;
1973
1974 // The AND is going to be removed, so nothing may use the SCC it defines.
1975 if (!MI.allImplicitDefsAreDead())
1976 return false;
1977
1978 // Find the EXEC operand, and the lane mask it is being ANDed with.
1979 unsigned ExecIdx = 0;
1980 for (unsigned I : {1u, 2u}) {
1981 const MachineOperand &MO = MI.getOperand(I);
1982 if (MO.isReg() && MO.getReg() == LMC.ExecReg)
1983 ExecIdx = I;
1984 }
1985 if (!ExecIdx)
1986 return false;
1987 MachineOperand &Src = MI.getOperand(3 - ExecIdx);
1988 if (!Src.isReg() || !Src.getReg().isVirtual() || Src.getSubReg())
1989 return false;
1990
1991 Register SrcReg = Src.getReg();
1992 if (!TII->isMaskedByExec(SrcReg, MI, *MRI))
1993 return false;
1994
1995 LLVM_DEBUG(dbgs() << "Folding redundant AND with EXEC: " << MI);
1996
1997 Register DstReg = MI.getOperand(0).getReg();
1998 if (DstReg.isVirtual()) {
1999 if (!MRI->constrainRegClass(SrcReg, MRI->getRegClass(DstReg)))
2000 return false;
2001 MRI->replaceRegWith(DstReg, SrcReg);
2002 } else {
2003 // A physical destination, e.g. the $vcc written by moveToVALU. Register
2004 // allocation will usually make this copy an identity copy.
2005 MachineBasicBlock *MBB = MI.getParent();
2006 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY), DstReg)
2007 .addReg(SrcReg);
2008 }
2009
2010 MI.eraseFromParent();
2011 return true;
2012}
2013
2014/// Fold S_AND (S_CSELECT EXEC|-1, 0), %mask -> S_CSELECT %mask, 0, rewriting
2015/// the S_CSELECT in place. The EXEC form requires %mask to be masked by EXEC.
2016/// Also handles S_CSELECT 0, EXEC|-1.
2017bool SIFoldOperandsImpl::tryFoldAndCSelectExec(MachineInstr &MI) const {
2018 const AMDGPU::LaneMaskConstants &LMC = AMDGPU::LaneMaskConstants::get(*ST);
2019 // The AND is erased, so its SCC def must be dead.
2020 if (MI.getOpcode() != LMC.AndOpc || !MI.allImplicitDefsAreDead())
2021 return false;
2022
2023 for (unsigned SelIdx : {1u, 2u}) {
2024 const MachineOperand &SelMO = MI.getOperand(SelIdx);
2025 const MachineOperand &MaskMO = MI.getOperand(3 - SelIdx);
2026 // The S_CSELECT is rewritten in place, so the AND must be its only user.
2027 // %mask is then read at the S_CSELECT; EXEC is the only physical register
2028 // known not to change in between.
2029 if (!SelMO.isReg() || !SelMO.getReg().isVirtual() || SelMO.getSubReg() ||
2030 !MaskMO.isReg() || MaskMO.getSubReg() ||
2031 (MaskMO.getReg().isPhysical() && MaskMO.getReg() != LMC.ExecReg) ||
2032 !MRI->hasOneNonDBGUse(SelMO.getReg()))
2033 continue;
2034
2035 MachineInstr *Sel = MRI->getVRegDef(SelMO.getReg());
2036 if (!Sel || Sel->getOpcode() != LMC.CSelectOpc ||
2037 Sel->getParent() != MI.getParent())
2038 continue;
2039
2040 unsigned ArmIdx;
2041 if (Sel->getOperand(2).isImm() && Sel->getOperand(2).getImm() == 0)
2042 ArmIdx = 1;
2043 else if (Sel->getOperand(1).isImm() && Sel->getOperand(1).getImm() == 0)
2044 ArmIdx = 2;
2045 else
2046 continue;
2047
2048 Register MaskReg = MaskMO.getReg();
2049 MachineOperand &Arm = Sel->getOperand(ArmIdx);
2050 const bool IsAllOnesArm = Arm.isImm() && Arm.getImm() == -1;
2051 const bool IsExecArm = Arm.isReg() && Arm.getReg() == LMC.ExecReg;
2052 if (!IsAllOnesArm &&
2053 (!IsExecArm || !TII->isMaskedByExec(MaskReg, MI, *MRI)))
2054 continue;
2055
2056 // A def of %mask in another block dominates the S_CSELECT; in the same
2057 // block it must not lie between the S_CSELECT and the AND.
2058 if (MaskReg.isVirtual()) {
2059 const MachineInstr *MaskDef = MRI->getVRegDef(MaskReg);
2060 if (!MaskDef)
2061 continue;
2062 if (MaskDef->getParent() == Sel->getParent()) {
2063 constexpr unsigned MaxInstScan = 20;
2064 unsigned NumInst = 0;
2065 if (any_of(instructionsWithoutDebug(std::next(Sel->getIterator()),
2066 MI.getIterator()),
2067 [&](const MachineInstr &I) {
2068 return ++NumInst > MaxInstScan || &I == MaskDef;
2069 }))
2070 continue;
2071 }
2072 }
2073
2074 Register SelReg = SelMO.getReg();
2075 Register DstReg = MI.getOperand(0).getReg();
2076 if (DstReg.isVirtual() &&
2077 !MRI->constrainRegClass(SelReg, MRI->getRegClass(DstReg)))
2078 continue;
2079
2080 LLVM_DEBUG(dbgs() << "Folding AND of S_CSELECT into S_CSELECT: " << MI);
2081
2082 // Debug uses of the S_CSELECT refer to its old value.
2084 Arm.ChangeToRegister(MaskReg, /*isDef=*/false);
2085
2086 if (DstReg.isVirtual()) {
2087 MRI->replaceRegWith(DstReg, SelReg);
2088 } else {
2089 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY),
2090 DstReg)
2091 .addReg(SelReg);
2092 }
2093
2094 MI.eraseFromParent();
2095 return true;
2096 }
2097
2098 return false;
2099}
2100
2101bool SIFoldOperandsImpl::foldInstOperand(MachineInstr &MI,
2102 const FoldableDef &OpToFold) const {
2103 // We need mutate the operands of new mov instructions to add implicit
2104 // uses of EXEC, but adding them invalidates the use_iterator, so defer
2105 // this.
2106 SmallVector<MachineInstr *, 4> CopiesToReplace;
2108 MachineOperand &Dst = MI.getOperand(0);
2109 bool Changed = false;
2110
2113 for (auto *U : UsesToProcess) {
2114 MachineInstr *UseMI = U->getParent();
2115
2116 FoldableDef SubOpToFold = OpToFold.getWithSubReg(*TRI, U->getSubReg());
2117 Changed |= foldOperand(SubOpToFold, UseMI, UseMI->getOperandNo(U), FoldList,
2118 CopiesToReplace);
2119 }
2120
2121 if (CopiesToReplace.empty() && FoldList.empty())
2122 return Changed;
2123
2124 // Make sure we add EXEC uses to any new v_mov instructions created.
2125 for (MachineInstr *Copy : CopiesToReplace)
2126 Copy->addImplicitDefUseOperands(*MF);
2127
2128 SetVector<MachineInstr *> ConstantFoldCandidates;
2129 for (FoldCandidate &Fold : FoldList) {
2130 assert(!Fold.isReg() || Fold.Def.OpToFold);
2131 if (Fold.isReg() && Fold.getReg().isVirtual()) {
2132 Register Reg = Fold.getReg();
2133 const MachineInstr *DefMI = Fold.Def.DefMI;
2134 if (DefMI->readsRegister(AMDGPU::EXEC, TRI) &&
2135 execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI))
2136 continue;
2137 }
2138 if (updateOperand(Fold)) {
2139 LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
2140 << static_cast<int>(Fold.UseOpNo) << " of "
2141 << *Fold.UseMI);
2142
2143 if (Fold.isImm())
2144 ConstantFoldCandidates.insert(Fold.UseMI);
2145
2146 } else if (Fold.Commuted) {
2147 // Restoring instruction's original operand order if fold has failed.
2148 TII->commuteInstruction(*Fold.UseMI, false);
2149 }
2150 }
2151
2152 for (MachineInstr *MI : ConstantFoldCandidates) {
2153 if (tryConstantFoldOp(MI)) {
2154 LLVM_DEBUG(dbgs() << "Constant folded " << *MI);
2155 Changed = true;
2156 }
2157 }
2158 return true;
2159}
2160
2161/// Fold %agpr = COPY (REG_SEQUENCE x_MOV_B32, ...) into REG_SEQUENCE
2162/// (V_ACCVGPR_WRITE_B32_e64) ... depending on the reg_sequence input values.
2163bool SIFoldOperandsImpl::foldCopyToAGPRRegSequence(MachineInstr *CopyMI) const {
2164 // It is very tricky to store a value into an AGPR. v_accvgpr_write_b32 can
2165 // only accept VGPR or inline immediate. Recreate a reg_sequence with its
2166 // initializers right here, so we will rematerialize immediates and avoid
2167 // copies via different reg classes.
2168 const TargetRegisterClass *DefRC =
2169 MRI->getRegClass(CopyMI->getOperand(0).getReg());
2170 if (!TRI->isAGPRClass(DefRC))
2171 return false;
2172
2173 Register UseReg = CopyMI->getOperand(1).getReg();
2174 MachineInstr *RegSeq = MRI->getVRegDef(UseReg);
2175 if (!RegSeq || !RegSeq->isRegSequence())
2176 return false;
2177
2178 const DebugLoc &DL = CopyMI->getDebugLoc();
2179 MachineBasicBlock &MBB = *CopyMI->getParent();
2180
2181 MachineInstrBuilder B(*MBB.getParent(), CopyMI);
2182 DenseMap<TargetInstrInfo::RegSubRegPair, Register> VGPRCopies;
2183
2184 const TargetRegisterClass *UseRC =
2185 MRI->getRegClass(CopyMI->getOperand(1).getReg());
2186
2187 // Value, subregindex for new REG_SEQUENCE
2189
2190 unsigned NumRegSeqOperands = RegSeq->getNumOperands();
2191 unsigned NumFoldable = 0;
2192
2193 for (unsigned I = 1; I != NumRegSeqOperands; I += 2) {
2194 MachineOperand &RegOp = RegSeq->getOperand(I);
2195 unsigned SubRegIdx = RegSeq->getOperand(I + 1).getImm();
2196
2197 if (RegOp.getSubReg()) {
2198 // TODO: Handle subregister compose
2199 NewDefs.emplace_back(&RegOp, SubRegIdx);
2200 continue;
2201 }
2202
2203 MachineOperand *Lookup = lookUpCopyChain(*TII, *MRI, RegOp.getReg());
2204 if (!Lookup)
2205 Lookup = &RegOp;
2206
2207 if (Lookup->isImm()) {
2208 // Check if this is an agpr_32 subregister.
2209 const TargetRegisterClass *DestSuperRC = TRI->getMatchingSuperRegClass(
2210 DefRC, &AMDGPU::AGPR_32RegClass, SubRegIdx);
2211 if (DestSuperRC &&
2212 TII->isInlineConstant(*Lookup, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
2213 ++NumFoldable;
2214 NewDefs.emplace_back(Lookup, SubRegIdx);
2215 continue;
2216 }
2217 }
2218
2219 const TargetRegisterClass *InputRC =
2220 Lookup->isReg() ? MRI->getRegClass(Lookup->getReg())
2221 : MRI->getRegClass(RegOp.getReg());
2222
2223 // TODO: Account for Lookup->getSubReg()
2224
2225 // If we can't find a matching super class, this is an SGPR->AGPR or
2226 // VGPR->AGPR subreg copy (or something constant-like we have to materialize
2227 // in the AGPR). We can't directly copy from SGPR to AGPR on gfx908, so we
2228 // want to rewrite to copy to an intermediate VGPR class.
2229 const TargetRegisterClass *MatchRC =
2230 TRI->getMatchingSuperRegClass(DefRC, InputRC, SubRegIdx);
2231 if (!MatchRC) {
2232 ++NumFoldable;
2233 NewDefs.emplace_back(&RegOp, SubRegIdx);
2234 continue;
2235 }
2236
2237 NewDefs.emplace_back(&RegOp, SubRegIdx);
2238 }
2239
2240 // Do not clone a reg_sequence and merely change the result register class.
2241 if (NumFoldable == 0)
2242 return false;
2243
2244 CopyMI->setDesc(TII->get(AMDGPU::REG_SEQUENCE));
2245 for (unsigned I = CopyMI->getNumOperands() - 1; I > 0; --I)
2246 CopyMI->removeOperand(I);
2247
2248 for (auto [Def, DestSubIdx] : NewDefs) {
2249 if (!Def->isReg()) {
2250 // TODO: Should we use single write for each repeated value like in
2251 // register case?
2252 Register Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
2253 BuildMI(MBB, CopyMI, DL, TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp)
2254 .add(*Def);
2255 B.addReg(Tmp);
2256 } else {
2257 TargetInstrInfo::RegSubRegPair Src = getRegSubRegPair(*Def);
2258 Def->setIsKill(false);
2259
2260 Register &VGPRCopy = VGPRCopies[Src];
2261 if (!VGPRCopy) {
2262 const TargetRegisterClass *VGPRUseSubRC =
2263 TRI->getSubRegisterClass(UseRC, DestSubIdx);
2264
2265 // We cannot build a reg_sequence out of the same registers, they
2266 // must be copied. Better do it here before copyPhysReg() created
2267 // several reads to do the AGPR->VGPR->AGPR copy.
2268
2269 // Direct copy from SGPR to AGPR is not possible on gfx908. To avoid
2270 // creation of exploded copies SGPR->VGPR->AGPR in the copyPhysReg()
2271 // later, create a copy here and track if we already have such a copy.
2272 const TargetRegisterClass *SubRC =
2273 TRI->getSubRegisterClass(MRI->getRegClass(Src.Reg), Src.SubReg);
2274 if (!VGPRUseSubRC->hasSubClassEq(SubRC)) {
2275 // TODO: Try to reconstrain class
2276 VGPRCopy = MRI->createVirtualRegister(VGPRUseSubRC);
2277 BuildMI(MBB, CopyMI, DL, TII->get(AMDGPU::COPY), VGPRCopy).add(*Def);
2278 B.addReg(VGPRCopy);
2279 } else {
2280 // If it is already a VGPR, do not copy the register.
2281 B.add(*Def);
2282 }
2283 } else {
2284 B.addReg(VGPRCopy);
2285 }
2286 }
2287
2288 B.addImm(DestSubIdx);
2289 }
2290
2291 LLVM_DEBUG(dbgs() << "Folded " << *CopyMI);
2292 return true;
2293}
2294
2295bool SIFoldOperandsImpl::tryFoldFoldableCopy(
2296 MachineInstr &MI, MachineOperand *&CurrentKnownM0Val) const {
2297 Register DstReg = MI.getOperand(0).getReg();
2298 // Specially track simple redefs of m0 to the same value in a block, so we
2299 // can erase the later ones.
2300 if (DstReg == AMDGPU::M0) {
2301 MachineOperand &NewM0Val = MI.getOperand(1);
2302 if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) {
2303 MI.eraseFromParent();
2304 return true;
2305 }
2306
2307 // We aren't tracking other physical registers
2308 CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical())
2309 ? nullptr
2310 : &NewM0Val;
2311 return false;
2312 }
2313
2314 MachineOperand *OpToFoldPtr;
2315 if (MI.getOpcode() == AMDGPU::V_MOV_B16_t16_e64) {
2316 // Folding when any src_modifiers are non-zero is unsupported
2317 if (TII->hasAnyModifiersSet(MI))
2318 return false;
2319 OpToFoldPtr = &MI.getOperand(2);
2320 } else
2321 OpToFoldPtr = &MI.getOperand(1);
2322 MachineOperand &OpToFold = *OpToFoldPtr;
2323 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
2324
2325 // FIXME: We could also be folding things like TargetIndexes.
2326 if (!FoldingImm && !OpToFold.isReg())
2327 return false;
2328
2329 // Fold virtual registers and constant physical registers.
2330 if (OpToFold.isReg() && OpToFold.getReg().isPhysical() &&
2331 !TRI->isConstantPhysReg(OpToFold.getReg()))
2332 return false;
2333
2334 // Prevent folding operands backwards in the function. For example,
2335 // the COPY opcode must not be replaced by 1 in this example:
2336 //
2337 // %3 = COPY %vgpr0; VGPR_32:%3
2338 // ...
2339 // %vgpr0 = V_MOV_B32_e32 1, implicit %exec
2340 if (!DstReg.isVirtual())
2341 return false;
2342
2343 const TargetRegisterClass *DstRC =
2344 MRI->getRegClass(MI.getOperand(0).getReg());
2345
2346 // True16: Fix malformed 16-bit sgpr COPY produced by peephole-opt
2347 // Can remove this code if proper 16-bit SGPRs are implemented
2348 // Example: Pre-peephole-opt
2349 // %29:sgpr_lo16 = COPY %16.lo16:sreg_32
2350 // %32:sreg_32 = COPY %29:sgpr_lo16
2351 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %32:sreg_32
2352 // Post-peephole-opt and DCE
2353 // %32:sreg_32 = COPY %16.lo16:sreg_32
2354 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %32:sreg_32
2355 // After this transform
2356 // %32:sreg_32 = COPY %16:sreg_32
2357 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %32:sreg_32
2358 // After the fold operands pass
2359 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %16:sreg_32
2360 if (MI.getOpcode() == AMDGPU::COPY && OpToFold.isReg() &&
2361 OpToFold.getSubReg()) {
2362 if (DstRC == &AMDGPU::SReg_32RegClass &&
2363 DstRC == MRI->getRegClass(OpToFold.getReg())) {
2364 if (!TRI->getMatchingSuperRegClass(DstRC, &AMDGPU::SGPR_LO16RegClass,
2365 OpToFold.getSubReg()))
2366 return false;
2367 OpToFold.setSubReg(0);
2368 }
2369 }
2370
2371 // Fold copy to AGPR through reg_sequence
2372 // TODO: Handle with subregister extract
2373 if (OpToFold.isReg() && MI.isCopy() && !MI.getOperand(1).getSubReg()) {
2374 if (foldCopyToAGPRRegSequence(&MI))
2375 return true;
2376 }
2377
2378 FoldableDef Def(OpToFold, DstRC);
2379 bool Changed = foldInstOperand(MI, Def);
2380
2381 // If we managed to fold all uses of this copy then we might as well
2382 // delete it now.
2383 // The only reason we need to follow chains of copies here is that
2384 // tryFoldRegSequence looks forward through copies before folding a
2385 // REG_SEQUENCE into its eventual users.
2386 auto *InstToErase = &MI;
2387 while (MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
2388 auto &SrcOp = InstToErase->getOperand(1);
2389 auto SrcReg = SrcOp.isReg() ? SrcOp.getReg() : Register();
2390 InstToErase->eraseFromParent();
2391 Changed = true;
2392 InstToErase = nullptr;
2393 if (!SrcReg || SrcReg.isPhysical())
2394 break;
2395 InstToErase = MRI->getVRegDef(SrcReg);
2396 if (!InstToErase || !TII->isFoldableCopy(*InstToErase))
2397 break;
2398 }
2399
2400 if (InstToErase && InstToErase->isRegSequence() &&
2401 MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
2402 InstToErase->eraseFromParent();
2403 Changed = true;
2404 }
2405
2406 if (Changed)
2407 return true;
2408
2409 // Run this after foldInstOperand to avoid turning scalar additions into
2410 // vector additions when the result scalar result could just be folded into
2411 // the user(s).
2412 return OpToFold.isReg() &&
2413 foldCopyToVGPROfScalarAddOfFrameIndex(DstReg, OpToFold.getReg(), MI);
2414}
2415
2416// Clamp patterns are canonically selected to v_max_* instructions, so only
2417// handle them.
2418const MachineOperand *
2419SIFoldOperandsImpl::isClamp(const MachineInstr &MI) const {
2420 unsigned Op = MI.getOpcode();
2421 switch (Op) {
2422 case AMDGPU::V_MAX_F32_e64:
2423 case AMDGPU::V_MAX_F16_e64:
2424 case AMDGPU::V_MAX_F16_t16_e64:
2425 case AMDGPU::V_MAX_F16_fake16_e64:
2426 case AMDGPU::V_MAX_F64_e64:
2427 case AMDGPU::V_MAX_NUM_F64_e64:
2428 case AMDGPU::V_PK_MAX_F16:
2429 case AMDGPU::V_MAX_BF16_PSEUDO_e64:
2430 case AMDGPU::V_PK_MAX_NUM_BF16: {
2431 if (MI.mayRaiseFPException())
2432 return nullptr;
2433
2434 if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
2435 return nullptr;
2436
2437 // Make sure sources are identical.
2438 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
2439 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
2440 if (!Src0->isReg() || !Src1->isReg() ||
2441 Src0->getReg() != Src1->getReg() ||
2442 Src0->getSubReg() != Src1->getSubReg() ||
2443 Src0->getSubReg() != AMDGPU::NoSubRegister)
2444 return nullptr;
2445
2446 // Can't fold up if we have modifiers.
2447 if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
2448 return nullptr;
2449
2450 unsigned Src0Mods
2451 = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
2452 unsigned Src1Mods
2453 = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
2454
2455 // Having a 0 op_sel_hi would require swizzling the output in the source
2456 // instruction, which we can't do.
2457 unsigned UnsetMods =
2458 (Op == AMDGPU::V_PK_MAX_F16 || Op == AMDGPU::V_PK_MAX_NUM_BF16)
2460 : 0u;
2461 if (Src0Mods != UnsetMods || Src1Mods != UnsetMods)
2462 return nullptr;
2463 return Src0;
2464 }
2465 default:
2466 return nullptr;
2467 }
2468}
2469
2470// FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
2471bool SIFoldOperandsImpl::tryFoldClamp(MachineInstr &MI) {
2472 const MachineOperand *ClampSrc = isClamp(MI);
2473 if (!ClampSrc || !MRI->hasOneNonDBGUser(ClampSrc->getReg()))
2474 return false;
2475
2476 if (!ClampSrc->getReg().isVirtual())
2477 return false;
2478
2479 // Look through COPY. COPY only observed with True16. Setting the clamp bit on
2480 // Def changes the value of every register in the chain, so each of them must
2481 // have no other users.
2482 MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
2483 while (Def && Def->isCopy()) {
2484 Register CopySrcReg = Def->getOperand(1).getReg();
2485 if (!CopySrcReg.isVirtual() || !MRI->hasOneNonDBGUser(CopySrcReg))
2486 return false;
2487 Def = MRI->getVRegDef(CopySrcReg);
2488 }
2489 if (!Def)
2490 return false;
2491
2492 // The type of clamp must be compatible.
2493 if (!SIInstrInfo::hasSameClamp(*Def, MI))
2494 return false;
2495
2496 if (Def->mayRaiseFPException())
2497 return false;
2498
2499 MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
2500 if (!DefClamp)
2501 return false;
2502
2503 LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def);
2504
2505 // Clamp is applied after omod, so it is OK if omod is set.
2506 DefClamp->setImm(1);
2507
2508 Register DefReg = Def->getOperand(0).getReg();
2509 Register MIDstReg = MI.getOperand(0).getReg();
2510 if (TRI->isSGPRReg(*MRI, DefReg)) {
2511 // Pseudo scalar instructions have a SGPR for dst and clamp is a v_max*
2512 // instruction with a VGPR dst.
2513 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY),
2514 MIDstReg)
2515 .addReg(DefReg);
2516 } else {
2517 MRI->replaceRegWith(MIDstReg, DefReg);
2518 }
2519 MI.eraseFromParent();
2520
2521 // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
2522 // instruction, so we might as well convert it to the more flexible VOP3-only
2523 // mad/fma form.
2524 if (TII->convertToThreeAddress(*Def, /*LIS=*/nullptr))
2525 Def->eraseFromParent();
2526
2527 return true;
2528}
2529
2530static int getOModValue(unsigned Opc, int64_t Val) {
2531 switch (Opc) {
2532 case AMDGPU::V_MUL_F64_e64:
2533 case AMDGPU::V_MUL_F64_pseudo_e64: {
2534 switch (Val) {
2535 case 0x3fe0000000000000: // 0.5
2536 return SIOutMods::DIV2;
2537 case 0x4000000000000000: // 2.0
2538 return SIOutMods::MUL2;
2539 case 0x4010000000000000: // 4.0
2540 return SIOutMods::MUL4;
2541 default:
2542 return SIOutMods::NONE;
2543 }
2544 }
2545 case AMDGPU::V_MUL_F32_e64: {
2546 switch (static_cast<uint32_t>(Val)) {
2547 case 0x3f000000: // 0.5
2548 return SIOutMods::DIV2;
2549 case 0x40000000: // 2.0
2550 return SIOutMods::MUL2;
2551 case 0x40800000: // 4.0
2552 return SIOutMods::MUL4;
2553 default:
2554 return SIOutMods::NONE;
2555 }
2556 }
2557 case AMDGPU::V_MUL_F16_e64:
2558 case AMDGPU::V_MUL_F16_t16_e64:
2559 case AMDGPU::V_MUL_F16_fake16_e64: {
2560 switch (static_cast<uint16_t>(Val)) {
2561 case 0x3800: // 0.5
2562 return SIOutMods::DIV2;
2563 case 0x4000: // 2.0
2564 return SIOutMods::MUL2;
2565 case 0x4400: // 4.0
2566 return SIOutMods::MUL4;
2567 default:
2568 return SIOutMods::NONE;
2569 }
2570 }
2571 case AMDGPU::V_PK_MUL_BF16: {
2572 switch (static_cast<uint16_t>(Val)) {
2573 case 0x3F00: // 0.5 in BF16
2574 return SIOutMods::DIV2;
2575 case 0x4000: // 2.0 in BF16
2576 return SIOutMods::MUL2;
2577 case 0x4080: // 4.0 in BF16
2578 return SIOutMods::MUL4;
2579 default:
2580 return SIOutMods::NONE;
2581 }
2582 }
2583 default:
2584 llvm_unreachable("invalid mul opcode");
2585 }
2586}
2587
2588// FIXME: Does this really not support denormals with f16?
2589// FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
2590// handled, so will anything other than that break?
2591std::pair<const MachineOperand *, int>
2592SIFoldOperandsImpl::isOMod(const MachineInstr &MI) const {
2593 unsigned Op = MI.getOpcode();
2594 switch (Op) {
2595 case AMDGPU::V_MUL_F64_e64:
2596 case AMDGPU::V_MUL_F64_pseudo_e64:
2597 case AMDGPU::V_MUL_F32_e64:
2598 case AMDGPU::V_MUL_F16_t16_e64:
2599 case AMDGPU::V_MUL_F16_fake16_e64:
2600 case AMDGPU::V_MUL_F16_e64: {
2601 // If output denormals are enabled, omod is ignored.
2602 if ((Op == AMDGPU::V_MUL_F32_e64 &&
2604 ((Op == AMDGPU::V_MUL_F64_e64 || Op == AMDGPU::V_MUL_F64_pseudo_e64 ||
2605 Op == AMDGPU::V_MUL_F16_e64 || Op == AMDGPU::V_MUL_F16_t16_e64 ||
2606 Op == AMDGPU::V_MUL_F16_fake16_e64) &&
2609 MI.mayRaiseFPException())
2610 return {nullptr, SIOutMods::NONE};
2611
2612 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
2613 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
2614
2615 // If there is an immediate operand, it must be Src1
2616 std::optional<int64_t> Src1Imm = TII->getImmOrMaterializedImm(*MRI, *Src1);
2617 if (!Src1Imm)
2618 return {nullptr, SIOutMods::NONE};
2619
2620 int OMod = getOModValue(Op, *Src1Imm);
2621 if (OMod == SIOutMods::NONE ||
2622 TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
2623 TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
2624 TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
2625 TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
2626 return {nullptr, SIOutMods::NONE};
2627
2628 return {Src0, OMod};
2629 }
2630 case AMDGPU::V_ADD_F64_e64:
2631 case AMDGPU::V_ADD_F64_pseudo_e64:
2632 case AMDGPU::V_ADD_F32_e64:
2633 case AMDGPU::V_ADD_F16_e64:
2634 case AMDGPU::V_ADD_F16_t16_e64:
2635 case AMDGPU::V_ADD_F16_fake16_e64: {
2636 // If output denormals are enabled, omod is ignored.
2637 if ((Op == AMDGPU::V_ADD_F32_e64 &&
2639 ((Op == AMDGPU::V_ADD_F64_e64 || Op == AMDGPU::V_ADD_F64_pseudo_e64 ||
2640 Op == AMDGPU::V_ADD_F16_e64 || Op == AMDGPU::V_ADD_F16_t16_e64 ||
2641 Op == AMDGPU::V_ADD_F16_fake16_e64) &&
2643 return {nullptr, SIOutMods::NONE};
2644
2645 // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
2646 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
2647 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
2648
2649 if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
2650 Src0->getSubReg() == Src1->getSubReg() &&
2651 !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
2652 !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
2653 !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
2654 !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
2655 return {Src0, SIOutMods::MUL2};
2656
2657 return {nullptr, SIOutMods::NONE};
2658 }
2659 case AMDGPU::V_PK_MUL_BF16: {
2660 // OMOD folding for BF16 packed multiply. bf16 has no denormal mode of its
2661 // own; it follows the default ("denormal-fp-math") mode, which is the same
2662 // field as f64/f16.
2664 MI.mayRaiseFPException())
2665 return {nullptr, SIOutMods::NONE};
2666
2667 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
2668 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
2669
2670 // If there is an immediate operand, it must be Src1
2671 std::optional<int64_t> Src1Imm = TII->getImmOrMaterializedImm(*MRI, *Src1);
2672 if (!Src1Imm)
2673 return {nullptr, SIOutMods::NONE};
2674
2675 int OMod = getOModValue(AMDGPU::V_PK_MUL_BF16, *Src1Imm);
2676 if (OMod == SIOutMods::NONE)
2677 return {nullptr, SIOutMods::NONE};
2678
2679 // Modifiers other than op_sel_hi block OMOD folding. Per getOModValue
2680 // above, Src1 is an inline constant (0.5/2.0/4.0), which may carry
2681 // op_sel_lo to read it from the upper FP32 half, so allow that on src1.
2682 const MachineOperand *Src0Mods =
2683 TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
2684 const MachineOperand *Src1Mods =
2685 TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
2686 if ((Src0Mods->getImm() & ~SISrcMods::OP_SEL_1) ||
2687 (Src1Mods->getImm() & ~(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1)) ||
2688 TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
2689 TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
2690 return {nullptr, SIOutMods::NONE};
2691
2692 return {Src0, OMod};
2693 }
2694 case AMDGPU::V_PK_ADD_BF16: {
2695 // OMOD folding for BF16 packed add: x + x -> x * 2. See the bf16 denormal
2696 // mode note in the V_PK_MUL_BF16 case above.
2698 return {nullptr, SIOutMods::NONE};
2699
2700 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
2701 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
2702
2703 if (!Src0->isReg() || !Src1->isReg() || Src0->getReg() != Src1->getReg() ||
2704 Src0->getSubReg() != Src1->getSubReg())
2705 return {nullptr, SIOutMods::NONE};
2706
2707 // Modifiers other than op_sel_hi block OMOD folding
2708 const MachineOperand *Src0Mods =
2709 TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
2710 const MachineOperand *Src1Mods =
2711 TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
2712 if ((Src0Mods->getImm() & ~SISrcMods::OP_SEL_1) ||
2713 (Src1Mods->getImm() & ~SISrcMods::OP_SEL_1) ||
2714 TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
2715 TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
2716 return {nullptr, SIOutMods::NONE};
2717
2718 return {Src0, SIOutMods::MUL2};
2719 }
2720 default:
2721 return {nullptr, SIOutMods::NONE};
2722 }
2723}
2724
2725// FIXME: Does this need to check IEEE bit on function?
2726bool SIFoldOperandsImpl::tryFoldOMod(MachineInstr &MI) {
2727 const MachineOperand *RegOp;
2728 int OMod;
2729 std::tie(RegOp, OMod) = isOMod(MI);
2730 if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
2731 RegOp->getSubReg() != AMDGPU::NoSubRegister ||
2732 !MRI->hasOneNonDBGUser(RegOp->getReg()))
2733 return false;
2734
2735 MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
2736 Register OModSrcReg = Def->getOperand(0).getReg();
2737
2738 // In real-true16 mode, vgpr_16 results are packed into vgpr_32 via
2739 // REG_SEQUENCE. Look through it to find the actual instruction.
2740 if (Def->isRegSequence() && Def->getNumOperands() == 5 &&
2741 Def->getOperand(2).getImm() == AMDGPU::lo16) {
2742 // Only look through if the high 16 bits are undefined
2743 bool CanLookThrough = true;
2744 MachineInstr *Hi16Def = MRI->getVRegDef(Def->getOperand(3).getReg());
2745 if (!Hi16Def || !Hi16Def->isImplicitDef())
2746 CanLookThrough = false;
2747
2748 if (CanLookThrough) {
2749 Register SrcReg = Def->getOperand(1).getReg();
2750 if (!MRI->hasOneNonDBGUse(SrcReg))
2751 return false;
2752
2753 Def = MRI->getVRegDef(SrcReg);
2754 if (!Def)
2755 return false;
2756 }
2757 }
2758
2759 MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
2760 if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
2761 return false;
2762
2763 if (Def->mayRaiseFPException())
2764 return false;
2765
2766 // Clamp is applied after omod. If the source already has clamp set, don't
2767 // fold it.
2768 if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
2769 return false;
2770
2771 LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def);
2772
2773 DefOMod->setImm(OMod);
2774 MRI->replaceRegWith(MI.getOperand(0).getReg(), OModSrcReg);
2775 MI.eraseFromParent();
2776
2777 // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
2778 // instruction, so we might as well convert it to the more flexible VOP3-only
2779 // mad/fma form.
2780 if (TII->convertToThreeAddress(*Def, /*LIS=*/nullptr))
2781 Def->eraseFromParent();
2782
2783 return true;
2784}
2785
2786// Try to optimize SGPR reg sequences that are splat <s, s> or <s, s, s, s>
2787// where all uses are PackedSingleSGPR64BitInst, replacing with <s, undef, ...>
2788bool SIFoldOperandsImpl::tryFoldSGPRSplatRegSequence(MachineInstr &MI) {
2789 assert(MI.isRegSequence());
2790
2791 if (!ST->hasPackedFP64SingleSGPROps() && !ST->hasPackedU64SingleSGPROps())
2792 return false;
2793
2794 Register Reg = MI.getOperand(0).getReg();
2795
2796 // Only optimize 128-bit SGPR register sequences
2797 const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
2798 if (!TRI->isSGPRClass(RegClass) || TRI->getRegSizeInBits(*RegClass) != 128)
2799 return false;
2800
2802 if (!getRegSeqInit(Defs, Reg))
2803 return false;
2804
2805 // Check if this is a splat pattern
2806 if (Defs.size() <= 1)
2807 return false;
2808
2809 const auto &[FirstOp, _] = Defs.front();
2810 if (!FirstOp->isReg())
2811 return false;
2812
2813 Register FirstReg = FirstOp->getReg();
2814 unsigned FirstSubReg = FirstOp->getSubReg();
2815
2816 const TargetRegisterClass *FirstRegClass = MRI->getRegClass(FirstReg);
2817 if (!TRI->isSGPRClass(FirstRegClass))
2818 return false;
2819
2820 // Check remaining elements match first
2821 if (!llvm::all_of(llvm::drop_begin(Defs), [&](const auto &Def) {
2822 const auto &[Op, _] = Def;
2823 return Op->isReg() && Op->getReg() == FirstReg &&
2824 Op->getSubReg() == FirstSubReg;
2825 }))
2826 return false;
2827
2828 // Check if all uses are isSingleSGPRReadInst
2829 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
2831 return false;
2832 }
2833
2834 // Create new reg sequence with <s, undef, undef, ...>
2835 Register NewDst = MRI->createVirtualRegister(RegClass);
2836 MachineInstrBuilder RS = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2837 TII->get(AMDGPU::REG_SEQUENCE), NewDst);
2838
2839 // Add the first operand
2840 FirstOp->setIsKill(false);
2841 RS.add(*FirstOp);
2842 RS.addImm(Defs[0].second);
2843
2844 // Add undef for remaining lanes
2845 // Create an undef virtual register for the same register class
2846 Register UndefReg = MRI->createVirtualRegister(FirstRegClass);
2847 for (unsigned i = 1; i < Defs.size(); ++i) {
2848 RS.addReg(UndefReg, RegState::Undef);
2849 RS.addImm(Defs[i].second);
2850 }
2851
2852 // Replace all uses
2853 MRI->replaceRegWith(Reg, NewDst);
2854
2855 LLVM_DEBUG(dbgs() << "Folded splat SGPR reg_sequence: " << MI << " into "
2856 << *RS);
2857
2858 MI.eraseFromParent();
2859 return true;
2860}
2861
2862// Try to fold a reg_sequence with vgpr output and agpr inputs into an
2863// instruction which can take an agpr. So far that means a store.
2864bool SIFoldOperandsImpl::tryFoldRegSequence(MachineInstr &MI) {
2865 assert(MI.isRegSequence());
2866
2867 // Try to optimize SGPR splat sequences first
2868 if (tryFoldSGPRSplatRegSequence(MI))
2869 return true;
2870
2871 auto Reg = MI.getOperand(0).getReg();
2872
2873 if (!ST->hasGFX90AInsts() || !TRI->isVGPR(*MRI, Reg) ||
2875 return false;
2876
2878 if (!getRegSeqInit(Defs, Reg))
2879 return false;
2880
2881 for (auto &[Op, SubIdx] : Defs) {
2882 if (!Op->isReg())
2883 return false;
2884 if (TRI->isAGPR(*MRI, Op->getReg()))
2885 continue;
2886 // Maybe this is a COPY from AREG
2887 const MachineInstr *SubDef = MRI->getVRegDef(Op->getReg());
2888 if (!SubDef || !SubDef->isCopy() || SubDef->getOperand(1).getSubReg())
2889 return false;
2890 if (!TRI->isAGPR(*MRI, SubDef->getOperand(1).getReg()))
2891 return false;
2892 }
2893
2894 MachineOperand *Op = &*MRI->use_nodbg_begin(Reg);
2895 MachineInstr *UseMI = Op->getParent();
2896 while (UseMI->isCopy() && !Op->getSubReg()) {
2897 Reg = UseMI->getOperand(0).getReg();
2898 if (!TRI->isVGPR(*MRI, Reg) || !MRI->hasOneNonDBGUse(Reg))
2899 return false;
2900 Op = &*MRI->use_nodbg_begin(Reg);
2901 UseMI = Op->getParent();
2902 }
2903
2904 if (Op->getSubReg())
2905 return false;
2906
2907 unsigned OpIdx = Op - &UseMI->getOperand(0);
2908 const MCInstrDesc &InstDesc = UseMI->getDesc();
2909 const TargetRegisterClass *OpRC = TII->getRegClass(InstDesc, OpIdx);
2910 if (!OpRC || !TRI->isVectorSuperClass(OpRC))
2911 return false;
2912
2913 const auto *NewDstRC = TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg));
2914 auto Dst = MRI->createVirtualRegister(NewDstRC);
2915 auto RS = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2916 TII->get(AMDGPU::REG_SEQUENCE), Dst);
2917
2918 for (auto &[Def, SubIdx] : Defs) {
2919 Def->setIsKill(false);
2920 if (TRI->isAGPR(*MRI, Def->getReg())) {
2921 RS.add(*Def);
2922 } else { // This is a copy
2923 MachineInstr *SubDef = MRI->getVRegDef(Def->getReg());
2924 SubDef->getOperand(1).setIsKill(false);
2925 RS.addReg(SubDef->getOperand(1).getReg(), {}, Def->getSubReg());
2926 }
2927 RS.addImm(SubIdx);
2928 }
2929
2930 Op->setReg(Dst);
2931 if (!TII->isOperandLegal(*UseMI, OpIdx, Op)) {
2932 Op->setReg(Reg);
2933 RS->eraseFromParent();
2934 return false;
2935 }
2936
2937 LLVM_DEBUG(dbgs() << "Folded " << *RS << " into " << *UseMI);
2938
2939 // Erase the REG_SEQUENCE eagerly, unless we followed a chain of COPY users,
2940 // in which case we can erase them all later in runOnMachineFunction.
2941 if (MRI->use_nodbg_empty(MI.getOperand(0).getReg()))
2942 MI.eraseFromParent();
2943 return true;
2944}
2945
2946/// Checks whether \p Copy is a AGPR -> VGPR copy. Returns `true` on success and
2947/// stores the AGPR register in \p OutReg and the subreg in \p OutSubReg
2948static bool isAGPRCopy(const SIRegisterInfo &TRI,
2949 const MachineRegisterInfo &MRI, const MachineInstr &Copy,
2950 Register &OutReg, unsigned &OutSubReg) {
2951 assert(Copy.isCopy());
2952
2953 const MachineOperand &CopySrc = Copy.getOperand(1);
2954 Register CopySrcReg = CopySrc.getReg();
2955 if (!CopySrcReg.isVirtual())
2956 return false;
2957
2958 // Common case: copy from AGPR directly, e.g.
2959 // %1:vgpr_32 = COPY %0:agpr_32
2960 if (TRI.isAGPR(MRI, CopySrcReg)) {
2961 OutReg = CopySrcReg;
2962 OutSubReg = CopySrc.getSubReg();
2963 return true;
2964 }
2965
2966 // Sometimes it can also involve two copies, e.g.
2967 // %1:vgpr_256 = COPY %0:agpr_256
2968 // %2:vgpr_32 = COPY %1:vgpr_256.sub0
2969 const MachineInstr *CopySrcDef = MRI.getVRegDef(CopySrcReg);
2970 if (!CopySrcDef || !CopySrcDef->isCopy())
2971 return false;
2972
2973 const MachineOperand &OtherCopySrc = CopySrcDef->getOperand(1);
2974 Register OtherCopySrcReg = OtherCopySrc.getReg();
2975 if (!OtherCopySrcReg.isVirtual() ||
2976 CopySrcDef->getOperand(0).getSubReg() != AMDGPU::NoSubRegister ||
2977 OtherCopySrc.getSubReg() != AMDGPU::NoSubRegister ||
2978 !TRI.isAGPR(MRI, OtherCopySrcReg))
2979 return false;
2980
2981 OutReg = OtherCopySrcReg;
2982 OutSubReg = CopySrc.getSubReg();
2983 return true;
2984}
2985
2986// Try to hoist an AGPR to VGPR copy across a PHI.
2987// This should allow folding of an AGPR into a consumer which may support it.
2988//
2989// Example 1: LCSSA PHI
2990// loop:
2991// %1:vreg = COPY %0:areg
2992// exit:
2993// %2:vreg = PHI %1:vreg, %loop
2994// =>
2995// loop:
2996// exit:
2997// %1:areg = PHI %0:areg, %loop
2998// %2:vreg = COPY %1:areg
2999//
3000// Example 2: PHI with multiple incoming values:
3001// entry:
3002// %1:vreg = GLOBAL_LOAD(..)
3003// loop:
3004// %2:vreg = PHI %1:vreg, %entry, %5:vreg, %loop
3005// %3:areg = COPY %2:vreg
3006// %4:areg = (instr using %3:areg)
3007// %5:vreg = COPY %4:areg
3008// =>
3009// entry:
3010// %1:vreg = GLOBAL_LOAD(..)
3011// %2:areg = COPY %1:vreg
3012// loop:
3013// %3:areg = PHI %2:areg, %entry, %X:areg,
3014// %4:areg = (instr using %3:areg)
3015bool SIFoldOperandsImpl::tryFoldPhiAGPR(MachineInstr &PHI) {
3016 assert(PHI.isPHI());
3017
3018 Register PhiOut = PHI.getOperand(0).getReg();
3019 if (!TRI->isVGPR(*MRI, PhiOut))
3020 return false;
3021
3022 // Iterate once over all incoming values of the PHI to check if this PHI is
3023 // eligible, and determine the exact AGPR RC we'll target.
3024 const TargetRegisterClass *ARC = nullptr;
3025 for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
3026 MachineOperand &MO = PHI.getOperand(K);
3027 MachineInstr *Copy = MRI->getVRegDef(MO.getReg());
3028 if (!Copy || !Copy->isCopy())
3029 continue;
3030
3031 Register AGPRSrc;
3032 unsigned AGPRRegMask = AMDGPU::NoSubRegister;
3033 if (!isAGPRCopy(*TRI, *MRI, *Copy, AGPRSrc, AGPRRegMask))
3034 continue;
3035
3036 const TargetRegisterClass *CopyInRC = MRI->getRegClass(AGPRSrc);
3037 if (const auto *SubRC = TRI->getSubRegisterClass(CopyInRC, AGPRRegMask))
3038 CopyInRC = SubRC;
3039
3040 if (ARC && !ARC->hasSubClassEq(CopyInRC))
3041 return false;
3042 ARC = CopyInRC;
3043 }
3044
3045 if (!ARC)
3046 return false;
3047
3048 bool IsAGPR32 = (ARC == &AMDGPU::AGPR_32RegClass);
3049
3050 // Rewrite the PHI's incoming values to ARC.
3051 LLVM_DEBUG(dbgs() << "Folding AGPR copies into: " << PHI);
3052 for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
3053 MachineOperand &MO = PHI.getOperand(K);
3054 Register Reg = MO.getReg();
3055
3057 MachineBasicBlock *InsertMBB = nullptr;
3058
3059 // Look at the def of Reg, ignoring all copies.
3060 unsigned CopyOpc = AMDGPU::COPY;
3061 if (MachineInstr *Def = MRI->getVRegDef(Reg)) {
3062
3063 // Look at pre-existing COPY instructions from ARC: Steal the operand. If
3064 // the copy was single-use, it will be removed by DCE later.
3065 if (Def->isCopy()) {
3066 Register AGPRSrc;
3067 unsigned AGPRSubReg = AMDGPU::NoSubRegister;
3068 if (isAGPRCopy(*TRI, *MRI, *Def, AGPRSrc, AGPRSubReg)) {
3069 MO.setReg(AGPRSrc);
3070 MO.setSubReg(AGPRSubReg);
3071 continue;
3072 }
3073
3074 // If this is a multi-use SGPR -> VGPR copy, use V_ACCVGPR_WRITE on
3075 // GFX908 directly instead of a COPY. Otherwise, SIFoldOperand may try
3076 // to fold the sgpr -> vgpr -> agpr copy into a sgpr -> agpr copy which
3077 // is unlikely to be profitable.
3078 //
3079 // Note that V_ACCVGPR_WRITE is only used for AGPR_32.
3080 MachineOperand &CopyIn = Def->getOperand(1);
3081 if (IsAGPR32 && !ST->hasGFX90AInsts() && !MRI->hasOneNonDBGUse(Reg) &&
3082 TRI->isSGPRReg(*MRI, CopyIn.getReg()))
3083 CopyOpc = AMDGPU::V_ACCVGPR_WRITE_B32_e64;
3084 }
3085
3086 InsertMBB = Def->getParent();
3087 InsertPt = InsertMBB->SkipPHIsLabelsAndDebug(++Def->getIterator());
3088 } else {
3089 InsertMBB = PHI.getOperand(MO.getOperandNo() + 1).getMBB();
3090 InsertPt = InsertMBB->getFirstTerminator();
3091 }
3092
3093 Register NewReg = MRI->createVirtualRegister(ARC);
3094 MachineInstr *MI = BuildMI(*InsertMBB, InsertPt, PHI.getDebugLoc(),
3095 TII->get(CopyOpc), NewReg)
3096 .addReg(Reg);
3097 MO.setReg(NewReg);
3098
3099 (void)MI;
3100 LLVM_DEBUG(dbgs() << " Created COPY: " << *MI);
3101 }
3102
3103 // Replace the PHI's result with a new register.
3104 Register NewReg = MRI->createVirtualRegister(ARC);
3105 PHI.getOperand(0).setReg(NewReg);
3106
3107 // COPY that new register back to the original PhiOut register. This COPY will
3108 // usually be folded out later.
3109 MachineBasicBlock *MBB = PHI.getParent();
3110 BuildMI(*MBB, MBB->getFirstNonPHI(), PHI.getDebugLoc(),
3111 TII->get(AMDGPU::COPY), PhiOut)
3112 .addReg(NewReg);
3113
3114 LLVM_DEBUG(dbgs() << " Done: Folded " << PHI);
3115 return true;
3116}
3117
3118// Attempt to convert VGPR load to an AGPR load.
3119bool SIFoldOperandsImpl::tryFoldLoad(MachineInstr &MI) {
3120 assert(MI.mayLoad());
3121 if (!ST->hasGFX90AInsts() || MI.getNumExplicitDefs() != 1)
3122 return false;
3123
3124 MachineOperand &Def = MI.getOperand(0);
3125 if (!Def.isDef())
3126 return false;
3127
3128 Register DefReg = Def.getReg();
3129
3130 if (DefReg.isPhysical() || !TRI->isVGPR(*MRI, DefReg))
3131 return false;
3132
3135 SmallVector<Register, 8> MoveRegs;
3136
3137 if (Users.empty())
3138 return false;
3139
3140 // Check that all uses a copy to an agpr or a reg_sequence producing an agpr.
3141 while (!Users.empty()) {
3142 const MachineInstr *I = Users.pop_back_val();
3143 if (!I->isCopy() && !I->isRegSequence())
3144 return false;
3145 Register DstReg = I->getOperand(0).getReg();
3146 // Physical registers may have more than one instruction definitions
3147 if (DstReg.isPhysical())
3148 return false;
3149 if (TRI->isAGPR(*MRI, DstReg))
3150 continue;
3151 MoveRegs.push_back(DstReg);
3152 for (const MachineInstr &U : MRI->use_nodbg_instructions(DstReg))
3153 Users.push_back(&U);
3154 }
3155
3156 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
3157 MRI->setRegClass(DefReg, TRI->getEquivalentAGPRClass(RC));
3158 if (!TII->isOperandLegal(MI, 0, &Def)) {
3159 MRI->setRegClass(DefReg, RC);
3160 return false;
3161 }
3162
3163 while (!MoveRegs.empty()) {
3164 Register Reg = MoveRegs.pop_back_val();
3165 MRI->setRegClass(Reg, TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg)));
3166 }
3167
3168 LLVM_DEBUG(dbgs() << "Folded " << MI);
3169
3170 return true;
3171}
3172
3173// tryFoldPhiAGPR will aggressively try to create AGPR PHIs.
3174// For GFX90A and later, this is pretty much always a good thing, but for GFX908
3175// there's cases where it can create a lot more AGPR-AGPR copies, which are
3176// expensive on this architecture due to the lack of V_ACCVGPR_MOV.
3177//
3178// This function looks at all AGPR PHIs in a basic block and collects their
3179// operands. Then, it checks for register that are used more than once across
3180// all PHIs and caches them in a VGPR. This prevents ExpandPostRAPseudo from
3181// having to create one VGPR temporary per use, which can get very messy if
3182// these PHIs come from a broken-up large PHI (e.g. 32 AGPR phis, one per vector
3183// element).
3184//
3185// Example
3186// a:
3187// %in:agpr_256 = COPY %foo:vgpr_256
3188// c:
3189// %x:agpr_32 = ..
3190// b:
3191// %0:areg = PHI %in.sub0:agpr_32, %a, %x, %c
3192// %1:areg = PHI %in.sub0:agpr_32, %a, %y, %c
3193// %2:areg = PHI %in.sub0:agpr_32, %a, %z, %c
3194// =>
3195// a:
3196// %in:agpr_256 = COPY %foo:vgpr_256
3197// %tmp:vgpr_32 = V_ACCVGPR_READ_B32_e64 %in.sub0:agpr_32
3198// %tmp_agpr:agpr_32 = COPY %tmp
3199// c:
3200// %x:agpr_32 = ..
3201// b:
3202// %0:areg = PHI %tmp_agpr, %a, %x, %c
3203// %1:areg = PHI %tmp_agpr, %a, %y, %c
3204// %2:areg = PHI %tmp_agpr, %a, %z, %c
3205bool SIFoldOperandsImpl::tryOptimizeAGPRPhis(MachineBasicBlock &MBB) {
3206 // This is only really needed on GFX908 where AGPR-AGPR copies are
3207 // unreasonably difficult.
3208 if (ST->hasGFX90AInsts())
3209 return false;
3210
3211 // Look at all AGPR Phis and collect the register + subregister used.
3212 DenseMap<std::pair<Register, unsigned>, std::vector<MachineOperand *>>
3213 RegToMO;
3214
3215 for (auto &MI : MBB) {
3216 if (!MI.isPHI())
3217 break;
3218
3219 if (!TRI->isAGPR(*MRI, MI.getOperand(0).getReg()))
3220 continue;
3221
3222 for (unsigned K = 1; K < MI.getNumOperands(); K += 2) {
3223 MachineOperand &PhiMO = MI.getOperand(K);
3224 if (!PhiMO.getSubReg())
3225 continue;
3226 RegToMO[{PhiMO.getReg(), PhiMO.getSubReg()}].push_back(&PhiMO);
3227 }
3228 }
3229
3230 // For all (Reg, SubReg) pair that are used more than once, cache the value in
3231 // a VGPR.
3232 bool Changed = false;
3233 for (const auto &[Entry, MOs] : RegToMO) {
3234 if (MOs.size() == 1)
3235 continue;
3236
3237 const auto [Reg, SubReg] = Entry;
3238 MachineInstr *Def = MRI->getVRegDef(Reg);
3239 MachineBasicBlock *DefMBB = Def->getParent();
3240
3241 // Create a copy in a VGPR using V_ACCVGPR_READ_B32_e64 so it's not folded
3242 // out.
3243 const TargetRegisterClass *ARC = getRegOpRC(*MRI, *TRI, *MOs.front());
3244 Register TempVGPR =
3245 MRI->createVirtualRegister(TRI->getEquivalentVGPRClass(ARC));
3246 MachineInstr *VGPRCopy =
3247 BuildMI(*DefMBB, ++Def->getIterator(), Def->getDebugLoc(),
3248 TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64), TempVGPR)
3249 .addReg(Reg, /* flags */ {}, SubReg);
3250
3251 // Copy back to an AGPR and use that instead of the AGPR subreg in all MOs.
3252 Register TempAGPR = MRI->createVirtualRegister(ARC);
3253 BuildMI(*DefMBB, ++VGPRCopy->getIterator(), Def->getDebugLoc(),
3254 TII->get(AMDGPU::COPY), TempAGPR)
3255 .addReg(TempVGPR);
3256
3257 LLVM_DEBUG(dbgs() << "Caching AGPR into VGPR: " << *VGPRCopy);
3258 for (MachineOperand *MO : MOs) {
3259 MO->setReg(TempAGPR);
3260 MO->setSubReg(AMDGPU::NoSubRegister);
3261 LLVM_DEBUG(dbgs() << " Changed PHI Operand: " << *MO << "\n");
3262 }
3263
3264 Changed = true;
3265 }
3266
3267 return Changed;
3268}
3269
3270bool SIFoldOperandsImpl::run(MachineFunction &MF, const MachineLoopInfo *MLI) {
3271 this->MF = &MF;
3272 MRI = &MF.getRegInfo();
3273 ST = &MF.getSubtarget<GCNSubtarget>();
3274 TII = ST->getInstrInfo();
3275 TRI = &TII->getRegisterInfo();
3276 MFI = MF.getInfo<SIMachineFunctionInfo>();
3277 this->MLI = MLI;
3278
3279 // omod is ignored by hardware if IEEE bit is enabled. omod also does not
3280 // correctly handle signed zeros.
3281 //
3282 // FIXME: Also need to check strictfp
3283 bool IsIEEEMode = MFI->getMode().IEEE;
3284
3285 bool Changed = false;
3286 for (MachineBasicBlock *MBB : depth_first(&MF)) {
3287 MachineOperand *CurrentKnownM0Val = nullptr;
3288 for (auto &MI : make_early_inc_range(*MBB)) {
3289 Changed |= tryFoldCndMask(MI);
3290
3291 // PeepholeOptimizer may have folded an inline immediate directly onto an
3292 // instruction operand without materializing it into a register first.
3293 // Such an instruction is never reached through a def->use edge in
3294 // foldInstOperand, so try to constant fold it here.
3295 if (tryConstantFoldOp(&MI)) {
3296 Changed = true;
3297 continue;
3298 }
3299
3300 if (tryFoldRedundantAND(MI)) {
3301 Changed = true;
3302 continue;
3303 }
3304
3305 if (tryFoldAndExec(MI)) {
3306 Changed = true;
3307 continue;
3308 }
3309
3310 if (MI.isRegSequence() && tryFoldRegSequence(MI)) {
3311 Changed = true;
3312 continue;
3313 }
3314
3315 if (MI.isPHI() && tryFoldPhiAGPR(MI)) {
3316 Changed = true;
3317 continue;
3318 }
3319
3320 if (MI.mayLoad() && tryFoldLoad(MI)) {
3321 Changed = true;
3322 continue;
3323 }
3324
3325 if (tryFoldAndCSelectExec(MI)) {
3326 Changed = true;
3327 continue;
3328 }
3329
3330 if (TII->isFoldableCopy(MI)) {
3331 Changed |= tryFoldFoldableCopy(MI, CurrentKnownM0Val);
3332 continue;
3333 }
3334
3335 // Saw an unknown clobber of m0, so we no longer know what it is.
3336 if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
3337 CurrentKnownM0Val = nullptr;
3338
3339 // TODO: Omod might be OK if there is NSZ only on the source
3340 // instruction, and not the omod multiply.
3341 if (IsIEEEMode || !MI.getFlag(MachineInstr::FmNsz) || !tryFoldOMod(MI))
3342 Changed |= tryFoldClamp(MI);
3343 }
3344
3345 Changed |= tryOptimizeAGPRPhis(*MBB);
3346 }
3347
3348 return Changed;
3349}
3350
3351PreservedAnalyses
3354 MFPropsModifier _(*this, MF);
3355
3356 const MachineLoopInfo *MLI = &MFAM.getResult<MachineLoopAnalysis>(MF);
3357 bool Changed = SIFoldOperandsImpl().run(MF, MLI);
3358 if (!Changed) {
3359 return PreservedAnalyses::all();
3360 }
3362 PA.preserveSet<CFGAnalyses>();
3363 PA.preserve<MachineLoopAnalysis>();
3364 return PA;
3365}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
uint64_t uint64_t
uint64_t Imm
Rewrite undef for PHI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat)
Updates the operand at Idx in instruction Inst with the result of instruction Mat.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
static Register UseReg(const MachineOperand &MO)
#define _
IRTranslator LLVM IR MI
iv Induction Variable Users
Definition IVUsers.cpp:48
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
MachineInstr *& Lo
static bool loopModifiesExec(const MachineLoop &L, const SIRegisterInfo &TRI)
static unsigned macToMad(unsigned Opc)
static bool isAGPRCopy(const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI, const MachineInstr &Copy, Register &OutReg, unsigned &OutSubReg)
Checks whether Copy is a AGPR -> VGPR copy.
static void appendFoldCandidate(SmallVectorImpl< FoldCandidate > &FoldList, FoldCandidate &&Entry)
static unsigned getZeroHi16LegacyOpcode(const GCNSubtarget &ST, const MachineInstr &MI)
static const TargetRegisterClass * getRegOpRC(const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const MachineOperand &MO)
static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result, uint32_t LHS, uint32_t RHS)
static int getOModValue(unsigned Opc, int64_t Val)
static unsigned getMovOpc(bool IsScalar)
static MachineOperand * lookUpCopyChain(const SIInstrInfo &TII, const MachineRegisterInfo &MRI, Register SrcReg)
static constexpr AMDGPU::OpName OpSelOnlyOpNames[]
Interface definition for SIInstrInfo.
Interface definition for SIRegisterInfo.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
Value * RHS
Value * LHS
const AArch64RegisterInfo & getRegisterInfo() const
getRegisterInfo - TargetInstrInfo is a superset of MRegister info.
static const LaneMaskConstants & get(const GCNSubtarget &ST)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
const SIInstrInfo * getInstrInfo() const override
bool hasDOTOpSelHazard() const
bool zeroesHigh16BitsOfDest(unsigned Opcode) const
Returns if the result of this instruction with a 16-bit result returned in a 32-bit register implicit...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
ArrayRef< MCOperandInfo > operands() const
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
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.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg=Register(), bool SkipPseudoOp=true)
Return the first instruction in MBB after I that is not a PHI, label or debug.
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 iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
LivenessQueryResult
Possible outcome of a register liveness query to computeRegisterLiveness()
@ LQR_Dead
Register is known to be fully dead.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isImplicitDef() const
bool isCopy() const
const MachineBasicBlock * getParent() const
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
LLVM_ABI bool allImplicitDefsAreDead() const
Return true if all the implicit defs of this instruction are dead.
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
unsigned getOperandNo(const_mop_iterator I) const
Returns the number of the operand iterator I points to.
LLVM_ABI unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
mop_range implicit_operands()
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
void clearFlag(MIFlag Flag)
clearFlag - Clear a MI flag.
bool isRegSequence() const
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
MachineOperand * mop_iterator
iterator/begin/end - Iterate over all operands of a machine instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Analysis pass that exposes the MachineLoopInfo for a machine function.
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.
LLVM_ABI void substVirtReg(Register Reg, unsigned SubIdx, const TargetRegisterInfo &)
substVirtReg - Substitute the current register with the virtual subregister Reg:SubReg.
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.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
LLVM_ABI void substPhysReg(MCRegister Reg, const TargetRegisterInfo &)
substPhysReg - Substitute the current register with the physical register Reg, taking any existing Su...
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)
Register getReg() const
getReg - Returns the register number.
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_GlobalAddress
Address of a global value.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
static MachineOperand CreateFI(int Idx)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
use_nodbg_iterator use_nodbg_begin(Register RegNo) const
LLVM_ABI void markUsesInDebugValueAsUndef(Register Reg) const
markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the specified register as undefined wh...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
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...
LLVM_ABI bool hasOneNonDBGUser(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
void setRegAllocationHint(Register VReg, unsigned Type, Register PrefReg)
setRegAllocationHint - Specify a register allocation hint for the specified virtual register.
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
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...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static bool hasSameClamp(const MachineInstr &A, const MachineInstr &B)
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...
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
Register getScratchRSrcReg() const
Returns the physical register reserved for use as the resource descriptor for scratch accesses.
SIModeRegisterDefaults getMode() const
static unsigned getSubRegFromChannel(uint64_t Channel, uint64_t NumRegs=1)
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
Register getReg() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static const unsigned CommuteAnyOperandIndex
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM Value Representation.
Definition Value.h:75
self_iterator getIterator()
Definition ilist_node.h:123
IteratorT end() const
IteratorT begin() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_READONLY int32_t getMFMAEarlyClobberOp(uint32_t Opcode)
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 getVOPe32(uint32_t Opcode)
constexpr bool isSISrcOperand(const MCOperandInfo &OpInfo)
Is this an AMDGPU specific source operand?
bool isInlinableLiteralBF16(int16_t Literal, bool HasInv2Pi, bool *IsBF16)
@ OPERAND_REG_IMM_V2FP64
Definition SIDefines.h:447
@ OPERAND_REG_IMM_V2FP16
Definition SIDefines.h:440
@ OPERAND_REG_INLINE_C_FP64
Definition SIDefines.h:456
@ 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_V2BF16
Definition SIDefines.h:439
@ OPERAND_REG_INLINE_C_INT64
Definition SIDefines.h:452
@ OPERAND_REG_IMM_NOINLINE_V2FP16
Definition SIDefines.h:444
@ 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_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_REG_IMM_V2FP32
Definition SIDefines.h:446
@ OPERAND_REG_INLINE_AC_FP64
Definition SIDefines.h:472
LLVM_READONLY int32_t getFlatScratchInstSSfromSV(uint32_t Opcode)
bool supportsScaleOffset(const MCInstrInfo &MII, unsigned Opcode)
@ Entry
Definition COFF.h:862
constexpr bool isVOP3(const T &...O)
Definition SIDefines.h:239
constexpr bool isMAI(const T &...O)
Definition SIDefines.h:355
constexpr bool isSWMMAC(const T &...O)
Definition SIDefines.h:382
constexpr bool isVOP3P(const T &...O)
Definition SIDefines.h:242
constexpr bool isWMMA(const T &...O)
Definition SIDefines.h:370
constexpr bool isDOT(const T &...O)
Definition SIDefines.h:358
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:343
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
TargetInstrInfo::RegSubRegPair getRegSubRegPair(const MachineOperand &O)
Create RegSubRegPair from a register MachineOperand.
MachineBasicBlock::instr_iterator getBundleStart(MachineBasicBlock::instr_iterator I)
Returns an iterator to the first instruction in the bundle containing I.
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
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
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
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
Op::Description Desc
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
char & SIFoldOperandsLegacyID
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
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
iterator_range< df_iterator< T > > depth_first(const T &G)
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
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
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
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
DenormalModeKind Output
Denormal flushing mode for floating point instruction results in the default floating point environme...
DenormalMode FP64FP16Denormals
If this is set, neither input or output denormals are flushed for both f64 and f16/v2f16 instructions...
bool IEEE
Floating point opcodes that support exception flag gathering quiet and propagate signaling NaN inputs...
DenormalMode FP32Denormals
If this is set, neither input or output denormals are flushed for most f32 instructions.