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