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