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