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