xref: /llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp (revision bf41c4d29e44bfe3ae96c968e2e44761d5acb3ed)
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/ADT/SetVector.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 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() || FoldOp->isGlobal());
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 isGlobal() const { return Kind == MachineOperand::MO_GlobalAddress; }
71 
72   bool isCommuted() const {
73     return Commuted;
74   }
75 
76   bool needsShrink() const {
77     return ShrinkOpcode != -1;
78   }
79 
80   int getShrinkOpcode() const {
81     return ShrinkOpcode;
82   }
83 };
84 
85 class SIFoldOperands : public MachineFunctionPass {
86 public:
87   static char ID;
88   MachineRegisterInfo *MRI;
89   const SIInstrInfo *TII;
90   const SIRegisterInfo *TRI;
91   const GCNSubtarget *ST;
92   const SIMachineFunctionInfo *MFI;
93 
94   void foldOperand(MachineOperand &OpToFold,
95                    MachineInstr *UseMI,
96                    int UseOpIdx,
97                    SmallVectorImpl<FoldCandidate> &FoldList,
98                    SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
99 
100   void foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
101 
102   const MachineOperand *isClamp(const MachineInstr &MI) const;
103   bool tryFoldClamp(MachineInstr &MI);
104 
105   std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
106   bool tryFoldOMod(MachineInstr &MI);
107 
108 public:
109   SIFoldOperands() : MachineFunctionPass(ID) {
110     initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry());
111   }
112 
113   bool runOnMachineFunction(MachineFunction &MF) override;
114 
115   StringRef getPassName() const override { return "SI Fold Operands"; }
116 
117   void getAnalysisUsage(AnalysisUsage &AU) const override {
118     AU.setPreservesCFG();
119     MachineFunctionPass::getAnalysisUsage(AU);
120   }
121 };
122 
123 } // End anonymous namespace.
124 
125 INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE,
126                 "SI Fold Operands", false, false)
127 
128 char SIFoldOperands::ID = 0;
129 
130 char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
131 
132 // Wrapper around isInlineConstant that understands special cases when
133 // instruction types are replaced during operand folding.
134 static bool isInlineConstantIfFolded(const SIInstrInfo *TII,
135                                      const MachineInstr &UseMI,
136                                      unsigned OpNo,
137                                      const MachineOperand &OpToFold) {
138   if (TII->isInlineConstant(UseMI, OpNo, OpToFold))
139     return true;
140 
141   unsigned Opc = UseMI.getOpcode();
142   switch (Opc) {
143   case AMDGPU::V_MAC_F32_e64:
144   case AMDGPU::V_MAC_F16_e64:
145   case AMDGPU::V_FMAC_F32_e64:
146   case AMDGPU::V_FMAC_F16_e64: {
147     // Special case for mac. Since this is replaced with mad when folded into
148     // src2, we need to check the legality for the final instruction.
149     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
150     if (static_cast<int>(OpNo) == Src2Idx) {
151       bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e64 ||
152                    Opc == AMDGPU::V_FMAC_F16_e64;
153       bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64 ||
154                    Opc == AMDGPU::V_FMAC_F32_e64;
155 
156       unsigned Opc = IsFMA ?
157         (IsF32 ? AMDGPU::V_FMA_F32 : AMDGPU::V_FMA_F16_gfx9) :
158         (IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
159       const MCInstrDesc &MadDesc = TII->get(Opc);
160       return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType);
161     }
162     return false;
163   }
164   default:
165     return false;
166   }
167 }
168 
169 // TODO: Add heuristic that the frame index might not fit in the addressing mode
170 // immediate offset to avoid materializing in loops.
171 static bool frameIndexMayFold(const SIInstrInfo *TII,
172                               const MachineInstr &UseMI,
173                               int OpNo,
174                               const MachineOperand &OpToFold) {
175   return OpToFold.isFI() &&
176     (TII->isMUBUF(UseMI) || TII->isFLATScratch(UseMI)) &&
177     OpNo == AMDGPU::getNamedOperandIdx(UseMI.getOpcode(), AMDGPU::OpName::vaddr);
178 }
179 
180 FunctionPass *llvm::createSIFoldOperandsPass() {
181   return new SIFoldOperands();
182 }
183 
184 static bool updateOperand(FoldCandidate &Fold,
185                           const SIInstrInfo &TII,
186                           const TargetRegisterInfo &TRI,
187                           const GCNSubtarget &ST) {
188   MachineInstr *MI = Fold.UseMI;
189   MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
190   assert(Old.isReg());
191 
192   if (Fold.isImm()) {
193     if (MI->getDesc().TSFlags & SIInstrFlags::IsPacked &&
194         !(MI->getDesc().TSFlags & SIInstrFlags::IsMAI) &&
195         AMDGPU::isInlinableLiteralV216(static_cast<uint16_t>(Fold.ImmToFold),
196                                        ST.hasInv2PiInlineImm())) {
197       // Set op_sel/op_sel_hi on this operand or bail out if op_sel is
198       // already set.
199       unsigned Opcode = MI->getOpcode();
200       int OpNo = MI->getOperandNo(&Old);
201       int ModIdx = -1;
202       if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0))
203         ModIdx = AMDGPU::OpName::src0_modifiers;
204       else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1))
205         ModIdx = AMDGPU::OpName::src1_modifiers;
206       else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2))
207         ModIdx = AMDGPU::OpName::src2_modifiers;
208       assert(ModIdx != -1);
209       ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModIdx);
210       MachineOperand &Mod = MI->getOperand(ModIdx);
211       unsigned Val = Mod.getImm();
212       if ((Val & SISrcMods::OP_SEL_0) || !(Val & SISrcMods::OP_SEL_1))
213         return false;
214       // Only apply the following transformation if that operand requries
215       // a packed immediate.
216       switch (TII.get(Opcode).OpInfo[OpNo].OperandType) {
217       case AMDGPU::OPERAND_REG_IMM_V2FP16:
218       case AMDGPU::OPERAND_REG_IMM_V2INT16:
219       case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
220       case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
221         // If upper part is all zero we do not need op_sel_hi.
222         if (!isUInt<16>(Fold.ImmToFold)) {
223           if (!(Fold.ImmToFold & 0xffff)) {
224             Mod.setImm(Mod.getImm() | SISrcMods::OP_SEL_0);
225             Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
226             Old.ChangeToImmediate((Fold.ImmToFold >> 16) & 0xffff);
227             return true;
228           }
229           Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
230           Old.ChangeToImmediate(Fold.ImmToFold & 0xffff);
231           return true;
232         }
233         break;
234       default:
235         break;
236       }
237     }
238   }
239 
240   if ((Fold.isImm() || Fold.isFI() || Fold.isGlobal()) && Fold.needsShrink()) {
241     MachineBasicBlock *MBB = MI->getParent();
242     auto Liveness = MBB->computeRegisterLiveness(&TRI, AMDGPU::VCC, MI, 16);
243     if (Liveness != MachineBasicBlock::LQR_Dead) {
244       LLVM_DEBUG(dbgs() << "Not shrinking " << MI << " due to vcc liveness\n");
245       return false;
246     }
247 
248     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
249     int Op32 = Fold.getShrinkOpcode();
250     MachineOperand &Dst0 = MI->getOperand(0);
251     MachineOperand &Dst1 = MI->getOperand(1);
252     assert(Dst0.isDef() && Dst1.isDef());
253 
254     bool HaveNonDbgCarryUse = !MRI.use_nodbg_empty(Dst1.getReg());
255 
256     const TargetRegisterClass *Dst0RC = MRI.getRegClass(Dst0.getReg());
257     Register NewReg0 = MRI.createVirtualRegister(Dst0RC);
258 
259     MachineInstr *Inst32 = TII.buildShrunkInst(*MI, Op32);
260 
261     if (HaveNonDbgCarryUse) {
262       BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::COPY), Dst1.getReg())
263         .addReg(AMDGPU::VCC, RegState::Kill);
264     }
265 
266     // Keep the old instruction around to avoid breaking iterators, but
267     // replace it with a dummy instruction to remove uses.
268     //
269     // FIXME: We should not invert how this pass looks at operands to avoid
270     // this. Should track set of foldable movs instead of looking for uses
271     // when looking at a use.
272     Dst0.setReg(NewReg0);
273     for (unsigned I = MI->getNumOperands() - 1; I > 0; --I)
274       MI->RemoveOperand(I);
275     MI->setDesc(TII.get(AMDGPU::IMPLICIT_DEF));
276 
277     if (Fold.isCommuted())
278       TII.commuteInstruction(*Inst32, false);
279     return true;
280   }
281 
282   assert(!Fold.needsShrink() && "not handled");
283 
284   if (Fold.isImm()) {
285     Old.ChangeToImmediate(Fold.ImmToFold);
286     return true;
287   }
288 
289   if (Fold.isGlobal()) {
290     Old.ChangeToGA(Fold.OpToFold->getGlobal(), Fold.OpToFold->getOffset(),
291                    Fold.OpToFold->getTargetFlags());
292     return true;
293   }
294 
295   if (Fold.isFI()) {
296     Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
297     return true;
298   }
299 
300   MachineOperand *New = Fold.OpToFold;
301   Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
302   Old.setIsUndef(New->isUndef());
303   return true;
304 }
305 
306 static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
307                               const MachineInstr *MI) {
308   for (auto Candidate : FoldList) {
309     if (Candidate.UseMI == MI)
310       return true;
311   }
312   return false;
313 }
314 
315 static void appendFoldCandidate(SmallVectorImpl<FoldCandidate> &FoldList,
316                                 MachineInstr *MI, unsigned OpNo,
317                                 MachineOperand *FoldOp, bool Commuted = false,
318                                 int ShrinkOp = -1) {
319   // Skip additional folding on the same operand.
320   for (FoldCandidate &Fold : FoldList)
321     if (Fold.UseMI == MI && Fold.UseOpNo == OpNo)
322       return;
323   LLVM_DEBUG(dbgs() << "Append " << (Commuted ? "commuted" : "normal")
324                     << " operand " << OpNo << "\n  " << *MI << '\n');
325   FoldList.push_back(FoldCandidate(MI, OpNo, FoldOp, Commuted, ShrinkOp));
326 }
327 
328 static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
329                              MachineInstr *MI, unsigned OpNo,
330                              MachineOperand *OpToFold,
331                              const SIInstrInfo *TII) {
332   if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
333     // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
334     unsigned Opc = MI->getOpcode();
335     if ((Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
336          Opc == AMDGPU::V_FMAC_F32_e64 || Opc == AMDGPU::V_FMAC_F16_e64) &&
337         (int)OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)) {
338       bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e64 ||
339                    Opc == AMDGPU::V_FMAC_F16_e64;
340       bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64 ||
341                    Opc == AMDGPU::V_FMAC_F32_e64;
342       unsigned NewOpc = IsFMA ?
343         (IsF32 ? AMDGPU::V_FMA_F32 : AMDGPU::V_FMA_F16_gfx9) :
344         (IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
345 
346       // Check if changing this to a v_mad_{f16, f32} instruction will allow us
347       // to fold the operand.
348       MI->setDesc(TII->get(NewOpc));
349       bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII);
350       if (FoldAsMAD) {
351         MI->untieRegOperand(OpNo);
352         return true;
353       }
354       MI->setDesc(TII->get(Opc));
355     }
356 
357     // Special case for s_setreg_b32
358     if (Opc == AMDGPU::S_SETREG_B32 && OpToFold->isImm()) {
359       MI->setDesc(TII->get(AMDGPU::S_SETREG_IMM32_B32));
360       appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
361       return true;
362     }
363 
364     // If we are already folding into another operand of MI, then
365     // we can't commute the instruction, otherwise we risk making the
366     // other fold illegal.
367     if (isUseMIInFoldList(FoldList, MI))
368       return false;
369 
370     unsigned CommuteOpNo = OpNo;
371 
372     // Operand is not legal, so try to commute the instruction to
373     // see if this makes it possible to fold.
374     unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
375     unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
376     bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
377 
378     if (CanCommute) {
379       if (CommuteIdx0 == OpNo)
380         CommuteOpNo = CommuteIdx1;
381       else if (CommuteIdx1 == OpNo)
382         CommuteOpNo = CommuteIdx0;
383     }
384 
385 
386     // One of operands might be an Imm operand, and OpNo may refer to it after
387     // the call of commuteInstruction() below. Such situations are avoided
388     // here explicitly as OpNo must be a register operand to be a candidate
389     // for memory folding.
390     if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
391                        !MI->getOperand(CommuteIdx1).isReg()))
392       return false;
393 
394     if (!CanCommute ||
395         !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
396       return false;
397 
398     if (!TII->isOperandLegal(*MI, CommuteOpNo, OpToFold)) {
399       if ((Opc == AMDGPU::V_ADD_CO_U32_e64 ||
400            Opc == AMDGPU::V_SUB_CO_U32_e64 ||
401            Opc == AMDGPU::V_SUBREV_CO_U32_e64) && // FIXME
402           (OpToFold->isImm() || OpToFold->isFI() || OpToFold->isGlobal())) {
403         MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
404 
405         // Verify the other operand is a VGPR, otherwise we would violate the
406         // constant bus restriction.
407         unsigned OtherIdx = CommuteOpNo == CommuteIdx0 ? CommuteIdx1 : CommuteIdx0;
408         MachineOperand &OtherOp = MI->getOperand(OtherIdx);
409         if (!OtherOp.isReg() ||
410             !TII->getRegisterInfo().isVGPR(MRI, OtherOp.getReg()))
411           return false;
412 
413         assert(MI->getOperand(1).isDef());
414 
415         // Make sure to get the 32-bit version of the commuted opcode.
416         unsigned MaybeCommutedOpc = MI->getOpcode();
417         int Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc);
418 
419         appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true, Op32);
420         return true;
421       }
422 
423       TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1);
424       return false;
425     }
426 
427     appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true);
428     return true;
429   }
430 
431   // Check the case where we might introduce a second constant operand to a
432   // scalar instruction
433   if (TII->isSALU(MI->getOpcode())) {
434     const MCInstrDesc &InstDesc = MI->getDesc();
435     const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpNo];
436     const SIRegisterInfo &SRI = TII->getRegisterInfo();
437 
438     // Fine if the operand can be encoded as an inline constant
439     if (OpToFold->isImm()) {
440       if (!SRI.opCanUseInlineConstant(OpInfo.OperandType) ||
441           !TII->isInlineConstant(*OpToFold, OpInfo)) {
442         // Otherwise check for another constant
443         for (unsigned i = 0, e = InstDesc.getNumOperands(); i != e; ++i) {
444           auto &Op = MI->getOperand(i);
445           if (OpNo != i &&
446               TII->isLiteralConstantLike(Op, OpInfo)) {
447             return false;
448           }
449         }
450       }
451     }
452   }
453 
454   appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
455   return true;
456 }
457 
458 // If the use operand doesn't care about the value, this may be an operand only
459 // used for register indexing, in which case it is unsafe to fold.
460 static bool isUseSafeToFold(const SIInstrInfo *TII,
461                             const MachineInstr &MI,
462                             const MachineOperand &UseMO) {
463   if (UseMO.isUndef() || TII->isSDWA(MI))
464     return false;
465 
466   switch (MI.getOpcode()) {
467   case AMDGPU::V_MOV_B32_e32:
468   case AMDGPU::V_MOV_B32_e64:
469   case AMDGPU::V_MOV_B64_PSEUDO:
470     // Do not fold into an indirect mov.
471     return !MI.hasRegisterImplicitUseOperand(AMDGPU::M0);
472   }
473 
474   return true;
475   //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
476 }
477 
478 // Find a def of the UseReg, check if it is a reg_seqence and find initializers
479 // for each subreg, tracking it to foldable inline immediate if possible.
480 // Returns true on success.
481 static bool getRegSeqInit(
482     SmallVectorImpl<std::pair<MachineOperand*, unsigned>> &Defs,
483     Register UseReg, uint8_t OpTy,
484     const SIInstrInfo *TII, const MachineRegisterInfo &MRI) {
485   MachineInstr *Def = MRI.getUniqueVRegDef(UseReg);
486   if (!Def || !Def->isRegSequence())
487     return false;
488 
489   for (unsigned I = 1, E = Def->getNumExplicitOperands(); I < E; I += 2) {
490     MachineOperand *Sub = &Def->getOperand(I);
491     assert (Sub->isReg());
492 
493     for (MachineInstr *SubDef = MRI.getUniqueVRegDef(Sub->getReg());
494          SubDef && Sub->isReg() && !Sub->getSubReg() &&
495          TII->isFoldableCopy(*SubDef);
496          SubDef = MRI.getUniqueVRegDef(Sub->getReg())) {
497       MachineOperand *Op = &SubDef->getOperand(1);
498       if (Op->isImm()) {
499         if (TII->isInlineConstant(*Op, OpTy))
500           Sub = Op;
501         break;
502       }
503       if (!Op->isReg())
504         break;
505       Sub = Op;
506     }
507 
508     Defs.push_back(std::make_pair(Sub, Def->getOperand(I + 1).getImm()));
509   }
510 
511   return true;
512 }
513 
514 static bool tryToFoldACImm(const SIInstrInfo *TII,
515                            const MachineOperand &OpToFold,
516                            MachineInstr *UseMI,
517                            unsigned UseOpIdx,
518                            SmallVectorImpl<FoldCandidate> &FoldList) {
519   const MCInstrDesc &Desc = UseMI->getDesc();
520   const MCOperandInfo *OpInfo = Desc.OpInfo;
521   if (!OpInfo || UseOpIdx >= Desc.getNumOperands())
522     return false;
523 
524   uint8_t OpTy = OpInfo[UseOpIdx].OperandType;
525   if (OpTy < AMDGPU::OPERAND_REG_INLINE_AC_FIRST ||
526       OpTy > AMDGPU::OPERAND_REG_INLINE_AC_LAST)
527     return false;
528 
529   if (OpToFold.isImm() && TII->isInlineConstant(OpToFold, OpTy) &&
530       TII->isOperandLegal(*UseMI, UseOpIdx, &OpToFold)) {
531     UseMI->getOperand(UseOpIdx).ChangeToImmediate(OpToFold.getImm());
532     return true;
533   }
534 
535   if (!OpToFold.isReg())
536     return false;
537 
538   Register UseReg = OpToFold.getReg();
539   if (!UseReg.isVirtual())
540     return false;
541 
542   if (llvm::find_if(FoldList, [UseMI](const FoldCandidate &FC) {
543         return FC.UseMI == UseMI; }) != FoldList.end())
544     return false;
545 
546   MachineRegisterInfo &MRI = UseMI->getParent()->getParent()->getRegInfo();
547   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
548   if (!getRegSeqInit(Defs, UseReg, OpTy, TII, MRI))
549     return false;
550 
551   int32_t Imm;
552   for (unsigned I = 0, E = Defs.size(); I != E; ++I) {
553     const MachineOperand *Op = Defs[I].first;
554     if (!Op->isImm())
555       return false;
556 
557     auto SubImm = Op->getImm();
558     if (!I) {
559       Imm = SubImm;
560       if (!TII->isInlineConstant(*Op, OpTy) ||
561           !TII->isOperandLegal(*UseMI, UseOpIdx, Op))
562         return false;
563 
564       continue;
565     }
566     if (Imm != SubImm)
567       return false; // Can only fold splat constants
568   }
569 
570   appendFoldCandidate(FoldList, UseMI, UseOpIdx, Defs[0].first);
571   return true;
572 }
573 
574 void SIFoldOperands::foldOperand(
575   MachineOperand &OpToFold,
576   MachineInstr *UseMI,
577   int UseOpIdx,
578   SmallVectorImpl<FoldCandidate> &FoldList,
579   SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
580   const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
581 
582   if (!isUseSafeToFold(TII, *UseMI, UseOp))
583     return;
584 
585   // FIXME: Fold operands with subregs.
586   if (UseOp.isReg() && OpToFold.isReg()) {
587     if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
588       return;
589   }
590 
591   // Special case for REG_SEQUENCE: We can't fold literals into
592   // REG_SEQUENCE instructions, so we have to fold them into the
593   // uses of REG_SEQUENCE.
594   if (UseMI->isRegSequence()) {
595     Register RegSeqDstReg = UseMI->getOperand(0).getReg();
596     unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
597 
598     MachineRegisterInfo::use_nodbg_iterator Next;
599     for (MachineRegisterInfo::use_nodbg_iterator
600            RSUse = MRI->use_nodbg_begin(RegSeqDstReg), RSE = MRI->use_nodbg_end();
601          RSUse != RSE; RSUse = Next) {
602       Next = std::next(RSUse);
603 
604       MachineInstr *RSUseMI = RSUse->getParent();
605 
606       if (tryToFoldACImm(TII, UseMI->getOperand(0), RSUseMI,
607                          RSUse.getOperandNo(), FoldList))
608         continue;
609 
610       if (RSUse->getSubReg() != RegSeqDstSubReg)
611         continue;
612 
613       foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList,
614                   CopiesToReplace);
615     }
616 
617     return;
618   }
619 
620   if (tryToFoldACImm(TII, OpToFold, UseMI, UseOpIdx, FoldList))
621     return;
622 
623   if (frameIndexMayFold(TII, *UseMI, UseOpIdx, OpToFold)) {
624     // Sanity check that this is a stack access.
625     // FIXME: Should probably use stack pseudos before frame lowering.
626 
627     if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() !=
628         MFI->getScratchRSrcReg())
629       return;
630 
631     // Ensure this is either relative to the current frame or the current wave.
632     MachineOperand &SOff =
633         *TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset);
634     if ((!SOff.isReg() || SOff.getReg() != MFI->getStackPtrOffsetReg()) &&
635         (!SOff.isImm() || SOff.getImm() != 0))
636       return;
637 
638     // A frame index will resolve to a positive constant, so it should always be
639     // safe to fold the addressing mode, even pre-GFX9.
640     UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getIndex());
641 
642     // If this is relative to the current wave, update it to be relative to the
643     // current frame.
644     if (SOff.isImm())
645       SOff.ChangeToRegister(MFI->getStackPtrOffsetReg(), false);
646     return;
647   }
648 
649   bool FoldingImmLike =
650       OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
651 
652   if (FoldingImmLike && UseMI->isCopy()) {
653     Register DestReg = UseMI->getOperand(0).getReg();
654     Register SrcReg = UseMI->getOperand(1).getReg();
655     assert(SrcReg.isVirtual());
656 
657     const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
658 
659     // Don't fold into a copy to a physical register with the same class. Doing
660     // so would interfere with the register coalescer's logic which would avoid
661     // redundant initalizations.
662     if (DestReg.isPhysical() && SrcRC->contains(DestReg))
663       return;
664 
665     const TargetRegisterClass *DestRC = TRI->getRegClassForReg(*MRI, DestReg);
666     if (!DestReg.isPhysical()) {
667       if (TRI->isSGPRClass(SrcRC) && TRI->hasVectorRegisters(DestRC)) {
668         MachineRegisterInfo::use_nodbg_iterator NextUse;
669         SmallVector<FoldCandidate, 4> CopyUses;
670         for (MachineRegisterInfo::use_nodbg_iterator Use = MRI->use_nodbg_begin(DestReg),
671                E = MRI->use_nodbg_end();
672              Use != E; Use = NextUse) {
673           NextUse = std::next(Use);
674           // There's no point trying to fold into an implicit operand.
675           if (Use->isImplicit())
676             continue;
677 
678           FoldCandidate FC = FoldCandidate(Use->getParent(), Use.getOperandNo(),
679                                            &UseMI->getOperand(1));
680           CopyUses.push_back(FC);
681         }
682         for (auto &F : CopyUses) {
683           foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo, FoldList, CopiesToReplace);
684         }
685       }
686 
687       if (DestRC == &AMDGPU::AGPR_32RegClass &&
688           TII->isInlineConstant(OpToFold, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
689         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32));
690         UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
691         CopiesToReplace.push_back(UseMI);
692         return;
693       }
694     }
695 
696     // In order to fold immediates into copies, we need to change the
697     // copy to a MOV.
698 
699     unsigned MovOp = TII->getMovOpcode(DestRC);
700     if (MovOp == AMDGPU::COPY)
701       return;
702 
703     UseMI->setDesc(TII->get(MovOp));
704     MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin();
705     MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end();
706     while (ImpOpI != ImpOpE) {
707       MachineInstr::mop_iterator Tmp = ImpOpI;
708       ImpOpI++;
709       UseMI->RemoveOperand(UseMI->getOperandNo(Tmp));
710     }
711     CopiesToReplace.push_back(UseMI);
712   } else {
713     if (UseMI->isCopy() && OpToFold.isReg() &&
714         UseMI->getOperand(0).getReg().isVirtual() &&
715         !UseMI->getOperand(1).getSubReg()) {
716       LLVM_DEBUG(dbgs() << "Folding " << OpToFold
717                         << "\n into " << *UseMI << '\n');
718       unsigned Size = TII->getOpSize(*UseMI, 1);
719       Register UseReg = OpToFold.getReg();
720       UseMI->getOperand(1).setReg(UseReg);
721       UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
722       UseMI->getOperand(1).setIsKill(false);
723       CopiesToReplace.push_back(UseMI);
724       OpToFold.setIsKill(false);
725 
726       // That is very tricky to store a value into an AGPR. v_accvgpr_write_b32
727       // can only accept VGPR or inline immediate. Recreate a reg_sequence with
728       // its initializers right here, so we will rematerialize immediates and
729       // avoid copies via different reg classes.
730       SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
731       if (Size > 4 && TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
732           getRegSeqInit(Defs, UseReg, AMDGPU::OPERAND_REG_INLINE_C_INT32, TII,
733                         *MRI)) {
734         const DebugLoc &DL = UseMI->getDebugLoc();
735         MachineBasicBlock &MBB = *UseMI->getParent();
736 
737         UseMI->setDesc(TII->get(AMDGPU::REG_SEQUENCE));
738         for (unsigned I = UseMI->getNumOperands() - 1; I > 0; --I)
739           UseMI->RemoveOperand(I);
740 
741         MachineInstrBuilder B(*MBB.getParent(), UseMI);
742         DenseMap<TargetInstrInfo::RegSubRegPair, Register> VGPRCopies;
743         SmallSetVector<TargetInstrInfo::RegSubRegPair, 32> SeenAGPRs;
744         for (unsigned I = 0; I < Size / 4; ++I) {
745           MachineOperand *Def = Defs[I].first;
746           TargetInstrInfo::RegSubRegPair CopyToVGPR;
747           if (Def->isImm() &&
748               TII->isInlineConstant(*Def, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
749             int64_t Imm = Def->getImm();
750 
751             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
752             BuildMI(MBB, UseMI, DL,
753                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32), Tmp).addImm(Imm);
754             B.addReg(Tmp);
755           } else if (Def->isReg() && TRI->isAGPR(*MRI, Def->getReg())) {
756             auto Src = getRegSubRegPair(*Def);
757             Def->setIsKill(false);
758             if (!SeenAGPRs.insert(Src)) {
759               // We cannot build a reg_sequence out of the same registers, they
760               // must be copied. Better do it here before copyPhysReg() created
761               // several reads to do the AGPR->VGPR->AGPR copy.
762               CopyToVGPR = Src;
763             } else {
764               B.addReg(Src.Reg, Def->isUndef() ? RegState::Undef : 0,
765                        Src.SubReg);
766             }
767           } else {
768             assert(Def->isReg());
769             Def->setIsKill(false);
770             auto Src = getRegSubRegPair(*Def);
771 
772             // Direct copy from SGPR to AGPR is not possible. To avoid creation
773             // of exploded copies SGPR->VGPR->AGPR in the copyPhysReg() later,
774             // create a copy here and track if we already have such a copy.
775             if (TRI->isSGPRReg(*MRI, Src.Reg)) {
776               CopyToVGPR = Src;
777             } else {
778               auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
779               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Tmp).add(*Def);
780               B.addReg(Tmp);
781             }
782           }
783 
784           if (CopyToVGPR.Reg) {
785             Register Vgpr;
786             if (VGPRCopies.count(CopyToVGPR)) {
787               Vgpr = VGPRCopies[CopyToVGPR];
788             } else {
789               Vgpr = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
790               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Vgpr).add(*Def);
791               VGPRCopies[CopyToVGPR] = Vgpr;
792             }
793             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
794             BuildMI(MBB, UseMI, DL,
795                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32), Tmp).addReg(Vgpr);
796             B.addReg(Tmp);
797           }
798 
799           B.addImm(Defs[I].second);
800         }
801         LLVM_DEBUG(dbgs() << "Folded " << *UseMI << '\n');
802         return;
803       }
804 
805       if (Size != 4)
806         return;
807       if (TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
808           TRI->isVGPR(*MRI, UseMI->getOperand(1).getReg()))
809         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32));
810       else if (TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) &&
811                TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg()))
812         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_READ_B32));
813       return;
814     }
815 
816     unsigned UseOpc = UseMI->getOpcode();
817     if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
818         (UseOpc == AMDGPU::V_READLANE_B32 &&
819          (int)UseOpIdx ==
820          AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) {
821       // %vgpr = V_MOV_B32 imm
822       // %sgpr = V_READFIRSTLANE_B32 %vgpr
823       // =>
824       // %sgpr = S_MOV_B32 imm
825       if (FoldingImmLike) {
826         if (execMayBeModifiedBeforeUse(*MRI,
827                                        UseMI->getOperand(UseOpIdx).getReg(),
828                                        *OpToFold.getParent(),
829                                        *UseMI))
830           return;
831 
832         UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32));
833 
834         if (OpToFold.isImm())
835           UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
836         else
837           UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getIndex());
838         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
839         return;
840       }
841 
842       if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) {
843         if (execMayBeModifiedBeforeUse(*MRI,
844                                        UseMI->getOperand(UseOpIdx).getReg(),
845                                        *OpToFold.getParent(),
846                                        *UseMI))
847           return;
848 
849         // %vgpr = COPY %sgpr0
850         // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
851         // =>
852         // %sgpr1 = COPY %sgpr0
853         UseMI->setDesc(TII->get(AMDGPU::COPY));
854         UseMI->getOperand(1).setReg(OpToFold.getReg());
855         UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
856         UseMI->getOperand(1).setIsKill(false);
857         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
858         return;
859       }
860     }
861 
862     const MCInstrDesc &UseDesc = UseMI->getDesc();
863 
864     // Don't fold into target independent nodes.  Target independent opcodes
865     // don't have defined register classes.
866     if (UseDesc.isVariadic() ||
867         UseOp.isImplicit() ||
868         UseDesc.OpInfo[UseOpIdx].RegClass == -1)
869       return;
870   }
871 
872   if (!FoldingImmLike) {
873     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
874 
875     // FIXME: We could try to change the instruction from 64-bit to 32-bit
876     // to enable more folding opportunites.  The shrink operands pass
877     // already does this.
878     return;
879   }
880 
881 
882   const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
883   const TargetRegisterClass *FoldRC =
884     TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
885 
886   // Split 64-bit constants into 32-bits for folding.
887   if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
888     Register UseReg = UseOp.getReg();
889     const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg);
890 
891     if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
892       return;
893 
894     APInt Imm(64, OpToFold.getImm());
895     if (UseOp.getSubReg() == AMDGPU::sub0) {
896       Imm = Imm.getLoBits(32);
897     } else {
898       assert(UseOp.getSubReg() == AMDGPU::sub1);
899       Imm = Imm.getHiBits(32);
900     }
901 
902     MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
903     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
904     return;
905   }
906 
907 
908 
909   tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
910 }
911 
912 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
913                                   uint32_t LHS, uint32_t RHS) {
914   switch (Opcode) {
915   case AMDGPU::V_AND_B32_e64:
916   case AMDGPU::V_AND_B32_e32:
917   case AMDGPU::S_AND_B32:
918     Result = LHS & RHS;
919     return true;
920   case AMDGPU::V_OR_B32_e64:
921   case AMDGPU::V_OR_B32_e32:
922   case AMDGPU::S_OR_B32:
923     Result = LHS | RHS;
924     return true;
925   case AMDGPU::V_XOR_B32_e64:
926   case AMDGPU::V_XOR_B32_e32:
927   case AMDGPU::S_XOR_B32:
928     Result = LHS ^ RHS;
929     return true;
930   case AMDGPU::S_XNOR_B32:
931     Result = ~(LHS ^ RHS);
932     return true;
933   case AMDGPU::S_NAND_B32:
934     Result = ~(LHS & RHS);
935     return true;
936   case AMDGPU::S_NOR_B32:
937     Result = ~(LHS | RHS);
938     return true;
939   case AMDGPU::S_ANDN2_B32:
940     Result = LHS & ~RHS;
941     return true;
942   case AMDGPU::S_ORN2_B32:
943     Result = LHS | ~RHS;
944     return true;
945   case AMDGPU::V_LSHL_B32_e64:
946   case AMDGPU::V_LSHL_B32_e32:
947   case AMDGPU::S_LSHL_B32:
948     // The instruction ignores the high bits for out of bounds shifts.
949     Result = LHS << (RHS & 31);
950     return true;
951   case AMDGPU::V_LSHLREV_B32_e64:
952   case AMDGPU::V_LSHLREV_B32_e32:
953     Result = RHS << (LHS & 31);
954     return true;
955   case AMDGPU::V_LSHR_B32_e64:
956   case AMDGPU::V_LSHR_B32_e32:
957   case AMDGPU::S_LSHR_B32:
958     Result = LHS >> (RHS & 31);
959     return true;
960   case AMDGPU::V_LSHRREV_B32_e64:
961   case AMDGPU::V_LSHRREV_B32_e32:
962     Result = RHS >> (LHS & 31);
963     return true;
964   case AMDGPU::V_ASHR_I32_e64:
965   case AMDGPU::V_ASHR_I32_e32:
966   case AMDGPU::S_ASHR_I32:
967     Result = static_cast<int32_t>(LHS) >> (RHS & 31);
968     return true;
969   case AMDGPU::V_ASHRREV_I32_e64:
970   case AMDGPU::V_ASHRREV_I32_e32:
971     Result = static_cast<int32_t>(RHS) >> (LHS & 31);
972     return true;
973   default:
974     return false;
975   }
976 }
977 
978 static unsigned getMovOpc(bool IsScalar) {
979   return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
980 }
981 
982 /// Remove any leftover implicit operands from mutating the instruction. e.g.
983 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
984 /// anymore.
985 static void stripExtraCopyOperands(MachineInstr &MI) {
986   const MCInstrDesc &Desc = MI.getDesc();
987   unsigned NumOps = Desc.getNumOperands() +
988                     Desc.getNumImplicitUses() +
989                     Desc.getNumImplicitDefs();
990 
991   for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
992     MI.RemoveOperand(I);
993 }
994 
995 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
996   MI.setDesc(NewDesc);
997   stripExtraCopyOperands(MI);
998 }
999 
1000 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
1001                                                MachineOperand &Op) {
1002   if (Op.isReg()) {
1003     // If this has a subregister, it obviously is a register source.
1004     if (Op.getSubReg() != AMDGPU::NoSubRegister || !Op.getReg().isVirtual())
1005       return &Op;
1006 
1007     MachineInstr *Def = MRI.getVRegDef(Op.getReg());
1008     if (Def && Def->isMoveImmediate()) {
1009       MachineOperand &ImmSrc = Def->getOperand(1);
1010       if (ImmSrc.isImm())
1011         return &ImmSrc;
1012     }
1013   }
1014 
1015   return &Op;
1016 }
1017 
1018 // Try to simplify operations with a constant that may appear after instruction
1019 // selection.
1020 // TODO: See if a frame index with a fixed offset can fold.
1021 static bool tryConstantFoldOp(MachineRegisterInfo &MRI,
1022                               const SIInstrInfo *TII,
1023                               MachineInstr *MI,
1024                               MachineOperand *ImmOp) {
1025   unsigned Opc = MI->getOpcode();
1026   if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
1027       Opc == AMDGPU::S_NOT_B32) {
1028     MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm());
1029     mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
1030     return true;
1031   }
1032 
1033   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1034   if (Src1Idx == -1)
1035     return false;
1036 
1037   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1038   MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
1039   MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
1040 
1041   if (!Src0->isImm() && !Src1->isImm())
1042     return false;
1043 
1044   if (MI->getOpcode() == AMDGPU::V_LSHL_OR_B32 ||
1045       MI->getOpcode() == AMDGPU::V_LSHL_ADD_U32 ||
1046       MI->getOpcode() == AMDGPU::V_AND_OR_B32) {
1047     if (Src0->isImm() && Src0->getImm() == 0) {
1048       // v_lshl_or_b32 0, X, Y -> copy Y
1049       // v_lshl_or_b32 0, X, K -> v_mov_b32 K
1050       // v_lshl_add_b32 0, X, Y -> copy Y
1051       // v_lshl_add_b32 0, X, K -> v_mov_b32 K
1052       // v_and_or_b32 0, X, Y -> copy Y
1053       // v_and_or_b32 0, X, K -> v_mov_b32 K
1054       bool UseCopy = TII->getNamedOperand(*MI, AMDGPU::OpName::src2)->isReg();
1055       MI->RemoveOperand(Src1Idx);
1056       MI->RemoveOperand(Src0Idx);
1057 
1058       MI->setDesc(TII->get(UseCopy ? AMDGPU::COPY : AMDGPU::V_MOV_B32_e32));
1059       return true;
1060     }
1061   }
1062 
1063   // and k0, k1 -> v_mov_b32 (k0 & k1)
1064   // or k0, k1 -> v_mov_b32 (k0 | k1)
1065   // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
1066   if (Src0->isImm() && Src1->isImm()) {
1067     int32_t NewImm;
1068     if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
1069       return false;
1070 
1071     const SIRegisterInfo &TRI = TII->getRegisterInfo();
1072     bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
1073 
1074     // Be careful to change the right operand, src0 may belong to a different
1075     // instruction.
1076     MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
1077     MI->RemoveOperand(Src1Idx);
1078     mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
1079     return true;
1080   }
1081 
1082   if (!MI->isCommutable())
1083     return false;
1084 
1085   if (Src0->isImm() && !Src1->isImm()) {
1086     std::swap(Src0, Src1);
1087     std::swap(Src0Idx, Src1Idx);
1088   }
1089 
1090   int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
1091   if (Opc == AMDGPU::V_OR_B32_e64 ||
1092       Opc == AMDGPU::V_OR_B32_e32 ||
1093       Opc == AMDGPU::S_OR_B32) {
1094     if (Src1Val == 0) {
1095       // y = or x, 0 => y = copy x
1096       MI->RemoveOperand(Src1Idx);
1097       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1098     } else if (Src1Val == -1) {
1099       // y = or x, -1 => y = v_mov_b32 -1
1100       MI->RemoveOperand(Src1Idx);
1101       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
1102     } else
1103       return false;
1104 
1105     return true;
1106   }
1107 
1108   if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
1109       MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
1110       MI->getOpcode() == AMDGPU::S_AND_B32) {
1111     if (Src1Val == 0) {
1112       // y = and x, 0 => y = v_mov_b32 0
1113       MI->RemoveOperand(Src0Idx);
1114       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
1115     } else if (Src1Val == -1) {
1116       // y = and x, -1 => y = copy x
1117       MI->RemoveOperand(Src1Idx);
1118       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1119       stripExtraCopyOperands(*MI);
1120     } else
1121       return false;
1122 
1123     return true;
1124   }
1125 
1126   if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
1127       MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
1128       MI->getOpcode() == AMDGPU::S_XOR_B32) {
1129     if (Src1Val == 0) {
1130       // y = xor x, 0 => y = copy x
1131       MI->RemoveOperand(Src1Idx);
1132       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1133       return true;
1134     }
1135   }
1136 
1137   return false;
1138 }
1139 
1140 // Try to fold an instruction into a simpler one
1141 static bool tryFoldInst(const SIInstrInfo *TII,
1142                         MachineInstr *MI) {
1143   unsigned Opc = MI->getOpcode();
1144 
1145   if (Opc == AMDGPU::V_CNDMASK_B32_e32    ||
1146       Opc == AMDGPU::V_CNDMASK_B32_e64    ||
1147       Opc == AMDGPU::V_CNDMASK_B64_PSEUDO) {
1148     const MachineOperand *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
1149     const MachineOperand *Src1 = TII->getNamedOperand(*MI, AMDGPU::OpName::src1);
1150     int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
1151     int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
1152     if (Src1->isIdenticalTo(*Src0) &&
1153         (Src1ModIdx == -1 || !MI->getOperand(Src1ModIdx).getImm()) &&
1154         (Src0ModIdx == -1 || !MI->getOperand(Src0ModIdx).getImm())) {
1155       LLVM_DEBUG(dbgs() << "Folded " << *MI << " into ");
1156       auto &NewDesc =
1157           TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false));
1158       int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
1159       if (Src2Idx != -1)
1160         MI->RemoveOperand(Src2Idx);
1161       MI->RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
1162       if (Src1ModIdx != -1)
1163         MI->RemoveOperand(Src1ModIdx);
1164       if (Src0ModIdx != -1)
1165         MI->RemoveOperand(Src0ModIdx);
1166       mutateCopyOp(*MI, NewDesc);
1167       LLVM_DEBUG(dbgs() << *MI << '\n');
1168       return true;
1169     }
1170   }
1171 
1172   return false;
1173 }
1174 
1175 void SIFoldOperands::foldInstOperand(MachineInstr &MI,
1176                                      MachineOperand &OpToFold) const {
1177   // We need mutate the operands of new mov instructions to add implicit
1178   // uses of EXEC, but adding them invalidates the use_iterator, so defer
1179   // this.
1180   SmallVector<MachineInstr *, 4> CopiesToReplace;
1181   SmallVector<FoldCandidate, 4> FoldList;
1182   MachineOperand &Dst = MI.getOperand(0);
1183 
1184   bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1185   if (FoldingImm) {
1186     unsigned NumLiteralUses = 0;
1187     MachineOperand *NonInlineUse = nullptr;
1188     int NonInlineUseOpNo = -1;
1189 
1190     MachineRegisterInfo::use_nodbg_iterator NextUse;
1191     for (MachineRegisterInfo::use_nodbg_iterator
1192            Use = MRI->use_nodbg_begin(Dst.getReg()), E = MRI->use_nodbg_end();
1193          Use != E; Use = NextUse) {
1194       NextUse = std::next(Use);
1195       MachineInstr *UseMI = Use->getParent();
1196       unsigned OpNo = Use.getOperandNo();
1197 
1198       // Folding the immediate may reveal operations that can be constant
1199       // folded or replaced with a copy. This can happen for example after
1200       // frame indices are lowered to constants or from splitting 64-bit
1201       // constants.
1202       //
1203       // We may also encounter cases where one or both operands are
1204       // immediates materialized into a register, which would ordinarily not
1205       // be folded due to multiple uses or operand constraints.
1206 
1207       if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) {
1208         LLVM_DEBUG(dbgs() << "Constant folded " << *UseMI << '\n');
1209 
1210         // Some constant folding cases change the same immediate's use to a new
1211         // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user
1212         // again. The same constant folded instruction could also have a second
1213         // use operand.
1214         NextUse = MRI->use_nodbg_begin(Dst.getReg());
1215         FoldList.clear();
1216         continue;
1217       }
1218 
1219       // Try to fold any inline immediate uses, and then only fold other
1220       // constants if they have one use.
1221       //
1222       // The legality of the inline immediate must be checked based on the use
1223       // operand, not the defining instruction, because 32-bit instructions
1224       // with 32-bit inline immediate sources may be used to materialize
1225       // constants used in 16-bit operands.
1226       //
1227       // e.g. it is unsafe to fold:
1228       //  s_mov_b32 s0, 1.0    // materializes 0x3f800000
1229       //  v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
1230 
1231       // Folding immediates with more than one use will increase program size.
1232       // FIXME: This will also reduce register usage, which may be better
1233       // in some cases. A better heuristic is needed.
1234       if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
1235         foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
1236       } else if (frameIndexMayFold(TII, *UseMI, OpNo, OpToFold)) {
1237         foldOperand(OpToFold, UseMI, OpNo, FoldList,
1238                     CopiesToReplace);
1239       } else {
1240         if (++NumLiteralUses == 1) {
1241           NonInlineUse = &*Use;
1242           NonInlineUseOpNo = OpNo;
1243         }
1244       }
1245     }
1246 
1247     if (NumLiteralUses == 1) {
1248       MachineInstr *UseMI = NonInlineUse->getParent();
1249       foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
1250     }
1251   } else {
1252     // Folding register.
1253     SmallVector <MachineRegisterInfo::use_nodbg_iterator, 4> UsesToProcess;
1254     for (MachineRegisterInfo::use_nodbg_iterator
1255            Use = MRI->use_nodbg_begin(Dst.getReg()), E = MRI->use_nodbg_end();
1256          Use != E; ++Use) {
1257       UsesToProcess.push_back(Use);
1258     }
1259     for (auto U : UsesToProcess) {
1260       MachineInstr *UseMI = U->getParent();
1261 
1262       foldOperand(OpToFold, UseMI, U.getOperandNo(),
1263         FoldList, CopiesToReplace);
1264     }
1265   }
1266 
1267   MachineFunction *MF = MI.getParent()->getParent();
1268   // Make sure we add EXEC uses to any new v_mov instructions created.
1269   for (MachineInstr *Copy : CopiesToReplace)
1270     Copy->addImplicitDefUseOperands(*MF);
1271 
1272   for (FoldCandidate &Fold : FoldList) {
1273     assert(!Fold.isReg() || Fold.OpToFold);
1274     if (Fold.isReg() && Fold.OpToFold->getReg().isVirtual()) {
1275       Register Reg = Fold.OpToFold->getReg();
1276       MachineInstr *DefMI = Fold.OpToFold->getParent();
1277       if (DefMI->readsRegister(AMDGPU::EXEC, TRI) &&
1278           execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI))
1279         continue;
1280     }
1281     if (updateOperand(Fold, *TII, *TRI, *ST)) {
1282       // Clear kill flags.
1283       if (Fold.isReg()) {
1284         assert(Fold.OpToFold && Fold.OpToFold->isReg());
1285         // FIXME: Probably shouldn't bother trying to fold if not an
1286         // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
1287         // copies.
1288         MRI->clearKillFlags(Fold.OpToFold->getReg());
1289       }
1290       LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
1291                         << static_cast<int>(Fold.UseOpNo) << " of "
1292                         << *Fold.UseMI << '\n');
1293       tryFoldInst(TII, Fold.UseMI);
1294     } else if (Fold.isCommuted()) {
1295       // Restoring instruction's original operand order if fold has failed.
1296       TII->commuteInstruction(*Fold.UseMI, false);
1297     }
1298   }
1299 }
1300 
1301 // Clamp patterns are canonically selected to v_max_* instructions, so only
1302 // handle them.
1303 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
1304   unsigned Op = MI.getOpcode();
1305   switch (Op) {
1306   case AMDGPU::V_MAX_F32_e64:
1307   case AMDGPU::V_MAX_F16_e64:
1308   case AMDGPU::V_MAX_F64:
1309   case AMDGPU::V_PK_MAX_F16: {
1310     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
1311       return nullptr;
1312 
1313     // Make sure sources are identical.
1314     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1315     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1316     if (!Src0->isReg() || !Src1->isReg() ||
1317         Src0->getReg() != Src1->getReg() ||
1318         Src0->getSubReg() != Src1->getSubReg() ||
1319         Src0->getSubReg() != AMDGPU::NoSubRegister)
1320       return nullptr;
1321 
1322     // Can't fold up if we have modifiers.
1323     if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1324       return nullptr;
1325 
1326     unsigned Src0Mods
1327       = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
1328     unsigned Src1Mods
1329       = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
1330 
1331     // Having a 0 op_sel_hi would require swizzling the output in the source
1332     // instruction, which we can't do.
1333     unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
1334                                                       : 0u;
1335     if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
1336       return nullptr;
1337     return Src0;
1338   }
1339   default:
1340     return nullptr;
1341   }
1342 }
1343 
1344 // We obviously have multiple uses in a clamp since the register is used twice
1345 // in the same instruction.
1346 static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) {
1347   int Count = 0;
1348   for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
1349        I != E; ++I) {
1350     if (++Count > 1)
1351       return false;
1352   }
1353 
1354   return true;
1355 }
1356 
1357 // FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
1358 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
1359   const MachineOperand *ClampSrc = isClamp(MI);
1360   if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg()))
1361     return false;
1362 
1363   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
1364 
1365   // The type of clamp must be compatible.
1366   if (TII->getClampMask(*Def) != TII->getClampMask(MI))
1367     return false;
1368 
1369   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
1370   if (!DefClamp)
1371     return false;
1372 
1373   LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def
1374                     << '\n');
1375 
1376   // Clamp is applied after omod, so it is OK if omod is set.
1377   DefClamp->setImm(1);
1378   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1379   MI.eraseFromParent();
1380   return true;
1381 }
1382 
1383 static int getOModValue(unsigned Opc, int64_t Val) {
1384   switch (Opc) {
1385   case AMDGPU::V_MUL_F32_e64: {
1386     switch (static_cast<uint32_t>(Val)) {
1387     case 0x3f000000: // 0.5
1388       return SIOutMods::DIV2;
1389     case 0x40000000: // 2.0
1390       return SIOutMods::MUL2;
1391     case 0x40800000: // 4.0
1392       return SIOutMods::MUL4;
1393     default:
1394       return SIOutMods::NONE;
1395     }
1396   }
1397   case AMDGPU::V_MUL_F16_e64: {
1398     switch (static_cast<uint16_t>(Val)) {
1399     case 0x3800: // 0.5
1400       return SIOutMods::DIV2;
1401     case 0x4000: // 2.0
1402       return SIOutMods::MUL2;
1403     case 0x4400: // 4.0
1404       return SIOutMods::MUL4;
1405     default:
1406       return SIOutMods::NONE;
1407     }
1408   }
1409   default:
1410     llvm_unreachable("invalid mul opcode");
1411   }
1412 }
1413 
1414 // FIXME: Does this really not support denormals with f16?
1415 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1416 // handled, so will anything other than that break?
1417 std::pair<const MachineOperand *, int>
1418 SIFoldOperands::isOMod(const MachineInstr &MI) const {
1419   unsigned Op = MI.getOpcode();
1420   switch (Op) {
1421   case AMDGPU::V_MUL_F32_e64:
1422   case AMDGPU::V_MUL_F16_e64: {
1423     // If output denormals are enabled, omod is ignored.
1424     if ((Op == AMDGPU::V_MUL_F32_e64 && MFI->getMode().FP32OutputDenormals) ||
1425         (Op == AMDGPU::V_MUL_F16_e64 && MFI->getMode().FP64FP16OutputDenormals))
1426       return std::make_pair(nullptr, SIOutMods::NONE);
1427 
1428     const MachineOperand *RegOp = nullptr;
1429     const MachineOperand *ImmOp = nullptr;
1430     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1431     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1432     if (Src0->isImm()) {
1433       ImmOp = Src0;
1434       RegOp = Src1;
1435     } else if (Src1->isImm()) {
1436       ImmOp = Src1;
1437       RegOp = Src0;
1438     } else
1439       return std::make_pair(nullptr, SIOutMods::NONE);
1440 
1441     int OMod = getOModValue(Op, ImmOp->getImm());
1442     if (OMod == SIOutMods::NONE ||
1443         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1444         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1445         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1446         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1447       return std::make_pair(nullptr, SIOutMods::NONE);
1448 
1449     return std::make_pair(RegOp, OMod);
1450   }
1451   case AMDGPU::V_ADD_F32_e64:
1452   case AMDGPU::V_ADD_F16_e64: {
1453     // If output denormals are enabled, omod is ignored.
1454     if ((Op == AMDGPU::V_ADD_F32_e64 && MFI->getMode().FP32OutputDenormals) ||
1455         (Op == AMDGPU::V_ADD_F16_e64 && MFI->getMode().FP64FP16OutputDenormals))
1456       return std::make_pair(nullptr, SIOutMods::NONE);
1457 
1458     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1459     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1460     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1461 
1462     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1463         Src0->getSubReg() == Src1->getSubReg() &&
1464         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1465         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1466         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1467         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1468       return std::make_pair(Src0, SIOutMods::MUL2);
1469 
1470     return std::make_pair(nullptr, SIOutMods::NONE);
1471   }
1472   default:
1473     return std::make_pair(nullptr, SIOutMods::NONE);
1474   }
1475 }
1476 
1477 // FIXME: Does this need to check IEEE bit on function?
1478 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
1479   const MachineOperand *RegOp;
1480   int OMod;
1481   std::tie(RegOp, OMod) = isOMod(MI);
1482   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1483       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1484       !hasOneNonDBGUseInst(*MRI, RegOp->getReg()))
1485     return false;
1486 
1487   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1488   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1489   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1490     return false;
1491 
1492   // Clamp is applied after omod. If the source already has clamp set, don't
1493   // fold it.
1494   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1495     return false;
1496 
1497   LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def << '\n');
1498 
1499   DefOMod->setImm(OMod);
1500   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1501   MI.eraseFromParent();
1502   return true;
1503 }
1504 
1505 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
1506   if (skipFunction(MF.getFunction()))
1507     return false;
1508 
1509   MRI = &MF.getRegInfo();
1510   ST = &MF.getSubtarget<GCNSubtarget>();
1511   TII = ST->getInstrInfo();
1512   TRI = &TII->getRegisterInfo();
1513   MFI = MF.getInfo<SIMachineFunctionInfo>();
1514 
1515   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
1516   // correctly handle signed zeros.
1517   //
1518   // FIXME: Also need to check strictfp
1519   bool IsIEEEMode = MFI->getMode().IEEE;
1520   bool HasNSZ = MFI->hasNoSignedZerosFPMath();
1521 
1522   for (MachineBasicBlock *MBB : depth_first(&MF)) {
1523     MachineBasicBlock::iterator I, Next;
1524 
1525     MachineOperand *CurrentKnownM0Val = nullptr;
1526     for (I = MBB->begin(); I != MBB->end(); I = Next) {
1527       Next = std::next(I);
1528       MachineInstr &MI = *I;
1529 
1530       tryFoldInst(TII, &MI);
1531 
1532       if (!TII->isFoldableCopy(MI)) {
1533         // Saw an unknown clobber of m0, so we no longer know what it is.
1534         if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
1535           CurrentKnownM0Val = nullptr;
1536 
1537         // TODO: Omod might be OK if there is NSZ only on the source
1538         // instruction, and not the omod multiply.
1539         if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
1540             !tryFoldOMod(MI))
1541           tryFoldClamp(MI);
1542 
1543         continue;
1544       }
1545 
1546       // Specially track simple redefs of m0 to the same value in a block, so we
1547       // can erase the later ones.
1548       if (MI.getOperand(0).getReg() == AMDGPU::M0) {
1549         MachineOperand &NewM0Val = MI.getOperand(1);
1550         if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) {
1551           MI.eraseFromParent();
1552           continue;
1553         }
1554 
1555         // We aren't tracking other physical registers
1556         CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical()) ?
1557           nullptr : &NewM0Val;
1558         continue;
1559       }
1560 
1561       MachineOperand &OpToFold = MI.getOperand(1);
1562       bool FoldingImm =
1563           OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1564 
1565       // FIXME: We could also be folding things like TargetIndexes.
1566       if (!FoldingImm && !OpToFold.isReg())
1567         continue;
1568 
1569       if (OpToFold.isReg() && !OpToFold.getReg().isVirtual())
1570         continue;
1571 
1572       // Prevent folding operands backwards in the function. For example,
1573       // the COPY opcode must not be replaced by 1 in this example:
1574       //
1575       //    %3 = COPY %vgpr0; VGPR_32:%3
1576       //    ...
1577       //    %vgpr0 = V_MOV_B32_e32 1, implicit %exec
1578       MachineOperand &Dst = MI.getOperand(0);
1579       if (Dst.isReg() && !Dst.getReg().isVirtual())
1580         continue;
1581 
1582       foldInstOperand(MI, OpToFold);
1583     }
1584   }
1585   return true;
1586 }
1587