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