1 //===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
9 //===----------------------------------------------------------------------===//
13 #include "AMDGPUSubtarget.h"
14 #include "SIInstrInfo.h"
15 #include "SIMachineFunctionInfo.h"
16 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetMachine.h"
24 #define DEBUG_TYPE "si-fold-operands"
29 struct FoldCandidate {
32 MachineOperand *OpToFold;
36 unsigned char UseOpNo;
37 MachineOperand::MachineOperandType Kind;
40 FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp,
41 bool Commuted_ = false) :
42 UseMI(MI), OpToFold(nullptr), UseOpNo(OpNo), Kind(FoldOp->getType()),
44 if (FoldOp->isImm()) {
45 ImmToFold = FoldOp->getImm();
46 } else if (FoldOp->isFI()) {
47 FrameIndexToFold = FoldOp->getIndex();
49 assert(FoldOp->isReg());
55 return Kind == MachineOperand::MO_FrameIndex;
59 return Kind == MachineOperand::MO_Immediate;
63 return Kind == MachineOperand::MO_Register;
66 bool isCommuted() const {
71 class SIFoldOperands : public MachineFunctionPass {
74 MachineRegisterInfo *MRI;
75 const SIInstrInfo *TII;
76 const SIRegisterInfo *TRI;
77 const SISubtarget *ST;
79 void foldOperand(MachineOperand &OpToFold,
82 SmallVectorImpl<FoldCandidate> &FoldList,
83 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
85 void foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
87 const MachineOperand *isClamp(const MachineInstr &MI) const;
88 bool tryFoldClamp(MachineInstr &MI);
90 std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
91 bool tryFoldOMod(MachineInstr &MI);
94 SIFoldOperands() : MachineFunctionPass(ID) {
95 initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry());
98 bool runOnMachineFunction(MachineFunction &MF) override;
100 StringRef getPassName() const override { return "SI Fold Operands"; }
102 void getAnalysisUsage(AnalysisUsage &AU) const override {
103 AU.setPreservesCFG();
104 MachineFunctionPass::getAnalysisUsage(AU);
108 } // End anonymous namespace.
110 INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE,
111 "SI Fold Operands", false, false)
113 char SIFoldOperands::ID = 0;
115 char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
117 // Wrapper around isInlineConstant that understands special cases when
118 // instruction types are replaced during operand folding.
119 static bool isInlineConstantIfFolded(const SIInstrInfo *TII,
120 const MachineInstr &UseMI,
122 const MachineOperand &OpToFold) {
123 if (TII->isInlineConstant(UseMI, OpNo, OpToFold))
126 unsigned Opc = UseMI.getOpcode();
128 case AMDGPU::V_MAC_F32_e64:
129 case AMDGPU::V_MAC_F16_e64: {
130 // Special case for mac. Since this is replaced with mad when folded into
131 // src2, we need to check the legality for the final instruction.
132 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
133 if (static_cast<int>(OpNo) == Src2Idx) {
134 bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
135 const MCInstrDesc &MadDesc
136 = TII->get(IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
137 return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType);
145 FunctionPass *llvm::createSIFoldOperandsPass() {
146 return new SIFoldOperands();
149 static bool updateOperand(FoldCandidate &Fold,
150 const TargetRegisterInfo &TRI) {
151 MachineInstr *MI = Fold.UseMI;
152 MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
156 Old.ChangeToImmediate(Fold.ImmToFold);
161 Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
165 MachineOperand *New = Fold.OpToFold;
166 if (TargetRegisterInfo::isVirtualRegister(Old.getReg()) &&
167 TargetRegisterInfo::isVirtualRegister(New->getReg())) {
168 Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
172 // FIXME: Handle physical registers.
177 static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
178 const MachineInstr *MI) {
179 for (auto Candidate : FoldList) {
180 if (Candidate.UseMI == MI)
186 static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
187 MachineInstr *MI, unsigned OpNo,
188 MachineOperand *OpToFold,
189 const SIInstrInfo *TII) {
190 if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
192 // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
193 unsigned Opc = MI->getOpcode();
194 if ((Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64) &&
195 (int)OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)) {
196 bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
198 // Check if changing this to a v_mad_{f16, f32} instruction will allow us
199 // to fold the operand.
200 MI->setDesc(TII->get(IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16));
201 bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII);
203 MI->untieRegOperand(OpNo);
206 MI->setDesc(TII->get(Opc));
209 // Special case for s_setreg_b32
210 if (Opc == AMDGPU::S_SETREG_B32 && OpToFold->isImm()) {
211 MI->setDesc(TII->get(AMDGPU::S_SETREG_IMM32_B32));
212 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
216 // If we are already folding into another operand of MI, then
217 // we can't commute the instruction, otherwise we risk making the
218 // other fold illegal.
219 if (isUseMIInFoldList(FoldList, MI))
222 // Operand is not legal, so try to commute the instruction to
223 // see if this makes it possible to fold.
224 unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
225 unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
226 bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
229 if (CommuteIdx0 == OpNo)
231 else if (CommuteIdx1 == OpNo)
235 // One of operands might be an Imm operand, and OpNo may refer to it after
236 // the call of commuteInstruction() below. Such situations are avoided
237 // here explicitly as OpNo must be a register operand to be a candidate
238 // for memory folding.
239 if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
240 !MI->getOperand(CommuteIdx1).isReg()))
244 !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
247 if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
248 TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1);
252 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold, true));
256 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
260 // If the use operand doesn't care about the value, this may be an operand only
261 // used for register indexing, in which case it is unsafe to fold.
262 static bool isUseSafeToFold(const SIInstrInfo *TII,
263 const MachineInstr &MI,
264 const MachineOperand &UseMO) {
265 return !UseMO.isUndef() && !TII->isSDWA(MI);
266 //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
269 void SIFoldOperands::foldOperand(
270 MachineOperand &OpToFold,
273 SmallVectorImpl<FoldCandidate> &FoldList,
274 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
275 const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
277 if (!isUseSafeToFold(TII, *UseMI, UseOp))
280 // FIXME: Fold operands with subregs.
281 if (UseOp.isReg() && OpToFold.isReg()) {
282 if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
285 // Don't fold subregister extracts into tied operands, only if it is a full
286 // copy since a subregister use tied to a full register def doesn't really
287 // make sense. e.g. don't fold:
289 // %vreg1 = COPY %vreg0:sub1
290 // %vreg2<tied3> = V_MAC_{F16, F32} %vreg3, %vreg4, %vreg1<tied0>
293 // %vreg2<tied3> = V_MAC_{F16, F32} %vreg3, %vreg4, %vreg0:sub1<tied0>
294 if (UseOp.isTied() && OpToFold.getSubReg() != AMDGPU::NoSubRegister)
298 // Special case for REG_SEQUENCE: We can't fold literals into
299 // REG_SEQUENCE instructions, so we have to fold them into the
300 // uses of REG_SEQUENCE.
301 if (UseMI->isRegSequence()) {
302 unsigned RegSeqDstReg = UseMI->getOperand(0).getReg();
303 unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
305 for (MachineRegisterInfo::use_iterator
306 RSUse = MRI->use_begin(RegSeqDstReg), RSE = MRI->use_end();
307 RSUse != RSE; ++RSUse) {
309 MachineInstr *RSUseMI = RSUse->getParent();
310 if (RSUse->getSubReg() != RegSeqDstSubReg)
313 foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList,
321 bool FoldingImm = OpToFold.isImm();
323 // In order to fold immediates into copies, we need to change the
325 if (FoldingImm && UseMI->isCopy()) {
326 unsigned DestReg = UseMI->getOperand(0).getReg();
327 const TargetRegisterClass *DestRC
328 = TargetRegisterInfo::isVirtualRegister(DestReg) ?
329 MRI->getRegClass(DestReg) :
330 TRI->getPhysRegClass(DestReg);
332 unsigned MovOp = TII->getMovOpcode(DestRC);
333 if (MovOp == AMDGPU::COPY)
336 UseMI->setDesc(TII->get(MovOp));
337 CopiesToReplace.push_back(UseMI);
339 const MCInstrDesc &UseDesc = UseMI->getDesc();
341 // Don't fold into target independent nodes. Target independent opcodes
342 // don't have defined register classes.
343 if (UseDesc.isVariadic() ||
344 UseDesc.OpInfo[UseOpIdx].RegClass == -1)
349 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
351 // FIXME: We could try to change the instruction from 64-bit to 32-bit
352 // to enable more folding opportunites. The shrink operands pass
353 // already does this.
358 const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
359 const TargetRegisterClass *FoldRC =
360 TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
363 // Split 64-bit constants into 32-bits for folding.
364 if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
365 unsigned UseReg = UseOp.getReg();
366 const TargetRegisterClass *UseRC
367 = TargetRegisterInfo::isVirtualRegister(UseReg) ?
368 MRI->getRegClass(UseReg) :
369 TRI->getPhysRegClass(UseReg);
371 if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
374 APInt Imm(64, OpToFold.getImm());
375 if (UseOp.getSubReg() == AMDGPU::sub0) {
376 Imm = Imm.getLoBits(32);
378 assert(UseOp.getSubReg() == AMDGPU::sub1);
379 Imm = Imm.getHiBits(32);
382 MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
383 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
389 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
392 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
393 uint32_t LHS, uint32_t RHS) {
395 case AMDGPU::V_AND_B32_e64:
396 case AMDGPU::V_AND_B32_e32:
397 case AMDGPU::S_AND_B32:
400 case AMDGPU::V_OR_B32_e64:
401 case AMDGPU::V_OR_B32_e32:
402 case AMDGPU::S_OR_B32:
405 case AMDGPU::V_XOR_B32_e64:
406 case AMDGPU::V_XOR_B32_e32:
407 case AMDGPU::S_XOR_B32:
410 case AMDGPU::V_LSHL_B32_e64:
411 case AMDGPU::V_LSHL_B32_e32:
412 case AMDGPU::S_LSHL_B32:
413 // The instruction ignores the high bits for out of bounds shifts.
414 Result = LHS << (RHS & 31);
416 case AMDGPU::V_LSHLREV_B32_e64:
417 case AMDGPU::V_LSHLREV_B32_e32:
418 Result = RHS << (LHS & 31);
420 case AMDGPU::V_LSHR_B32_e64:
421 case AMDGPU::V_LSHR_B32_e32:
422 case AMDGPU::S_LSHR_B32:
423 Result = LHS >> (RHS & 31);
425 case AMDGPU::V_LSHRREV_B32_e64:
426 case AMDGPU::V_LSHRREV_B32_e32:
427 Result = RHS >> (LHS & 31);
429 case AMDGPU::V_ASHR_I32_e64:
430 case AMDGPU::V_ASHR_I32_e32:
431 case AMDGPU::S_ASHR_I32:
432 Result = static_cast<int32_t>(LHS) >> (RHS & 31);
434 case AMDGPU::V_ASHRREV_I32_e64:
435 case AMDGPU::V_ASHRREV_I32_e32:
436 Result = static_cast<int32_t>(RHS) >> (LHS & 31);
443 static unsigned getMovOpc(bool IsScalar) {
444 return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
447 /// Remove any leftover implicit operands from mutating the instruction. e.g.
448 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
450 static void stripExtraCopyOperands(MachineInstr &MI) {
451 const MCInstrDesc &Desc = MI.getDesc();
452 unsigned NumOps = Desc.getNumOperands() +
453 Desc.getNumImplicitUses() +
454 Desc.getNumImplicitDefs();
456 for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
460 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
462 stripExtraCopyOperands(MI);
465 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
466 MachineOperand &Op) {
468 // If this has a subregister, it obviously is a register source.
469 if (Op.getSubReg() != AMDGPU::NoSubRegister)
472 MachineInstr *Def = MRI.getVRegDef(Op.getReg());
473 if (Def->isMoveImmediate()) {
474 MachineOperand &ImmSrc = Def->getOperand(1);
483 // Try to simplify operations with a constant that may appear after instruction
485 // TODO: See if a frame index with a fixed offset can fold.
486 static bool tryConstantFoldOp(MachineRegisterInfo &MRI,
487 const SIInstrInfo *TII,
489 MachineOperand *ImmOp) {
490 unsigned Opc = MI->getOpcode();
491 if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
492 Opc == AMDGPU::S_NOT_B32) {
493 MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm());
494 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
498 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
502 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
503 MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
504 MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
506 if (!Src0->isImm() && !Src1->isImm())
509 // and k0, k1 -> v_mov_b32 (k0 & k1)
510 // or k0, k1 -> v_mov_b32 (k0 | k1)
511 // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
512 if (Src0->isImm() && Src1->isImm()) {
514 if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
517 const SIRegisterInfo &TRI = TII->getRegisterInfo();
518 bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
520 // Be careful to change the right operand, src0 may belong to a different
522 MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
523 MI->RemoveOperand(Src1Idx);
524 mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
528 if (!MI->isCommutable())
531 if (Src0->isImm() && !Src1->isImm()) {
532 std::swap(Src0, Src1);
533 std::swap(Src0Idx, Src1Idx);
536 int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
537 if (Opc == AMDGPU::V_OR_B32_e64 ||
538 Opc == AMDGPU::V_OR_B32_e32 ||
539 Opc == AMDGPU::S_OR_B32) {
541 // y = or x, 0 => y = copy x
542 MI->RemoveOperand(Src1Idx);
543 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
544 } else if (Src1Val == -1) {
545 // y = or x, -1 => y = v_mov_b32 -1
546 MI->RemoveOperand(Src1Idx);
547 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
554 if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
555 MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
556 MI->getOpcode() == AMDGPU::S_AND_B32) {
558 // y = and x, 0 => y = v_mov_b32 0
559 MI->RemoveOperand(Src0Idx);
560 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
561 } else if (Src1Val == -1) {
562 // y = and x, -1 => y = copy x
563 MI->RemoveOperand(Src1Idx);
564 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
565 stripExtraCopyOperands(*MI);
572 if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
573 MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
574 MI->getOpcode() == AMDGPU::S_XOR_B32) {
576 // y = xor x, 0 => y = copy x
577 MI->RemoveOperand(Src1Idx);
578 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
586 // Try to fold an instruction into a simpler one
587 static bool tryFoldInst(const SIInstrInfo *TII,
589 unsigned Opc = MI->getOpcode();
591 if (Opc == AMDGPU::V_CNDMASK_B32_e32 ||
592 Opc == AMDGPU::V_CNDMASK_B32_e64 ||
593 Opc == AMDGPU::V_CNDMASK_B64_PSEUDO) {
594 const MachineOperand *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
595 const MachineOperand *Src1 = TII->getNamedOperand(*MI, AMDGPU::OpName::src1);
596 if (Src1->isIdenticalTo(*Src0)) {
597 DEBUG(dbgs() << "Folded " << *MI << " into ");
598 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
600 MI->RemoveOperand(Src2Idx);
601 MI->RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
602 mutateCopyOp(*MI, TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY
603 : getMovOpc(false)));
604 DEBUG(dbgs() << *MI << '\n');
612 void SIFoldOperands::foldInstOperand(MachineInstr &MI,
613 MachineOperand &OpToFold) const {
614 // We need mutate the operands of new mov instructions to add implicit
615 // uses of EXEC, but adding them invalidates the use_iterator, so defer
617 SmallVector<MachineInstr *, 4> CopiesToReplace;
618 SmallVector<FoldCandidate, 4> FoldList;
619 MachineOperand &Dst = MI.getOperand(0);
621 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
623 unsigned NumLiteralUses = 0;
624 MachineOperand *NonInlineUse = nullptr;
625 int NonInlineUseOpNo = -1;
627 MachineRegisterInfo::use_iterator NextUse, NextInstUse;
628 for (MachineRegisterInfo::use_iterator
629 Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
630 Use != E; Use = NextUse) {
631 NextUse = std::next(Use);
632 MachineInstr *UseMI = Use->getParent();
633 unsigned OpNo = Use.getOperandNo();
635 // Folding the immediate may reveal operations that can be constant
636 // folded or replaced with a copy. This can happen for example after
637 // frame indices are lowered to constants or from splitting 64-bit
640 // We may also encounter cases where one or both operands are
641 // immediates materialized into a register, which would ordinarily not
642 // be folded due to multiple uses or operand constraints.
644 if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) {
645 DEBUG(dbgs() << "Constant folded " << *UseMI <<'\n');
647 // Some constant folding cases change the same immediate's use to a new
648 // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user
649 // again. The same constant folded instruction could also have a second
651 NextUse = MRI->use_begin(Dst.getReg());
655 // Try to fold any inline immediate uses, and then only fold other
656 // constants if they have one use.
658 // The legality of the inline immediate must be checked based on the use
659 // operand, not the defining instruction, because 32-bit instructions
660 // with 32-bit inline immediate sources may be used to materialize
661 // constants used in 16-bit operands.
663 // e.g. it is unsafe to fold:
664 // s_mov_b32 s0, 1.0 // materializes 0x3f800000
665 // v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
667 // Folding immediates with more than one use will increase program size.
668 // FIXME: This will also reduce register usage, which may be better
669 // in some cases. A better heuristic is needed.
670 if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
671 foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
673 if (++NumLiteralUses == 1) {
674 NonInlineUse = &*Use;
675 NonInlineUseOpNo = OpNo;
680 if (NumLiteralUses == 1) {
681 MachineInstr *UseMI = NonInlineUse->getParent();
682 foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
686 for (MachineRegisterInfo::use_iterator
687 Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
689 MachineInstr *UseMI = Use->getParent();
691 foldOperand(OpToFold, UseMI, Use.getOperandNo(),
692 FoldList, CopiesToReplace);
696 MachineFunction *MF = MI.getParent()->getParent();
697 // Make sure we add EXEC uses to any new v_mov instructions created.
698 for (MachineInstr *Copy : CopiesToReplace)
699 Copy->addImplicitDefUseOperands(*MF);
701 for (FoldCandidate &Fold : FoldList) {
702 if (updateOperand(Fold, *TRI)) {
705 assert(Fold.OpToFold && Fold.OpToFold->isReg());
706 // FIXME: Probably shouldn't bother trying to fold if not an
707 // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
709 MRI->clearKillFlags(Fold.OpToFold->getReg());
711 DEBUG(dbgs() << "Folded source from " << MI << " into OpNo " <<
712 static_cast<int>(Fold.UseOpNo) << " of " << *Fold.UseMI << '\n');
713 tryFoldInst(TII, Fold.UseMI);
714 } else if (Fold.isCommuted()) {
715 // Restoring instruction's original operand order if fold has failed.
716 TII->commuteInstruction(*Fold.UseMI, false);
721 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
722 unsigned Op = MI.getOpcode();
724 case AMDGPU::V_MAX_F32_e64:
725 case AMDGPU::V_MAX_F16_e64:
726 case AMDGPU::V_MAX_F64: {
727 if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
730 // Make sure sources are identical.
731 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
732 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
733 if (!Src0->isReg() || Src0->getSubReg() != Src1->getSubReg() ||
734 Src0->getSubReg() != AMDGPU::NoSubRegister)
737 // Can't fold up if we have modifiers.
738 if (TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
739 TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
740 TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
749 // We obviously have multiple uses in a clamp since the register is used twice
750 // in the same instruction.
751 static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) {
753 for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
762 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
763 const MachineOperand *ClampSrc = isClamp(MI);
764 if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg()))
767 MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
768 if (!TII->hasFPClamp(*Def))
770 MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
774 DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def << '\n');
776 // Clamp is applied after omod, so it is OK if omod is set.
778 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
779 MI.eraseFromParent();
783 static int getOModValue(unsigned Opc, int64_t Val) {
785 case AMDGPU::V_MUL_F32_e64: {
786 switch (static_cast<uint32_t>(Val)) {
787 case 0x3f000000: // 0.5
788 return SIOutMods::DIV2;
789 case 0x40000000: // 2.0
790 return SIOutMods::MUL2;
791 case 0x40800000: // 4.0
792 return SIOutMods::MUL4;
794 return SIOutMods::NONE;
797 case AMDGPU::V_MUL_F16_e64: {
798 switch (static_cast<uint16_t>(Val)) {
800 return SIOutMods::DIV2;
802 return SIOutMods::MUL2;
804 return SIOutMods::MUL4;
806 return SIOutMods::NONE;
810 llvm_unreachable("invalid mul opcode");
814 // FIXME: Does this really not support denormals with f16?
815 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
816 // handled, so will anything other than that break?
817 std::pair<const MachineOperand *, int>
818 SIFoldOperands::isOMod(const MachineInstr &MI) const {
819 unsigned Op = MI.getOpcode();
821 case AMDGPU::V_MUL_F32_e64:
822 case AMDGPU::V_MUL_F16_e64: {
823 // If output denormals are enabled, omod is ignored.
824 if ((Op == AMDGPU::V_MUL_F32_e64 && ST->hasFP32Denormals()) ||
825 (Op == AMDGPU::V_MUL_F16_e64 && ST->hasFP16Denormals()))
826 return std::make_pair(nullptr, SIOutMods::NONE);
828 const MachineOperand *RegOp = nullptr;
829 const MachineOperand *ImmOp = nullptr;
830 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
831 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
835 } else if (Src1->isImm()) {
839 return std::make_pair(nullptr, SIOutMods::NONE);
841 int OMod = getOModValue(Op, ImmOp->getImm());
842 if (OMod == SIOutMods::NONE ||
843 TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
844 TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
845 TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
846 TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
847 return std::make_pair(nullptr, SIOutMods::NONE);
849 return std::make_pair(RegOp, OMod);
851 case AMDGPU::V_ADD_F32_e64:
852 case AMDGPU::V_ADD_F16_e64: {
853 // If output denormals are enabled, omod is ignored.
854 if ((Op == AMDGPU::V_ADD_F32_e64 && ST->hasFP32Denormals()) ||
855 (Op == AMDGPU::V_ADD_F16_e64 && ST->hasFP16Denormals()))
856 return std::make_pair(nullptr, SIOutMods::NONE);
858 // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
859 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
860 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
862 if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
863 Src0->getSubReg() == Src1->getSubReg() &&
864 !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
865 !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
866 !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
867 !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
868 return std::make_pair(Src0, SIOutMods::MUL2);
870 return std::make_pair(nullptr, SIOutMods::NONE);
873 return std::make_pair(nullptr, SIOutMods::NONE);
877 // FIXME: Does this need to check IEEE bit on function?
878 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
879 const MachineOperand *RegOp;
881 std::tie(RegOp, OMod) = isOMod(MI);
882 if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
883 RegOp->getSubReg() != AMDGPU::NoSubRegister ||
884 !hasOneNonDBGUseInst(*MRI, RegOp->getReg()))
887 MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
888 MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
889 if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
892 // Clamp is applied after omod. If the source already has clamp set, don't
894 if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
897 DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def << '\n');
899 DefOMod->setImm(OMod);
900 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
901 MI.eraseFromParent();
905 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
906 if (skipFunction(*MF.getFunction()))
909 MRI = &MF.getRegInfo();
910 ST = &MF.getSubtarget<SISubtarget>();
911 TII = ST->getInstrInfo();
912 TRI = &TII->getRegisterInfo();
914 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
916 // omod is ignored by hardware if IEEE bit is enabled. omod also does not
917 // correctly handle signed zeros.
919 // TODO: Check nsz on instructions when fast math flags are preserved to MI
921 bool IsIEEEMode = ST->enableIEEEBit(MF) || !MFI->hasNoSignedZerosFPMath();
923 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
926 MachineBasicBlock &MBB = *BI;
927 MachineBasicBlock::iterator I, Next;
928 for (I = MBB.begin(); I != MBB.end(); I = Next) {
930 MachineInstr &MI = *I;
932 tryFoldInst(TII, &MI);
934 if (!TII->isFoldableCopy(MI)) {
935 if (IsIEEEMode || !tryFoldOMod(MI))
940 MachineOperand &OpToFold = MI.getOperand(1);
941 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
943 // FIXME: We could also be folding things like TargetIndexes.
944 if (!FoldingImm && !OpToFold.isReg())
947 if (OpToFold.isReg() &&
948 !TargetRegisterInfo::isVirtualRegister(OpToFold.getReg()))
951 // Prevent folding operands backwards in the function. For example,
952 // the COPY opcode must not be replaced by 1 in this example:
954 // %vreg3<def> = COPY %VGPR0; VGPR_32:%vreg3
956 // %VGPR0<def> = V_MOV_B32_e32 1, %EXEC<imp-use>
957 MachineOperand &Dst = MI.getOperand(0);
959 !TargetRegisterInfo::isVirtualRegister(Dst.getReg()))
962 foldInstOperand(MI, OpToFold);