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