xref: /llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp (revision e75e197ad879177bc643d4c5d5596bbe173555e7)
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 "AMDGPU.h"
12 #include "AMDGPUSubtarget.h"
13 #include "SIInstrInfo.h"
14 #include "SIMachineFunctionInfo.h"
15 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/CodeGen/LiveIntervals.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Target/TargetMachine.h"
24 
25 #define DEBUG_TYPE "si-fold-operands"
26 using namespace llvm;
27 
28 namespace {
29 
30 struct FoldCandidate {
31   MachineInstr *UseMI;
32   union {
33     MachineOperand *OpToFold;
34     uint64_t ImmToFold;
35     int FrameIndexToFold;
36   };
37   int ShrinkOpcode;
38   unsigned char UseOpNo;
39   MachineOperand::MachineOperandType Kind;
40   bool Commuted;
41 
42   FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp,
43                 bool Commuted_ = false,
44                 int ShrinkOp = -1) :
45     UseMI(MI), OpToFold(nullptr), ShrinkOpcode(ShrinkOp), UseOpNo(OpNo),
46     Kind(FoldOp->getType()),
47     Commuted(Commuted_) {
48     if (FoldOp->isImm()) {
49       ImmToFold = FoldOp->getImm();
50     } else if (FoldOp->isFI()) {
51       FrameIndexToFold = FoldOp->getIndex();
52     } else {
53       assert(FoldOp->isReg());
54       OpToFold = FoldOp;
55     }
56   }
57 
58   bool isFI() const {
59     return Kind == MachineOperand::MO_FrameIndex;
60   }
61 
62   bool isImm() const {
63     return Kind == MachineOperand::MO_Immediate;
64   }
65 
66   bool isReg() const {
67     return Kind == MachineOperand::MO_Register;
68   }
69 
70   bool isCommuted() const {
71     return Commuted;
72   }
73 
74   bool needsShrink() const {
75     return ShrinkOpcode != -1;
76   }
77 
78   int getShrinkOpcode() const {
79     return ShrinkOpcode;
80   }
81 };
82 
83 class SIFoldOperands : public MachineFunctionPass {
84 public:
85   static char ID;
86   MachineRegisterInfo *MRI;
87   const SIInstrInfo *TII;
88   const SIRegisterInfo *TRI;
89   const GCNSubtarget *ST;
90 
91   void foldOperand(MachineOperand &OpToFold,
92                    MachineInstr *UseMI,
93                    unsigned UseOpIdx,
94                    SmallVectorImpl<FoldCandidate> &FoldList,
95                    SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
96 
97   void foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
98 
99   const MachineOperand *isClamp(const MachineInstr &MI) const;
100   bool tryFoldClamp(MachineInstr &MI);
101 
102   std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
103   bool tryFoldOMod(MachineInstr &MI);
104 
105 public:
106   SIFoldOperands() : MachineFunctionPass(ID) {
107     initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry());
108   }
109 
110   bool runOnMachineFunction(MachineFunction &MF) override;
111 
112   StringRef getPassName() const override { return "SI Fold Operands"; }
113 
114   void getAnalysisUsage(AnalysisUsage &AU) const override {
115     AU.setPreservesCFG();
116     MachineFunctionPass::getAnalysisUsage(AU);
117   }
118 };
119 
120 } // End anonymous namespace.
121 
122 INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE,
123                 "SI Fold Operands", false, false)
124 
125 char SIFoldOperands::ID = 0;
126 
127 char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
128 
129 // Wrapper around isInlineConstant that understands special cases when
130 // instruction types are replaced during operand folding.
131 static bool isInlineConstantIfFolded(const SIInstrInfo *TII,
132                                      const MachineInstr &UseMI,
133                                      unsigned OpNo,
134                                      const MachineOperand &OpToFold) {
135   if (TII->isInlineConstant(UseMI, OpNo, OpToFold))
136     return true;
137 
138   unsigned Opc = UseMI.getOpcode();
139   switch (Opc) {
140   case AMDGPU::V_MAC_F32_e64:
141   case AMDGPU::V_MAC_F16_e64:
142   case AMDGPU::V_FMAC_F32_e64: {
143     // Special case for mac. Since this is replaced with mad when folded into
144     // src2, we need to check the legality for the final instruction.
145     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
146     if (static_cast<int>(OpNo) == Src2Idx) {
147       bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e64;
148       bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
149 
150       unsigned Opc = IsFMA ?
151         AMDGPU::V_FMA_F32 : (IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
152       const MCInstrDesc &MadDesc = TII->get(Opc);
153       return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType);
154     }
155     return false;
156   }
157   default:
158     return false;
159   }
160 }
161 
162 FunctionPass *llvm::createSIFoldOperandsPass() {
163   return new SIFoldOperands();
164 }
165 
166 static bool updateOperand(FoldCandidate &Fold,
167                           const SIInstrInfo &TII,
168                           const TargetRegisterInfo &TRI,
169                           const GCNSubtarget &ST) {
170   MachineInstr *MI = Fold.UseMI;
171   MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
172   assert(Old.isReg());
173 
174   if (Fold.isImm()) {
175     if (MI->getDesc().TSFlags & SIInstrFlags::IsPacked &&
176         AMDGPU::isInlinableLiteralV216(static_cast<uint16_t>(Fold.ImmToFold),
177                                        ST.hasInv2PiInlineImm())) {
178       // Set op_sel/op_sel_hi on this operand or bail out if op_sel is
179       // already set.
180       unsigned Opcode = MI->getOpcode();
181       int OpNo = MI->getOperandNo(&Old);
182       int ModIdx = -1;
183       if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0))
184         ModIdx = AMDGPU::OpName::src0_modifiers;
185       else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1))
186         ModIdx = AMDGPU::OpName::src1_modifiers;
187       else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2))
188         ModIdx = AMDGPU::OpName::src2_modifiers;
189       assert(ModIdx != -1);
190       ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModIdx);
191       MachineOperand &Mod = MI->getOperand(ModIdx);
192       unsigned Val = Mod.getImm();
193       if ((Val & SISrcMods::OP_SEL_0) || !(Val & SISrcMods::OP_SEL_1))
194         return false;
195       // Only apply the following transformation if that operand requries
196       // a packed immediate.
197       switch (TII.get(Opcode).OpInfo[OpNo].OperandType) {
198       case AMDGPU::OPERAND_REG_IMM_V2FP16:
199       case AMDGPU::OPERAND_REG_IMM_V2INT16:
200       case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
201       case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
202         // If upper part is all zero we do not need op_sel_hi.
203         if (!isUInt<16>(Fold.ImmToFold)) {
204           if (!(Fold.ImmToFold & 0xffff)) {
205             Mod.setImm(Mod.getImm() | SISrcMods::OP_SEL_0);
206             Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
207             Old.ChangeToImmediate((Fold.ImmToFold >> 16) & 0xffff);
208             return true;
209           }
210           Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
211           Old.ChangeToImmediate(Fold.ImmToFold & 0xffff);
212           return true;
213         }
214         break;
215       default:
216         break;
217       }
218     }
219   }
220 
221   if ((Fold.isImm() || Fold.isFI()) && Fold.needsShrink()) {
222     MachineBasicBlock *MBB = MI->getParent();
223     auto Liveness = MBB->computeRegisterLiveness(&TRI, AMDGPU::VCC, MI);
224     if (Liveness != MachineBasicBlock::LQR_Dead)
225       return false;
226 
227     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
228     int Op32 = Fold.getShrinkOpcode();
229     MachineOperand &Dst0 = MI->getOperand(0);
230     MachineOperand &Dst1 = MI->getOperand(1);
231     assert(Dst0.isDef() && Dst1.isDef());
232 
233     bool HaveNonDbgCarryUse = !MRI.use_nodbg_empty(Dst1.getReg());
234 
235     const TargetRegisterClass *Dst0RC = MRI.getRegClass(Dst0.getReg());
236     unsigned NewReg0 = MRI.createVirtualRegister(Dst0RC);
237 
238     MachineInstr *Inst32 = TII.buildShrunkInst(*MI, Op32);
239 
240     if (HaveNonDbgCarryUse) {
241       BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::COPY), Dst1.getReg())
242         .addReg(AMDGPU::VCC, RegState::Kill);
243     }
244 
245     // Keep the old instruction around to avoid breaking iterators, but
246     // replace it with a dummy instruction to remove uses.
247     //
248     // FIXME: We should not invert how this pass looks at operands to avoid
249     // this. Should track set of foldable movs instead of looking for uses
250     // when looking at a use.
251     Dst0.setReg(NewReg0);
252     for (unsigned I = MI->getNumOperands() - 1; I > 0; --I)
253       MI->RemoveOperand(I);
254     MI->setDesc(TII.get(AMDGPU::IMPLICIT_DEF));
255 
256     if (Fold.isCommuted())
257       TII.commuteInstruction(*Inst32, false);
258     return true;
259   }
260 
261   assert(!Fold.needsShrink() && "not handled");
262 
263   if (Fold.isImm()) {
264     Old.ChangeToImmediate(Fold.ImmToFold);
265     return true;
266   }
267 
268   if (Fold.isFI()) {
269     Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
270     return true;
271   }
272 
273   MachineOperand *New = Fold.OpToFold;
274   Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
275   Old.setIsUndef(New->isUndef());
276   return true;
277 }
278 
279 static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
280                               const MachineInstr *MI) {
281   for (auto Candidate : FoldList) {
282     if (Candidate.UseMI == MI)
283       return true;
284   }
285   return false;
286 }
287 
288 static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
289                              MachineInstr *MI, unsigned OpNo,
290                              MachineOperand *OpToFold,
291                              const SIInstrInfo *TII) {
292   if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
293 
294     // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
295     unsigned Opc = MI->getOpcode();
296     if ((Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
297          Opc == AMDGPU::V_FMAC_F32_e64) &&
298         (int)OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)) {
299       bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e64;
300       bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
301       unsigned NewOpc = IsFMA ?
302         AMDGPU::V_FMA_F32 : (IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
303 
304       // Check if changing this to a v_mad_{f16, f32} instruction will allow us
305       // to fold the operand.
306       MI->setDesc(TII->get(NewOpc));
307       bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII);
308       if (FoldAsMAD) {
309         MI->untieRegOperand(OpNo);
310         return true;
311       }
312       MI->setDesc(TII->get(Opc));
313     }
314 
315     // Special case for s_setreg_b32
316     if (Opc == AMDGPU::S_SETREG_B32 && OpToFold->isImm()) {
317       MI->setDesc(TII->get(AMDGPU::S_SETREG_IMM32_B32));
318       FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
319       return true;
320     }
321 
322     // If we are already folding into another operand of MI, then
323     // we can't commute the instruction, otherwise we risk making the
324     // other fold illegal.
325     if (isUseMIInFoldList(FoldList, MI))
326       return false;
327 
328     unsigned CommuteOpNo = OpNo;
329 
330     // Operand is not legal, so try to commute the instruction to
331     // see if this makes it possible to fold.
332     unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
333     unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
334     bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
335 
336     if (CanCommute) {
337       if (CommuteIdx0 == OpNo)
338         CommuteOpNo = CommuteIdx1;
339       else if (CommuteIdx1 == OpNo)
340         CommuteOpNo = CommuteIdx0;
341     }
342 
343 
344     // One of operands might be an Imm operand, and OpNo may refer to it after
345     // the call of commuteInstruction() below. Such situations are avoided
346     // here explicitly as OpNo must be a register operand to be a candidate
347     // for memory folding.
348     if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
349                        !MI->getOperand(CommuteIdx1).isReg()))
350       return false;
351 
352     if (!CanCommute ||
353         !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
354       return false;
355 
356     if (!TII->isOperandLegal(*MI, CommuteOpNo, OpToFold)) {
357       if ((Opc == AMDGPU::V_ADD_I32_e64 ||
358            Opc == AMDGPU::V_SUB_I32_e64 ||
359            Opc == AMDGPU::V_SUBREV_I32_e64) && // FIXME
360           (OpToFold->isImm() || OpToFold->isFI())) {
361         MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
362 
363         // Verify the other operand is a VGPR, otherwise we would violate the
364         // constant bus restriction.
365         unsigned OtherIdx = CommuteOpNo == CommuteIdx0 ? CommuteIdx1 : CommuteIdx0;
366         MachineOperand &OtherOp = MI->getOperand(OtherIdx);
367         if (!OtherOp.isReg() ||
368             !TII->getRegisterInfo().isVGPR(MRI, OtherOp.getReg()))
369           return false;
370 
371         assert(MI->getOperand(1).isDef());
372 
373         // Make sure to get the 32-bit version of the commuted opcode.
374         unsigned MaybeCommutedOpc = MI->getOpcode();
375         int Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc);
376 
377         FoldList.push_back(FoldCandidate(MI, CommuteOpNo, OpToFold, true,
378                                          Op32));
379         return true;
380       }
381 
382       TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1);
383       return false;
384     }
385 
386     FoldList.push_back(FoldCandidate(MI, CommuteOpNo, OpToFold, true));
387     return true;
388   }
389 
390   FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
391   return true;
392 }
393 
394 // If the use operand doesn't care about the value, this may be an operand only
395 // used for register indexing, in which case it is unsafe to fold.
396 static bool isUseSafeToFold(const SIInstrInfo *TII,
397                             const MachineInstr &MI,
398                             const MachineOperand &UseMO) {
399   return !UseMO.isUndef() && !TII->isSDWA(MI);
400   //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
401 }
402 
403 void SIFoldOperands::foldOperand(
404   MachineOperand &OpToFold,
405   MachineInstr *UseMI,
406   unsigned UseOpIdx,
407   SmallVectorImpl<FoldCandidate> &FoldList,
408   SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
409   const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
410 
411   if (!isUseSafeToFold(TII, *UseMI, UseOp))
412     return;
413 
414   // FIXME: Fold operands with subregs.
415   if (UseOp.isReg() && OpToFold.isReg()) {
416     if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
417       return;
418 
419     // Don't fold subregister extracts into tied operands, only if it is a full
420     // copy since a subregister use tied to a full register def doesn't really
421     // make sense. e.g. don't fold:
422     //
423     // %1 = COPY %0:sub1
424     // %2<tied3> = V_MAC_{F16, F32} %3, %4, %1<tied0>
425     //
426     //  into
427     // %2<tied3> = V_MAC_{F16, F32} %3, %4, %0:sub1<tied0>
428     if (UseOp.isTied() && OpToFold.getSubReg() != AMDGPU::NoSubRegister)
429       return;
430   }
431 
432   // Special case for REG_SEQUENCE: We can't fold literals into
433   // REG_SEQUENCE instructions, so we have to fold them into the
434   // uses of REG_SEQUENCE.
435   if (UseMI->isRegSequence()) {
436     unsigned RegSeqDstReg = UseMI->getOperand(0).getReg();
437     unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
438 
439     for (MachineRegisterInfo::use_iterator
440            RSUse = MRI->use_begin(RegSeqDstReg), RSE = MRI->use_end();
441          RSUse != RSE; ++RSUse) {
442 
443       MachineInstr *RSUseMI = RSUse->getParent();
444       if (RSUse->getSubReg() != RegSeqDstSubReg)
445         continue;
446 
447       foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList,
448                   CopiesToReplace);
449     }
450 
451     return;
452   }
453 
454 
455   bool FoldingImm = OpToFold.isImm();
456 
457   if (FoldingImm && UseMI->isCopy()) {
458     unsigned DestReg = UseMI->getOperand(0).getReg();
459     const TargetRegisterClass *DestRC
460       = TargetRegisterInfo::isVirtualRegister(DestReg) ?
461       MRI->getRegClass(DestReg) :
462       TRI->getPhysRegClass(DestReg);
463 
464     unsigned SrcReg  = UseMI->getOperand(1).getReg();
465     if (TargetRegisterInfo::isVirtualRegister(DestReg) &&
466       TargetRegisterInfo::isVirtualRegister(SrcReg)) {
467       const TargetRegisterClass * SrcRC = MRI->getRegClass(SrcReg);
468       if (TRI->isSGPRClass(SrcRC) && TRI->hasVGPRs(DestRC)) {
469         MachineRegisterInfo::use_iterator NextUse;
470         SmallVector<FoldCandidate, 4> CopyUses;
471         for (MachineRegisterInfo::use_iterator
472           Use = MRI->use_begin(DestReg), E = MRI->use_end();
473           Use != E; Use = NextUse) {
474           NextUse = std::next(Use);
475           FoldCandidate FC = FoldCandidate(Use->getParent(),
476            Use.getOperandNo(), &UseMI->getOperand(1));
477           CopyUses.push_back(FC);
478        }
479         for (auto & F : CopyUses) {
480           foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo,
481            FoldList, CopiesToReplace);
482         }
483       }
484     }
485 
486     // In order to fold immediates into copies, we need to change the
487     // copy to a MOV.
488 
489     unsigned MovOp = TII->getMovOpcode(DestRC);
490     if (MovOp == AMDGPU::COPY)
491       return;
492 
493     UseMI->setDesc(TII->get(MovOp));
494     CopiesToReplace.push_back(UseMI);
495   } else {
496     if (UseMI->isCopy() && OpToFold.isReg() &&
497         TargetRegisterInfo::isVirtualRegister(UseMI->getOperand(0).getReg()) &&
498         TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) &&
499         TRI->isVGPR(*MRI, UseMI->getOperand(1).getReg()) &&
500         !UseMI->getOperand(1).getSubReg()) {
501       UseMI->getOperand(1).setReg(OpToFold.getReg());
502       UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
503       UseMI->getOperand(1).setIsKill(false);
504       CopiesToReplace.push_back(UseMI);
505       OpToFold.setIsKill(false);
506       return;
507     }
508 
509     const MCInstrDesc &UseDesc = UseMI->getDesc();
510 
511     // Don't fold into target independent nodes.  Target independent opcodes
512     // don't have defined register classes.
513     if (UseDesc.isVariadic() ||
514         UseOp.isImplicit() ||
515         UseDesc.OpInfo[UseOpIdx].RegClass == -1)
516       return;
517   }
518 
519   if (!FoldingImm) {
520     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
521 
522     // FIXME: We could try to change the instruction from 64-bit to 32-bit
523     // to enable more folding opportunites.  The shrink operands pass
524     // already does this.
525     return;
526   }
527 
528 
529   const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
530   const TargetRegisterClass *FoldRC =
531     TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
532 
533   // Split 64-bit constants into 32-bits for folding.
534   if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
535     unsigned UseReg = UseOp.getReg();
536     const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg);
537 
538     if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
539       return;
540 
541     APInt Imm(64, OpToFold.getImm());
542     if (UseOp.getSubReg() == AMDGPU::sub0) {
543       Imm = Imm.getLoBits(32);
544     } else {
545       assert(UseOp.getSubReg() == AMDGPU::sub1);
546       Imm = Imm.getHiBits(32);
547     }
548 
549     MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
550     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
551     return;
552   }
553 
554 
555 
556   tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
557 }
558 
559 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
560                                   uint32_t LHS, uint32_t RHS) {
561   switch (Opcode) {
562   case AMDGPU::V_AND_B32_e64:
563   case AMDGPU::V_AND_B32_e32:
564   case AMDGPU::S_AND_B32:
565     Result = LHS & RHS;
566     return true;
567   case AMDGPU::V_OR_B32_e64:
568   case AMDGPU::V_OR_B32_e32:
569   case AMDGPU::S_OR_B32:
570     Result = LHS | RHS;
571     return true;
572   case AMDGPU::V_XOR_B32_e64:
573   case AMDGPU::V_XOR_B32_e32:
574   case AMDGPU::S_XOR_B32:
575     Result = LHS ^ RHS;
576     return true;
577   case AMDGPU::V_LSHL_B32_e64:
578   case AMDGPU::V_LSHL_B32_e32:
579   case AMDGPU::S_LSHL_B32:
580     // The instruction ignores the high bits for out of bounds shifts.
581     Result = LHS << (RHS & 31);
582     return true;
583   case AMDGPU::V_LSHLREV_B32_e64:
584   case AMDGPU::V_LSHLREV_B32_e32:
585     Result = RHS << (LHS & 31);
586     return true;
587   case AMDGPU::V_LSHR_B32_e64:
588   case AMDGPU::V_LSHR_B32_e32:
589   case AMDGPU::S_LSHR_B32:
590     Result = LHS >> (RHS & 31);
591     return true;
592   case AMDGPU::V_LSHRREV_B32_e64:
593   case AMDGPU::V_LSHRREV_B32_e32:
594     Result = RHS >> (LHS & 31);
595     return true;
596   case AMDGPU::V_ASHR_I32_e64:
597   case AMDGPU::V_ASHR_I32_e32:
598   case AMDGPU::S_ASHR_I32:
599     Result = static_cast<int32_t>(LHS) >> (RHS & 31);
600     return true;
601   case AMDGPU::V_ASHRREV_I32_e64:
602   case AMDGPU::V_ASHRREV_I32_e32:
603     Result = static_cast<int32_t>(RHS) >> (LHS & 31);
604     return true;
605   default:
606     return false;
607   }
608 }
609 
610 static unsigned getMovOpc(bool IsScalar) {
611   return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
612 }
613 
614 /// Remove any leftover implicit operands from mutating the instruction. e.g.
615 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
616 /// anymore.
617 static void stripExtraCopyOperands(MachineInstr &MI) {
618   const MCInstrDesc &Desc = MI.getDesc();
619   unsigned NumOps = Desc.getNumOperands() +
620                     Desc.getNumImplicitUses() +
621                     Desc.getNumImplicitDefs();
622 
623   for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
624     MI.RemoveOperand(I);
625 }
626 
627 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
628   MI.setDesc(NewDesc);
629   stripExtraCopyOperands(MI);
630 }
631 
632 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
633                                                MachineOperand &Op) {
634   if (Op.isReg()) {
635     // If this has a subregister, it obviously is a register source.
636     if (Op.getSubReg() != AMDGPU::NoSubRegister ||
637         !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
638       return &Op;
639 
640     MachineInstr *Def = MRI.getVRegDef(Op.getReg());
641     if (Def && Def->isMoveImmediate()) {
642       MachineOperand &ImmSrc = Def->getOperand(1);
643       if (ImmSrc.isImm())
644         return &ImmSrc;
645     }
646   }
647 
648   return &Op;
649 }
650 
651 // Try to simplify operations with a constant that may appear after instruction
652 // selection.
653 // TODO: See if a frame index with a fixed offset can fold.
654 static bool tryConstantFoldOp(MachineRegisterInfo &MRI,
655                               const SIInstrInfo *TII,
656                               MachineInstr *MI,
657                               MachineOperand *ImmOp) {
658   unsigned Opc = MI->getOpcode();
659   if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
660       Opc == AMDGPU::S_NOT_B32) {
661     MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm());
662     mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
663     return true;
664   }
665 
666   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
667   if (Src1Idx == -1)
668     return false;
669 
670   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
671   MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
672   MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
673 
674   if (!Src0->isImm() && !Src1->isImm())
675     return false;
676 
677   if (MI->getOpcode() == AMDGPU::V_LSHL_OR_B32) {
678     if (Src0->isImm() && Src0->getImm() == 0) {
679       // v_lshl_or_b32 0, X, Y -> copy Y
680       // v_lshl_or_b32 0, X, K -> v_mov_b32 K
681       bool UseCopy = TII->getNamedOperand(*MI, AMDGPU::OpName::src2)->isReg();
682       MI->RemoveOperand(Src1Idx);
683       MI->RemoveOperand(Src0Idx);
684 
685       MI->setDesc(TII->get(UseCopy ? AMDGPU::COPY : AMDGPU::V_MOV_B32_e32));
686       return true;
687     }
688   }
689 
690   // and k0, k1 -> v_mov_b32 (k0 & k1)
691   // or k0, k1 -> v_mov_b32 (k0 | k1)
692   // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
693   if (Src0->isImm() && Src1->isImm()) {
694     int32_t NewImm;
695     if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
696       return false;
697 
698     const SIRegisterInfo &TRI = TII->getRegisterInfo();
699     bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
700 
701     // Be careful to change the right operand, src0 may belong to a different
702     // instruction.
703     MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
704     MI->RemoveOperand(Src1Idx);
705     mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
706     return true;
707   }
708 
709   if (!MI->isCommutable())
710     return false;
711 
712   if (Src0->isImm() && !Src1->isImm()) {
713     std::swap(Src0, Src1);
714     std::swap(Src0Idx, Src1Idx);
715   }
716 
717   int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
718   if (Opc == AMDGPU::V_OR_B32_e64 ||
719       Opc == AMDGPU::V_OR_B32_e32 ||
720       Opc == AMDGPU::S_OR_B32) {
721     if (Src1Val == 0) {
722       // y = or x, 0 => y = copy x
723       MI->RemoveOperand(Src1Idx);
724       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
725     } else if (Src1Val == -1) {
726       // y = or x, -1 => y = v_mov_b32 -1
727       MI->RemoveOperand(Src1Idx);
728       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
729     } else
730       return false;
731 
732     return true;
733   }
734 
735   if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
736       MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
737       MI->getOpcode() == AMDGPU::S_AND_B32) {
738     if (Src1Val == 0) {
739       // y = and x, 0 => y = v_mov_b32 0
740       MI->RemoveOperand(Src0Idx);
741       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
742     } else if (Src1Val == -1) {
743       // y = and x, -1 => y = copy x
744       MI->RemoveOperand(Src1Idx);
745       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
746       stripExtraCopyOperands(*MI);
747     } else
748       return false;
749 
750     return true;
751   }
752 
753   if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
754       MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
755       MI->getOpcode() == AMDGPU::S_XOR_B32) {
756     if (Src1Val == 0) {
757       // y = xor x, 0 => y = copy x
758       MI->RemoveOperand(Src1Idx);
759       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
760       return true;
761     }
762   }
763 
764   return false;
765 }
766 
767 // Try to fold an instruction into a simpler one
768 static bool tryFoldInst(const SIInstrInfo *TII,
769                         MachineInstr *MI) {
770   unsigned Opc = MI->getOpcode();
771 
772   if (Opc == AMDGPU::V_CNDMASK_B32_e32    ||
773       Opc == AMDGPU::V_CNDMASK_B32_e64    ||
774       Opc == AMDGPU::V_CNDMASK_B64_PSEUDO) {
775     const MachineOperand *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
776     const MachineOperand *Src1 = TII->getNamedOperand(*MI, AMDGPU::OpName::src1);
777     int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
778     int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
779     if (Src1->isIdenticalTo(*Src0) &&
780         (Src1ModIdx == -1 || !MI->getOperand(Src1ModIdx).getImm()) &&
781         (Src0ModIdx == -1 || !MI->getOperand(Src0ModIdx).getImm())) {
782       LLVM_DEBUG(dbgs() << "Folded " << *MI << " into ");
783       auto &NewDesc =
784           TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false));
785       int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
786       if (Src2Idx != -1)
787         MI->RemoveOperand(Src2Idx);
788       MI->RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
789       if (Src1ModIdx != -1)
790         MI->RemoveOperand(Src1ModIdx);
791       if (Src0ModIdx != -1)
792         MI->RemoveOperand(Src0ModIdx);
793       mutateCopyOp(*MI, NewDesc);
794       LLVM_DEBUG(dbgs() << *MI << '\n');
795       return true;
796     }
797   }
798 
799   return false;
800 }
801 
802 void SIFoldOperands::foldInstOperand(MachineInstr &MI,
803                                      MachineOperand &OpToFold) const {
804   // We need mutate the operands of new mov instructions to add implicit
805   // uses of EXEC, but adding them invalidates the use_iterator, so defer
806   // this.
807   SmallVector<MachineInstr *, 4> CopiesToReplace;
808   SmallVector<FoldCandidate, 4> FoldList;
809   MachineOperand &Dst = MI.getOperand(0);
810 
811   bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
812   if (FoldingImm) {
813     unsigned NumLiteralUses = 0;
814     MachineOperand *NonInlineUse = nullptr;
815     int NonInlineUseOpNo = -1;
816 
817     MachineRegisterInfo::use_iterator NextUse;
818     for (MachineRegisterInfo::use_iterator
819            Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
820          Use != E; Use = NextUse) {
821       NextUse = std::next(Use);
822       MachineInstr *UseMI = Use->getParent();
823       unsigned OpNo = Use.getOperandNo();
824 
825       // Folding the immediate may reveal operations that can be constant
826       // folded or replaced with a copy. This can happen for example after
827       // frame indices are lowered to constants or from splitting 64-bit
828       // constants.
829       //
830       // We may also encounter cases where one or both operands are
831       // immediates materialized into a register, which would ordinarily not
832       // be folded due to multiple uses or operand constraints.
833 
834       if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) {
835         LLVM_DEBUG(dbgs() << "Constant folded " << *UseMI << '\n');
836 
837         // Some constant folding cases change the same immediate's use to a new
838         // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user
839         // again. The same constant folded instruction could also have a second
840         // use operand.
841         NextUse = MRI->use_begin(Dst.getReg());
842         FoldList.clear();
843         continue;
844       }
845 
846       // Try to fold any inline immediate uses, and then only fold other
847       // constants if they have one use.
848       //
849       // The legality of the inline immediate must be checked based on the use
850       // operand, not the defining instruction, because 32-bit instructions
851       // with 32-bit inline immediate sources may be used to materialize
852       // constants used in 16-bit operands.
853       //
854       // e.g. it is unsafe to fold:
855       //  s_mov_b32 s0, 1.0    // materializes 0x3f800000
856       //  v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
857 
858       // Folding immediates with more than one use will increase program size.
859       // FIXME: This will also reduce register usage, which may be better
860       // in some cases. A better heuristic is needed.
861       if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
862         foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
863       } else {
864         if (++NumLiteralUses == 1) {
865           NonInlineUse = &*Use;
866           NonInlineUseOpNo = OpNo;
867         }
868       }
869     }
870 
871     if (NumLiteralUses == 1) {
872       MachineInstr *UseMI = NonInlineUse->getParent();
873       foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
874     }
875   } else {
876     // Folding register.
877     SmallVector <MachineRegisterInfo::use_iterator, 4> UsesToProcess;
878     for (MachineRegisterInfo::use_iterator
879            Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
880          Use != E; ++Use) {
881       UsesToProcess.push_back(Use);
882     }
883     for (auto U : UsesToProcess) {
884       MachineInstr *UseMI = U->getParent();
885 
886       foldOperand(OpToFold, UseMI, U.getOperandNo(),
887         FoldList, CopiesToReplace);
888     }
889   }
890 
891   MachineFunction *MF = MI.getParent()->getParent();
892   // Make sure we add EXEC uses to any new v_mov instructions created.
893   for (MachineInstr *Copy : CopiesToReplace)
894     Copy->addImplicitDefUseOperands(*MF);
895 
896   for (FoldCandidate &Fold : FoldList) {
897     if (updateOperand(Fold, *TII, *TRI, *ST)) {
898       // Clear kill flags.
899       if (Fold.isReg()) {
900         assert(Fold.OpToFold && Fold.OpToFold->isReg());
901         // FIXME: Probably shouldn't bother trying to fold if not an
902         // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
903         // copies.
904         MRI->clearKillFlags(Fold.OpToFold->getReg());
905       }
906       LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
907                         << static_cast<int>(Fold.UseOpNo) << " of "
908                         << *Fold.UseMI << '\n');
909       tryFoldInst(TII, Fold.UseMI);
910     } else if (Fold.isCommuted()) {
911       // Restoring instruction's original operand order if fold has failed.
912       TII->commuteInstruction(*Fold.UseMI, false);
913     }
914   }
915 }
916 
917 // Clamp patterns are canonically selected to v_max_* instructions, so only
918 // handle them.
919 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
920   unsigned Op = MI.getOpcode();
921   switch (Op) {
922   case AMDGPU::V_MAX_F32_e64:
923   case AMDGPU::V_MAX_F16_e64:
924   case AMDGPU::V_MAX_F64:
925   case AMDGPU::V_PK_MAX_F16: {
926     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
927       return nullptr;
928 
929     // Make sure sources are identical.
930     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
931     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
932     if (!Src0->isReg() || !Src1->isReg() ||
933         Src0->getReg() != Src1->getReg() ||
934         Src0->getSubReg() != Src1->getSubReg() ||
935         Src0->getSubReg() != AMDGPU::NoSubRegister)
936       return nullptr;
937 
938     // Can't fold up if we have modifiers.
939     if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
940       return nullptr;
941 
942     unsigned Src0Mods
943       = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
944     unsigned Src1Mods
945       = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
946 
947     // Having a 0 op_sel_hi would require swizzling the output in the source
948     // instruction, which we can't do.
949     unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
950                                                       : 0u;
951     if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
952       return nullptr;
953     return Src0;
954   }
955   default:
956     return nullptr;
957   }
958 }
959 
960 // We obviously have multiple uses in a clamp since the register is used twice
961 // in the same instruction.
962 static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) {
963   int Count = 0;
964   for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
965        I != E; ++I) {
966     if (++Count > 1)
967       return false;
968   }
969 
970   return true;
971 }
972 
973 // FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
974 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
975   const MachineOperand *ClampSrc = isClamp(MI);
976   if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg()))
977     return false;
978 
979   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
980 
981   // The type of clamp must be compatible.
982   if (TII->getClampMask(*Def) != TII->getClampMask(MI))
983     return false;
984 
985   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
986   if (!DefClamp)
987     return false;
988 
989   LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def
990                     << '\n');
991 
992   // Clamp is applied after omod, so it is OK if omod is set.
993   DefClamp->setImm(1);
994   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
995   MI.eraseFromParent();
996   return true;
997 }
998 
999 static int getOModValue(unsigned Opc, int64_t Val) {
1000   switch (Opc) {
1001   case AMDGPU::V_MUL_F32_e64: {
1002     switch (static_cast<uint32_t>(Val)) {
1003     case 0x3f000000: // 0.5
1004       return SIOutMods::DIV2;
1005     case 0x40000000: // 2.0
1006       return SIOutMods::MUL2;
1007     case 0x40800000: // 4.0
1008       return SIOutMods::MUL4;
1009     default:
1010       return SIOutMods::NONE;
1011     }
1012   }
1013   case AMDGPU::V_MUL_F16_e64: {
1014     switch (static_cast<uint16_t>(Val)) {
1015     case 0x3800: // 0.5
1016       return SIOutMods::DIV2;
1017     case 0x4000: // 2.0
1018       return SIOutMods::MUL2;
1019     case 0x4400: // 4.0
1020       return SIOutMods::MUL4;
1021     default:
1022       return SIOutMods::NONE;
1023     }
1024   }
1025   default:
1026     llvm_unreachable("invalid mul opcode");
1027   }
1028 }
1029 
1030 // FIXME: Does this really not support denormals with f16?
1031 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1032 // handled, so will anything other than that break?
1033 std::pair<const MachineOperand *, int>
1034 SIFoldOperands::isOMod(const MachineInstr &MI) const {
1035   unsigned Op = MI.getOpcode();
1036   switch (Op) {
1037   case AMDGPU::V_MUL_F32_e64:
1038   case AMDGPU::V_MUL_F16_e64: {
1039     // If output denormals are enabled, omod is ignored.
1040     if ((Op == AMDGPU::V_MUL_F32_e64 && ST->hasFP32Denormals()) ||
1041         (Op == AMDGPU::V_MUL_F16_e64 && ST->hasFP16Denormals()))
1042       return std::make_pair(nullptr, SIOutMods::NONE);
1043 
1044     const MachineOperand *RegOp = nullptr;
1045     const MachineOperand *ImmOp = nullptr;
1046     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1047     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1048     if (Src0->isImm()) {
1049       ImmOp = Src0;
1050       RegOp = Src1;
1051     } else if (Src1->isImm()) {
1052       ImmOp = Src1;
1053       RegOp = Src0;
1054     } else
1055       return std::make_pair(nullptr, SIOutMods::NONE);
1056 
1057     int OMod = getOModValue(Op, ImmOp->getImm());
1058     if (OMod == SIOutMods::NONE ||
1059         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1060         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1061         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1062         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1063       return std::make_pair(nullptr, SIOutMods::NONE);
1064 
1065     return std::make_pair(RegOp, OMod);
1066   }
1067   case AMDGPU::V_ADD_F32_e64:
1068   case AMDGPU::V_ADD_F16_e64: {
1069     // If output denormals are enabled, omod is ignored.
1070     if ((Op == AMDGPU::V_ADD_F32_e64 && ST->hasFP32Denormals()) ||
1071         (Op == AMDGPU::V_ADD_F16_e64 && ST->hasFP16Denormals()))
1072       return std::make_pair(nullptr, SIOutMods::NONE);
1073 
1074     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1075     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1076     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1077 
1078     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1079         Src0->getSubReg() == Src1->getSubReg() &&
1080         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1081         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1082         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1083         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1084       return std::make_pair(Src0, SIOutMods::MUL2);
1085 
1086     return std::make_pair(nullptr, SIOutMods::NONE);
1087   }
1088   default:
1089     return std::make_pair(nullptr, SIOutMods::NONE);
1090   }
1091 }
1092 
1093 // FIXME: Does this need to check IEEE bit on function?
1094 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
1095   const MachineOperand *RegOp;
1096   int OMod;
1097   std::tie(RegOp, OMod) = isOMod(MI);
1098   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1099       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1100       !hasOneNonDBGUseInst(*MRI, RegOp->getReg()))
1101     return false;
1102 
1103   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1104   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1105   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1106     return false;
1107 
1108   // Clamp is applied after omod. If the source already has clamp set, don't
1109   // fold it.
1110   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1111     return false;
1112 
1113   LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def << '\n');
1114 
1115   DefOMod->setImm(OMod);
1116   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1117   MI.eraseFromParent();
1118   return true;
1119 }
1120 
1121 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
1122   if (skipFunction(MF.getFunction()))
1123     return false;
1124 
1125   MRI = &MF.getRegInfo();
1126   ST = &MF.getSubtarget<GCNSubtarget>();
1127   TII = ST->getInstrInfo();
1128   TRI = &TII->getRegisterInfo();
1129 
1130   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1131 
1132   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
1133   // correctly handle signed zeros.
1134   //
1135   // FIXME: Also need to check strictfp
1136   bool IsIEEEMode = MFI->getMode().IEEE;
1137   bool HasNSZ = MFI->hasNoSignedZerosFPMath();
1138 
1139   for (MachineBasicBlock *MBB : depth_first(&MF)) {
1140     MachineBasicBlock::iterator I, Next;
1141     for (I = MBB->begin(); I != MBB->end(); I = Next) {
1142       Next = std::next(I);
1143       MachineInstr &MI = *I;
1144 
1145       tryFoldInst(TII, &MI);
1146 
1147       if (!TII->isFoldableCopy(MI)) {
1148         // TODO: Omod might be OK if there is NSZ only on the source
1149         // instruction, and not the omod multiply.
1150         if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
1151             !tryFoldOMod(MI))
1152           tryFoldClamp(MI);
1153         continue;
1154       }
1155 
1156       MachineOperand &OpToFold = MI.getOperand(1);
1157       bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
1158 
1159       // FIXME: We could also be folding things like TargetIndexes.
1160       if (!FoldingImm && !OpToFold.isReg())
1161         continue;
1162 
1163       if (OpToFold.isReg() &&
1164           !TargetRegisterInfo::isVirtualRegister(OpToFold.getReg()))
1165         continue;
1166 
1167       // Prevent folding operands backwards in the function. For example,
1168       // the COPY opcode must not be replaced by 1 in this example:
1169       //
1170       //    %3 = COPY %vgpr0; VGPR_32:%3
1171       //    ...
1172       //    %vgpr0 = V_MOV_B32_e32 1, implicit %exec
1173       MachineOperand &Dst = MI.getOperand(0);
1174       if (Dst.isReg() &&
1175           !TargetRegisterInfo::isVirtualRegister(Dst.getReg()))
1176         continue;
1177 
1178       foldInstOperand(MI, OpToFold);
1179     }
1180   }
1181   return false;
1182 }
1183