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