xref: /llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp (revision bf6cab6f07e1db2329c36b5d8009bf4b16d2761c)
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);
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.getVRegDef(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.getVRegDef(Sub->getReg());
508          SubDef && Sub->isReg() && !Sub->getSubReg() &&
509          TII->isFoldableCopy(*SubDef);
510          SubDef = MRI.getVRegDef(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 (isUseMIInFoldList(FoldList, UseMI))
559     return false;
560 
561   MachineRegisterInfo &MRI = UseMI->getParent()->getParent()->getRegInfo();
562 
563   // Maybe it is just a COPY of an immediate itself.
564   MachineInstr *Def = MRI.getVRegDef(UseReg);
565   MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
566   if (!UseOp.getSubReg() && Def && TII->isFoldableCopy(*Def)) {
567     MachineOperand &DefOp = Def->getOperand(1);
568     if (DefOp.isImm() && TII->isInlineConstant(DefOp, OpTy) &&
569         TII->isOperandLegal(*UseMI, UseOpIdx, &DefOp)) {
570       UseMI->getOperand(UseOpIdx).ChangeToImmediate(DefOp.getImm());
571       return true;
572     }
573   }
574 
575   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
576   if (!getRegSeqInit(Defs, UseReg, OpTy, TII, MRI))
577     return false;
578 
579   int32_t Imm;
580   for (unsigned I = 0, E = Defs.size(); I != E; ++I) {
581     const MachineOperand *Op = Defs[I].first;
582     if (!Op->isImm())
583       return false;
584 
585     auto SubImm = Op->getImm();
586     if (!I) {
587       Imm = SubImm;
588       if (!TII->isInlineConstant(*Op, OpTy) ||
589           !TII->isOperandLegal(*UseMI, UseOpIdx, Op))
590         return false;
591 
592       continue;
593     }
594     if (Imm != SubImm)
595       return false; // Can only fold splat constants
596   }
597 
598   appendFoldCandidate(FoldList, UseMI, UseOpIdx, Defs[0].first);
599   return true;
600 }
601 
602 void SIFoldOperands::foldOperand(
603   MachineOperand &OpToFold,
604   MachineInstr *UseMI,
605   int UseOpIdx,
606   SmallVectorImpl<FoldCandidate> &FoldList,
607   SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
608   const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
609 
610   if (!isUseSafeToFold(TII, *UseMI, UseOp))
611     return;
612 
613   // FIXME: Fold operands with subregs.
614   if (UseOp.isReg() && OpToFold.isReg()) {
615     if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
616       return;
617   }
618 
619   // Special case for REG_SEQUENCE: We can't fold literals into
620   // REG_SEQUENCE instructions, so we have to fold them into the
621   // uses of REG_SEQUENCE.
622   if (UseMI->isRegSequence()) {
623     Register RegSeqDstReg = UseMI->getOperand(0).getReg();
624     unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
625 
626     for (auto &RSUse : make_early_inc_range(MRI->use_nodbg_operands(RegSeqDstReg))) {
627       MachineInstr *RSUseMI = RSUse.getParent();
628 
629       if (tryToFoldACImm(TII, UseMI->getOperand(0), RSUseMI,
630                          RSUseMI->getOperandNo(&RSUse), FoldList))
631         continue;
632 
633       if (RSUse.getSubReg() != RegSeqDstSubReg)
634         continue;
635 
636       foldOperand(OpToFold, RSUseMI, RSUseMI->getOperandNo(&RSUse), FoldList,
637                   CopiesToReplace);
638     }
639 
640     return;
641   }
642 
643   if (tryToFoldACImm(TII, OpToFold, UseMI, UseOpIdx, FoldList))
644     return;
645 
646   if (frameIndexMayFold(TII, *UseMI, UseOpIdx, OpToFold)) {
647     // Sanity check that this is a stack access.
648     // FIXME: Should probably use stack pseudos before frame lowering.
649 
650     if (TII->isMUBUF(*UseMI)) {
651       if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() !=
652           MFI->getScratchRSrcReg())
653         return;
654 
655       // Ensure this is either relative to the current frame or the current
656       // wave.
657       MachineOperand &SOff =
658           *TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset);
659       if (!SOff.isImm() || SOff.getImm() != 0)
660         return;
661     }
662 
663     // A frame index will resolve to a positive constant, so it should always be
664     // safe to fold the addressing mode, even pre-GFX9.
665     UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getIndex());
666 
667     if (TII->isFLATScratch(*UseMI) &&
668         AMDGPU::getNamedOperandIdx(UseMI->getOpcode(),
669                                    AMDGPU::OpName::vaddr) != -1) {
670       unsigned NewOpc = AMDGPU::getFlatScratchInstSSfromSV(UseMI->getOpcode());
671       UseMI->setDesc(TII->get(NewOpc));
672     }
673 
674     return;
675   }
676 
677   bool FoldingImmLike =
678       OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
679 
680   if (FoldingImmLike && UseMI->isCopy()) {
681     Register DestReg = UseMI->getOperand(0).getReg();
682     Register SrcReg = UseMI->getOperand(1).getReg();
683     assert(SrcReg.isVirtual());
684 
685     const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
686 
687     // Don't fold into a copy to a physical register with the same class. Doing
688     // so would interfere with the register coalescer's logic which would avoid
689     // redundant initalizations.
690     if (DestReg.isPhysical() && SrcRC->contains(DestReg))
691       return;
692 
693     const TargetRegisterClass *DestRC = TRI->getRegClassForReg(*MRI, DestReg);
694     if (!DestReg.isPhysical()) {
695       if (TRI->isSGPRClass(SrcRC) && TRI->hasVectorRegisters(DestRC)) {
696         SmallVector<FoldCandidate, 4> CopyUses;
697         for (auto &Use : make_early_inc_range(MRI->use_nodbg_operands(DestReg))) {
698           // There's no point trying to fold into an implicit operand.
699           if (Use.isImplicit())
700             continue;
701 
702           FoldCandidate FC = FoldCandidate(Use.getParent(), Use.getParent()->getOperandNo(&Use),
703                                            &UseMI->getOperand(1));
704           CopyUses.push_back(FC);
705         }
706         for (auto &F : CopyUses) {
707           foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo, FoldList, CopiesToReplace);
708         }
709       }
710 
711       if (DestRC == &AMDGPU::AGPR_32RegClass &&
712           TII->isInlineConstant(OpToFold, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
713         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
714         UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
715         CopiesToReplace.push_back(UseMI);
716         return;
717       }
718     }
719 
720     // In order to fold immediates into copies, we need to change the
721     // copy to a MOV.
722 
723     unsigned MovOp = TII->getMovOpcode(DestRC);
724     if (MovOp == AMDGPU::COPY)
725       return;
726 
727     UseMI->setDesc(TII->get(MovOp));
728     MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin();
729     MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end();
730     while (ImpOpI != ImpOpE) {
731       MachineInstr::mop_iterator Tmp = ImpOpI;
732       ImpOpI++;
733       UseMI->RemoveOperand(UseMI->getOperandNo(Tmp));
734     }
735     CopiesToReplace.push_back(UseMI);
736   } else {
737     if (UseMI->isCopy() && OpToFold.isReg() &&
738         UseMI->getOperand(0).getReg().isVirtual() &&
739         !UseMI->getOperand(1).getSubReg()) {
740       LLVM_DEBUG(dbgs() << "Folding " << OpToFold << "\n into " << *UseMI);
741       unsigned Size = TII->getOpSize(*UseMI, 1);
742       Register UseReg = OpToFold.getReg();
743       UseMI->getOperand(1).setReg(UseReg);
744       UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
745       UseMI->getOperand(1).setIsKill(false);
746       CopiesToReplace.push_back(UseMI);
747       OpToFold.setIsKill(false);
748 
749       // That is very tricky to store a value into an AGPR. v_accvgpr_write_b32
750       // can only accept VGPR or inline immediate. Recreate a reg_sequence with
751       // its initializers right here, so we will rematerialize immediates and
752       // avoid copies via different reg classes.
753       SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
754       if (Size > 4 && TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
755           getRegSeqInit(Defs, UseReg, AMDGPU::OPERAND_REG_INLINE_C_INT32, TII,
756                         *MRI)) {
757         const DebugLoc &DL = UseMI->getDebugLoc();
758         MachineBasicBlock &MBB = *UseMI->getParent();
759 
760         UseMI->setDesc(TII->get(AMDGPU::REG_SEQUENCE));
761         for (unsigned I = UseMI->getNumOperands() - 1; I > 0; --I)
762           UseMI->RemoveOperand(I);
763 
764         MachineInstrBuilder B(*MBB.getParent(), UseMI);
765         DenseMap<TargetInstrInfo::RegSubRegPair, Register> VGPRCopies;
766         SmallSetVector<TargetInstrInfo::RegSubRegPair, 32> SeenAGPRs;
767         for (unsigned I = 0; I < Size / 4; ++I) {
768           MachineOperand *Def = Defs[I].first;
769           TargetInstrInfo::RegSubRegPair CopyToVGPR;
770           if (Def->isImm() &&
771               TII->isInlineConstant(*Def, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
772             int64_t Imm = Def->getImm();
773 
774             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
775             BuildMI(MBB, UseMI, DL,
776                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addImm(Imm);
777             B.addReg(Tmp);
778           } else if (Def->isReg() && TRI->isAGPR(*MRI, Def->getReg())) {
779             auto Src = getRegSubRegPair(*Def);
780             Def->setIsKill(false);
781             if (!SeenAGPRs.insert(Src)) {
782               // We cannot build a reg_sequence out of the same registers, they
783               // must be copied. Better do it here before copyPhysReg() created
784               // several reads to do the AGPR->VGPR->AGPR copy.
785               CopyToVGPR = Src;
786             } else {
787               B.addReg(Src.Reg, Def->isUndef() ? RegState::Undef : 0,
788                        Src.SubReg);
789             }
790           } else {
791             assert(Def->isReg());
792             Def->setIsKill(false);
793             auto Src = getRegSubRegPair(*Def);
794 
795             // Direct copy from SGPR to AGPR is not possible. To avoid creation
796             // of exploded copies SGPR->VGPR->AGPR in the copyPhysReg() later,
797             // create a copy here and track if we already have such a copy.
798             if (TRI->isSGPRReg(*MRI, Src.Reg)) {
799               CopyToVGPR = Src;
800             } else {
801               auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
802               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Tmp).add(*Def);
803               B.addReg(Tmp);
804             }
805           }
806 
807           if (CopyToVGPR.Reg) {
808             Register Vgpr;
809             if (VGPRCopies.count(CopyToVGPR)) {
810               Vgpr = VGPRCopies[CopyToVGPR];
811             } else {
812               Vgpr = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
813               BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Vgpr).add(*Def);
814               VGPRCopies[CopyToVGPR] = Vgpr;
815             }
816             auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
817             BuildMI(MBB, UseMI, DL,
818                     TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addReg(Vgpr);
819             B.addReg(Tmp);
820           }
821 
822           B.addImm(Defs[I].second);
823         }
824         LLVM_DEBUG(dbgs() << "Folded " << *UseMI);
825         return;
826       }
827 
828       if (Size != 4)
829         return;
830       if (TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
831           TRI->isVGPR(*MRI, UseMI->getOperand(1).getReg()))
832         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64));
833       else if (TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) &&
834                TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg()))
835         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64));
836       else if (ST->hasGFX90AInsts() &&
837                TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) &&
838                TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg()))
839         UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_MOV_B32));
840       return;
841     }
842 
843     unsigned UseOpc = UseMI->getOpcode();
844     if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
845         (UseOpc == AMDGPU::V_READLANE_B32 &&
846          (int)UseOpIdx ==
847          AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) {
848       // %vgpr = V_MOV_B32 imm
849       // %sgpr = V_READFIRSTLANE_B32 %vgpr
850       // =>
851       // %sgpr = S_MOV_B32 imm
852       if (FoldingImmLike) {
853         if (execMayBeModifiedBeforeUse(*MRI,
854                                        UseMI->getOperand(UseOpIdx).getReg(),
855                                        *OpToFold.getParent(),
856                                        *UseMI))
857           return;
858 
859         UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32));
860 
861         if (OpToFold.isImm())
862           UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm());
863         else
864           UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getIndex());
865         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
866         return;
867       }
868 
869       if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) {
870         if (execMayBeModifiedBeforeUse(*MRI,
871                                        UseMI->getOperand(UseOpIdx).getReg(),
872                                        *OpToFold.getParent(),
873                                        *UseMI))
874           return;
875 
876         // %vgpr = COPY %sgpr0
877         // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
878         // =>
879         // %sgpr1 = COPY %sgpr0
880         UseMI->setDesc(TII->get(AMDGPU::COPY));
881         UseMI->getOperand(1).setReg(OpToFold.getReg());
882         UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
883         UseMI->getOperand(1).setIsKill(false);
884         UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane)
885         return;
886       }
887     }
888 
889     const MCInstrDesc &UseDesc = UseMI->getDesc();
890 
891     // Don't fold into target independent nodes.  Target independent opcodes
892     // don't have defined register classes.
893     if (UseDesc.isVariadic() ||
894         UseOp.isImplicit() ||
895         UseDesc.OpInfo[UseOpIdx].RegClass == -1)
896       return;
897   }
898 
899   if (!FoldingImmLike) {
900     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
901 
902     // FIXME: We could try to change the instruction from 64-bit to 32-bit
903     // to enable more folding opportunites.  The shrink operands pass
904     // already does this.
905     return;
906   }
907 
908 
909   const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
910   const TargetRegisterClass *FoldRC =
911     TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
912 
913   // Split 64-bit constants into 32-bits for folding.
914   if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
915     Register UseReg = UseOp.getReg();
916     const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg);
917 
918     if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
919       return;
920 
921     APInt Imm(64, OpToFold.getImm());
922     if (UseOp.getSubReg() == AMDGPU::sub0) {
923       Imm = Imm.getLoBits(32);
924     } else {
925       assert(UseOp.getSubReg() == AMDGPU::sub1);
926       Imm = Imm.getHiBits(32);
927     }
928 
929     MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
930     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
931     return;
932   }
933 
934 
935 
936   tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
937 }
938 
939 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
940                                   uint32_t LHS, uint32_t RHS) {
941   switch (Opcode) {
942   case AMDGPU::V_AND_B32_e64:
943   case AMDGPU::V_AND_B32_e32:
944   case AMDGPU::S_AND_B32:
945     Result = LHS & RHS;
946     return true;
947   case AMDGPU::V_OR_B32_e64:
948   case AMDGPU::V_OR_B32_e32:
949   case AMDGPU::S_OR_B32:
950     Result = LHS | RHS;
951     return true;
952   case AMDGPU::V_XOR_B32_e64:
953   case AMDGPU::V_XOR_B32_e32:
954   case AMDGPU::S_XOR_B32:
955     Result = LHS ^ RHS;
956     return true;
957   case AMDGPU::S_XNOR_B32:
958     Result = ~(LHS ^ RHS);
959     return true;
960   case AMDGPU::S_NAND_B32:
961     Result = ~(LHS & RHS);
962     return true;
963   case AMDGPU::S_NOR_B32:
964     Result = ~(LHS | RHS);
965     return true;
966   case AMDGPU::S_ANDN2_B32:
967     Result = LHS & ~RHS;
968     return true;
969   case AMDGPU::S_ORN2_B32:
970     Result = LHS | ~RHS;
971     return true;
972   case AMDGPU::V_LSHL_B32_e64:
973   case AMDGPU::V_LSHL_B32_e32:
974   case AMDGPU::S_LSHL_B32:
975     // The instruction ignores the high bits for out of bounds shifts.
976     Result = LHS << (RHS & 31);
977     return true;
978   case AMDGPU::V_LSHLREV_B32_e64:
979   case AMDGPU::V_LSHLREV_B32_e32:
980     Result = RHS << (LHS & 31);
981     return true;
982   case AMDGPU::V_LSHR_B32_e64:
983   case AMDGPU::V_LSHR_B32_e32:
984   case AMDGPU::S_LSHR_B32:
985     Result = LHS >> (RHS & 31);
986     return true;
987   case AMDGPU::V_LSHRREV_B32_e64:
988   case AMDGPU::V_LSHRREV_B32_e32:
989     Result = RHS >> (LHS & 31);
990     return true;
991   case AMDGPU::V_ASHR_I32_e64:
992   case AMDGPU::V_ASHR_I32_e32:
993   case AMDGPU::S_ASHR_I32:
994     Result = static_cast<int32_t>(LHS) >> (RHS & 31);
995     return true;
996   case AMDGPU::V_ASHRREV_I32_e64:
997   case AMDGPU::V_ASHRREV_I32_e32:
998     Result = static_cast<int32_t>(RHS) >> (LHS & 31);
999     return true;
1000   default:
1001     return false;
1002   }
1003 }
1004 
1005 static unsigned getMovOpc(bool IsScalar) {
1006   return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1007 }
1008 
1009 /// Remove any leftover implicit operands from mutating the instruction. e.g.
1010 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
1011 /// anymore.
1012 static void stripExtraCopyOperands(MachineInstr &MI) {
1013   const MCInstrDesc &Desc = MI.getDesc();
1014   unsigned NumOps = Desc.getNumOperands() +
1015                     Desc.getNumImplicitUses() +
1016                     Desc.getNumImplicitDefs();
1017 
1018   for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
1019     MI.RemoveOperand(I);
1020 }
1021 
1022 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
1023   MI.setDesc(NewDesc);
1024   stripExtraCopyOperands(MI);
1025 }
1026 
1027 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
1028                                                MachineOperand &Op) {
1029   if (Op.isReg()) {
1030     // If this has a subregister, it obviously is a register source.
1031     if (Op.getSubReg() != AMDGPU::NoSubRegister || !Op.getReg().isVirtual())
1032       return &Op;
1033 
1034     MachineInstr *Def = MRI.getVRegDef(Op.getReg());
1035     if (Def && Def->isMoveImmediate()) {
1036       MachineOperand &ImmSrc = Def->getOperand(1);
1037       if (ImmSrc.isImm())
1038         return &ImmSrc;
1039     }
1040   }
1041 
1042   return &Op;
1043 }
1044 
1045 // Try to simplify operations with a constant that may appear after instruction
1046 // selection.
1047 // TODO: See if a frame index with a fixed offset can fold.
1048 static bool tryConstantFoldOp(MachineRegisterInfo &MRI,
1049                               const SIInstrInfo *TII,
1050                               MachineInstr *MI,
1051                               MachineOperand *ImmOp) {
1052   unsigned Opc = MI->getOpcode();
1053   if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
1054       Opc == AMDGPU::S_NOT_B32) {
1055     MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm());
1056     mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
1057     return true;
1058   }
1059 
1060   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1061   if (Src1Idx == -1)
1062     return false;
1063 
1064   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1065   MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
1066   MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
1067 
1068   if (!Src0->isImm() && !Src1->isImm())
1069     return false;
1070 
1071   // and k0, k1 -> v_mov_b32 (k0 & k1)
1072   // or k0, k1 -> v_mov_b32 (k0 | k1)
1073   // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
1074   if (Src0->isImm() && Src1->isImm()) {
1075     int32_t NewImm;
1076     if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
1077       return false;
1078 
1079     const SIRegisterInfo &TRI = TII->getRegisterInfo();
1080     bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
1081 
1082     // Be careful to change the right operand, src0 may belong to a different
1083     // instruction.
1084     MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
1085     MI->RemoveOperand(Src1Idx);
1086     mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
1087     return true;
1088   }
1089 
1090   if (!MI->isCommutable())
1091     return false;
1092 
1093   if (Src0->isImm() && !Src1->isImm()) {
1094     std::swap(Src0, Src1);
1095     std::swap(Src0Idx, Src1Idx);
1096   }
1097 
1098   int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
1099   if (Opc == AMDGPU::V_OR_B32_e64 ||
1100       Opc == AMDGPU::V_OR_B32_e32 ||
1101       Opc == AMDGPU::S_OR_B32) {
1102     if (Src1Val == 0) {
1103       // y = or x, 0 => y = copy x
1104       MI->RemoveOperand(Src1Idx);
1105       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1106     } else if (Src1Val == -1) {
1107       // y = or x, -1 => y = v_mov_b32 -1
1108       MI->RemoveOperand(Src1Idx);
1109       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
1110     } else
1111       return false;
1112 
1113     return true;
1114   }
1115 
1116   if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
1117       MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
1118       MI->getOpcode() == AMDGPU::S_AND_B32) {
1119     if (Src1Val == 0) {
1120       // y = and x, 0 => y = v_mov_b32 0
1121       MI->RemoveOperand(Src0Idx);
1122       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
1123     } else if (Src1Val == -1) {
1124       // y = and x, -1 => y = copy x
1125       MI->RemoveOperand(Src1Idx);
1126       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1127       stripExtraCopyOperands(*MI);
1128     } else
1129       return false;
1130 
1131     return true;
1132   }
1133 
1134   if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
1135       MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
1136       MI->getOpcode() == AMDGPU::S_XOR_B32) {
1137     if (Src1Val == 0) {
1138       // y = xor x, 0 => y = copy x
1139       MI->RemoveOperand(Src1Idx);
1140       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1141       return true;
1142     }
1143   }
1144 
1145   return false;
1146 }
1147 
1148 // Try to fold an instruction into a simpler one
1149 static bool tryFoldCndMask(const SIInstrInfo *TII,
1150                            MachineInstr *MI) {
1151   unsigned Opc = MI->getOpcode();
1152 
1153   if (Opc == AMDGPU::V_CNDMASK_B32_e32    ||
1154       Opc == AMDGPU::V_CNDMASK_B32_e64    ||
1155       Opc == AMDGPU::V_CNDMASK_B64_PSEUDO) {
1156     const MachineOperand *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
1157     const MachineOperand *Src1 = TII->getNamedOperand(*MI, AMDGPU::OpName::src1);
1158     int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
1159     int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
1160     if (Src1->isIdenticalTo(*Src0) &&
1161         (Src1ModIdx == -1 || !MI->getOperand(Src1ModIdx).getImm()) &&
1162         (Src0ModIdx == -1 || !MI->getOperand(Src0ModIdx).getImm())) {
1163       LLVM_DEBUG(dbgs() << "Folded " << *MI << " into ");
1164       auto &NewDesc =
1165           TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false));
1166       int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
1167       if (Src2Idx != -1)
1168         MI->RemoveOperand(Src2Idx);
1169       MI->RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
1170       if (Src1ModIdx != -1)
1171         MI->RemoveOperand(Src1ModIdx);
1172       if (Src0ModIdx != -1)
1173         MI->RemoveOperand(Src0ModIdx);
1174       mutateCopyOp(*MI, NewDesc);
1175       LLVM_DEBUG(dbgs() << *MI);
1176       return true;
1177     }
1178   }
1179 
1180   return false;
1181 }
1182 
1183 void SIFoldOperands::foldInstOperand(MachineInstr &MI,
1184                                      MachineOperand &OpToFold) const {
1185   // We need mutate the operands of new mov instructions to add implicit
1186   // uses of EXEC, but adding them invalidates the use_iterator, so defer
1187   // this.
1188   SmallVector<MachineInstr *, 4> CopiesToReplace;
1189   SmallVector<FoldCandidate, 4> FoldList;
1190   MachineOperand &Dst = MI.getOperand(0);
1191 
1192   bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1193   if (FoldingImm) {
1194     unsigned NumLiteralUses = 0;
1195     MachineOperand *NonInlineUse = nullptr;
1196     int NonInlineUseOpNo = -1;
1197 
1198     bool Again;
1199     do {
1200       Again = false;
1201       for (auto &Use : make_early_inc_range(MRI->use_nodbg_operands(Dst.getReg()))) {
1202         MachineInstr *UseMI = Use.getParent();
1203         unsigned OpNo = UseMI->getOperandNo(&Use);
1204 
1205         // Folding the immediate may reveal operations that can be constant
1206         // folded or replaced with a copy. This can happen for example after
1207         // frame indices are lowered to constants or from splitting 64-bit
1208         // constants.
1209         //
1210         // We may also encounter cases where one or both operands are
1211         // immediates materialized into a register, which would ordinarily not
1212         // be folded due to multiple uses or operand constraints.
1213 
1214         if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) {
1215           LLVM_DEBUG(dbgs() << "Constant folded " << *UseMI);
1216 
1217           // Some constant folding cases change the same immediate's use to a new
1218           // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user
1219           // again. The same constant folded instruction could also have a second
1220           // use operand.
1221           FoldList.clear();
1222           Again = true;
1223           break;
1224         }
1225 
1226         // Try to fold any inline immediate uses, and then only fold other
1227         // constants if they have one use.
1228         //
1229         // The legality of the inline immediate must be checked based on the use
1230         // operand, not the defining instruction, because 32-bit instructions
1231         // with 32-bit inline immediate sources may be used to materialize
1232         // constants used in 16-bit operands.
1233         //
1234         // e.g. it is unsafe to fold:
1235         //  s_mov_b32 s0, 1.0    // materializes 0x3f800000
1236         //  v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
1237 
1238         // Folding immediates with more than one use will increase program size.
1239         // FIXME: This will also reduce register usage, which may be better
1240         // in some cases. A better heuristic is needed.
1241         if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
1242           foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
1243         } else if (frameIndexMayFold(TII, *UseMI, OpNo, OpToFold)) {
1244           foldOperand(OpToFold, UseMI, OpNo, FoldList,
1245                       CopiesToReplace);
1246         } else {
1247           if (++NumLiteralUses == 1) {
1248             NonInlineUse = &Use;
1249             NonInlineUseOpNo = OpNo;
1250           }
1251         }
1252       }
1253     } while (Again);
1254 
1255     if (NumLiteralUses == 1) {
1256       MachineInstr *UseMI = NonInlineUse->getParent();
1257       foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
1258     }
1259   } else {
1260     // Folding register.
1261     SmallVector <MachineOperand *, 4> UsesToProcess;
1262     for (auto &Use : MRI->use_nodbg_operands(Dst.getReg()))
1263       UsesToProcess.push_back(&Use);
1264     for (auto U : UsesToProcess) {
1265       MachineInstr *UseMI = U->getParent();
1266 
1267       foldOperand(OpToFold, UseMI, UseMI->getOperandNo(U),
1268         FoldList, CopiesToReplace);
1269     }
1270   }
1271 
1272   MachineFunction *MF = MI.getParent()->getParent();
1273   // Make sure we add EXEC uses to any new v_mov instructions created.
1274   for (MachineInstr *Copy : CopiesToReplace)
1275     Copy->addImplicitDefUseOperands(*MF);
1276 
1277   SmallPtrSet<MachineInstr *, 16> Folded;
1278   for (FoldCandidate &Fold : FoldList) {
1279     assert(!Fold.isReg() || Fold.OpToFold);
1280     if (Folded.count(Fold.UseMI))
1281       continue;
1282     if (Fold.isReg() && Fold.OpToFold->getReg().isVirtual()) {
1283       Register Reg = Fold.OpToFold->getReg();
1284       MachineInstr *DefMI = Fold.OpToFold->getParent();
1285       if (DefMI->readsRegister(AMDGPU::EXEC, TRI) &&
1286           execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI))
1287         continue;
1288     }
1289     if (updateOperand(Fold, *TII, *TRI, *ST)) {
1290       // Clear kill flags.
1291       if (Fold.isReg()) {
1292         assert(Fold.OpToFold && Fold.OpToFold->isReg());
1293         // FIXME: Probably shouldn't bother trying to fold if not an
1294         // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
1295         // copies.
1296         MRI->clearKillFlags(Fold.OpToFold->getReg());
1297       }
1298       LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
1299                         << static_cast<int>(Fold.UseOpNo) << " of "
1300                         << *Fold.UseMI);
1301       if (tryFoldCndMask(TII, Fold.UseMI))
1302         Folded.insert(Fold.UseMI);
1303     } else if (Fold.isCommuted()) {
1304       // Restoring instruction's original operand order if fold has failed.
1305       TII->commuteInstruction(*Fold.UseMI, false);
1306     }
1307   }
1308 }
1309 
1310 // Clamp patterns are canonically selected to v_max_* instructions, so only
1311 // handle them.
1312 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
1313   unsigned Op = MI.getOpcode();
1314   switch (Op) {
1315   case AMDGPU::V_MAX_F32_e64:
1316   case AMDGPU::V_MAX_F16_e64:
1317   case AMDGPU::V_MAX_F64_e64:
1318   case AMDGPU::V_PK_MAX_F16: {
1319     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
1320       return nullptr;
1321 
1322     // Make sure sources are identical.
1323     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1324     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1325     if (!Src0->isReg() || !Src1->isReg() ||
1326         Src0->getReg() != Src1->getReg() ||
1327         Src0->getSubReg() != Src1->getSubReg() ||
1328         Src0->getSubReg() != AMDGPU::NoSubRegister)
1329       return nullptr;
1330 
1331     // Can't fold up if we have modifiers.
1332     if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1333       return nullptr;
1334 
1335     unsigned Src0Mods
1336       = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
1337     unsigned Src1Mods
1338       = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
1339 
1340     // Having a 0 op_sel_hi would require swizzling the output in the source
1341     // instruction, which we can't do.
1342     unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1
1343                                                       : 0u;
1344     if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
1345       return nullptr;
1346     return Src0;
1347   }
1348   default:
1349     return nullptr;
1350   }
1351 }
1352 
1353 // FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
1354 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
1355   const MachineOperand *ClampSrc = isClamp(MI);
1356   if (!ClampSrc || !MRI->hasOneNonDBGUser(ClampSrc->getReg()))
1357     return false;
1358 
1359   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
1360 
1361   // The type of clamp must be compatible.
1362   if (TII->getClampMask(*Def) != TII->getClampMask(MI))
1363     return false;
1364 
1365   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
1366   if (!DefClamp)
1367     return false;
1368 
1369   LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def);
1370 
1371   // Clamp is applied after omod, so it is OK if omod is set.
1372   DefClamp->setImm(1);
1373   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1374   MI.eraseFromParent();
1375   return true;
1376 }
1377 
1378 static int getOModValue(unsigned Opc, int64_t Val) {
1379   switch (Opc) {
1380   case AMDGPU::V_MUL_F64_e64: {
1381     switch (Val) {
1382     case 0x3fe0000000000000: // 0.5
1383       return SIOutMods::DIV2;
1384     case 0x4000000000000000: // 2.0
1385       return SIOutMods::MUL2;
1386     case 0x4010000000000000: // 4.0
1387       return SIOutMods::MUL4;
1388     default:
1389       return SIOutMods::NONE;
1390     }
1391   }
1392   case AMDGPU::V_MUL_F32_e64: {
1393     switch (static_cast<uint32_t>(Val)) {
1394     case 0x3f000000: // 0.5
1395       return SIOutMods::DIV2;
1396     case 0x40000000: // 2.0
1397       return SIOutMods::MUL2;
1398     case 0x40800000: // 4.0
1399       return SIOutMods::MUL4;
1400     default:
1401       return SIOutMods::NONE;
1402     }
1403   }
1404   case AMDGPU::V_MUL_F16_e64: {
1405     switch (static_cast<uint16_t>(Val)) {
1406     case 0x3800: // 0.5
1407       return SIOutMods::DIV2;
1408     case 0x4000: // 2.0
1409       return SIOutMods::MUL2;
1410     case 0x4400: // 4.0
1411       return SIOutMods::MUL4;
1412     default:
1413       return SIOutMods::NONE;
1414     }
1415   }
1416   default:
1417     llvm_unreachable("invalid mul opcode");
1418   }
1419 }
1420 
1421 // FIXME: Does this really not support denormals with f16?
1422 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
1423 // handled, so will anything other than that break?
1424 std::pair<const MachineOperand *, int>
1425 SIFoldOperands::isOMod(const MachineInstr &MI) const {
1426   unsigned Op = MI.getOpcode();
1427   switch (Op) {
1428   case AMDGPU::V_MUL_F64_e64:
1429   case AMDGPU::V_MUL_F32_e64:
1430   case AMDGPU::V_MUL_F16_e64: {
1431     // If output denormals are enabled, omod is ignored.
1432     if ((Op == AMDGPU::V_MUL_F32_e64 && MFI->getMode().FP32OutputDenormals) ||
1433         ((Op == AMDGPU::V_MUL_F64_e64 || Op == AMDGPU::V_MUL_F16_e64) &&
1434          MFI->getMode().FP64FP16OutputDenormals))
1435       return std::make_pair(nullptr, SIOutMods::NONE);
1436 
1437     const MachineOperand *RegOp = nullptr;
1438     const MachineOperand *ImmOp = nullptr;
1439     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1440     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1441     if (Src0->isImm()) {
1442       ImmOp = Src0;
1443       RegOp = Src1;
1444     } else if (Src1->isImm()) {
1445       ImmOp = Src1;
1446       RegOp = Src0;
1447     } else
1448       return std::make_pair(nullptr, SIOutMods::NONE);
1449 
1450     int OMod = getOModValue(Op, ImmOp->getImm());
1451     if (OMod == SIOutMods::NONE ||
1452         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
1453         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
1454         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
1455         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
1456       return std::make_pair(nullptr, SIOutMods::NONE);
1457 
1458     return std::make_pair(RegOp, OMod);
1459   }
1460   case AMDGPU::V_ADD_F64_e64:
1461   case AMDGPU::V_ADD_F32_e64:
1462   case AMDGPU::V_ADD_F16_e64: {
1463     // If output denormals are enabled, omod is ignored.
1464     if ((Op == AMDGPU::V_ADD_F32_e64 && MFI->getMode().FP32OutputDenormals) ||
1465         ((Op == AMDGPU::V_ADD_F64_e64 || Op == AMDGPU::V_ADD_F16_e64) &&
1466          MFI->getMode().FP64FP16OutputDenormals))
1467       return std::make_pair(nullptr, SIOutMods::NONE);
1468 
1469     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
1470     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1471     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1472 
1473     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
1474         Src0->getSubReg() == Src1->getSubReg() &&
1475         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
1476         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
1477         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
1478         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
1479       return std::make_pair(Src0, SIOutMods::MUL2);
1480 
1481     return std::make_pair(nullptr, SIOutMods::NONE);
1482   }
1483   default:
1484     return std::make_pair(nullptr, SIOutMods::NONE);
1485   }
1486 }
1487 
1488 // FIXME: Does this need to check IEEE bit on function?
1489 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
1490   const MachineOperand *RegOp;
1491   int OMod;
1492   std::tie(RegOp, OMod) = isOMod(MI);
1493   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
1494       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
1495       !MRI->hasOneNonDBGUser(RegOp->getReg()))
1496     return false;
1497 
1498   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
1499   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
1500   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
1501     return false;
1502 
1503   // Clamp is applied after omod. If the source already has clamp set, don't
1504   // fold it.
1505   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
1506     return false;
1507 
1508   LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def);
1509 
1510   DefOMod->setImm(OMod);
1511   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
1512   MI.eraseFromParent();
1513   return true;
1514 }
1515 
1516 // Try to fold a reg_sequence with vgpr output and agpr inputs into an
1517 // instruction which can take an agpr. So far that means a store.
1518 bool SIFoldOperands::tryFoldRegSequence(MachineInstr &MI) {
1519   assert(MI.isRegSequence());
1520   auto Reg = MI.getOperand(0).getReg();
1521 
1522   if (!ST->hasGFX90AInsts() || !TRI->isVGPR(*MRI, Reg) ||
1523       !MRI->hasOneNonDBGUse(Reg))
1524     return false;
1525 
1526   SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
1527   if (!getRegSeqInit(Defs, Reg, MCOI::OPERAND_REGISTER, TII, *MRI))
1528     return false;
1529 
1530   for (auto &Def : Defs) {
1531     const auto *Op = Def.first;
1532     if (!Op->isReg())
1533       return false;
1534     if (TRI->isAGPR(*MRI, Op->getReg()))
1535       continue;
1536     // Maybe this is a COPY from AREG
1537     const MachineInstr *SubDef = MRI->getVRegDef(Op->getReg());
1538     if (!SubDef || !SubDef->isCopy() || SubDef->getOperand(1).getSubReg())
1539       return false;
1540     if (!TRI->isAGPR(*MRI, SubDef->getOperand(1).getReg()))
1541       return false;
1542   }
1543 
1544   MachineOperand *Op = &*MRI->use_nodbg_begin(Reg);
1545   MachineInstr *UseMI = Op->getParent();
1546   while (UseMI->isCopy() && !Op->getSubReg()) {
1547     Reg = UseMI->getOperand(0).getReg();
1548     if (!TRI->isVGPR(*MRI, Reg) || !MRI->hasOneNonDBGUse(Reg))
1549       return false;
1550     Op = &*MRI->use_nodbg_begin(Reg);
1551     UseMI = Op->getParent();
1552   }
1553 
1554   if (Op->getSubReg())
1555     return false;
1556 
1557   unsigned OpIdx = Op - &UseMI->getOperand(0);
1558   const MCInstrDesc &InstDesc = UseMI->getDesc();
1559   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
1560   switch (OpInfo.RegClass) {
1561   case AMDGPU::AV_32RegClassID:  LLVM_FALLTHROUGH;
1562   case AMDGPU::AV_64RegClassID:  LLVM_FALLTHROUGH;
1563   case AMDGPU::AV_96RegClassID:  LLVM_FALLTHROUGH;
1564   case AMDGPU::AV_128RegClassID: LLVM_FALLTHROUGH;
1565   case AMDGPU::AV_160RegClassID:
1566     break;
1567   default:
1568     return false;
1569   }
1570 
1571   const auto *NewDstRC = TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg));
1572   auto Dst = MRI->createVirtualRegister(NewDstRC);
1573   auto RS = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1574                     TII->get(AMDGPU::REG_SEQUENCE), Dst);
1575 
1576   for (unsigned I = 0; I < Defs.size(); ++I) {
1577     MachineOperand *Def = Defs[I].first;
1578     Def->setIsKill(false);
1579     if (TRI->isAGPR(*MRI, Def->getReg())) {
1580       RS.add(*Def);
1581     } else { // This is a copy
1582       MachineInstr *SubDef = MRI->getVRegDef(Def->getReg());
1583       SubDef->getOperand(1).setIsKill(false);
1584       RS.addReg(SubDef->getOperand(1).getReg(), 0, Def->getSubReg());
1585     }
1586     RS.addImm(Defs[I].second);
1587   }
1588 
1589   Op->setReg(Dst);
1590   if (!TII->isOperandLegal(*UseMI, OpIdx, Op)) {
1591     Op->setReg(Reg);
1592     RS->eraseFromParent();
1593     return false;
1594   }
1595 
1596   LLVM_DEBUG(dbgs() << "Folded " << *RS << " into " << *UseMI);
1597 
1598   return true;
1599 }
1600 
1601 // Try to hoist an AGPR to VGPR copy out of the loop across a LCSSA PHI.
1602 // This should allow folding of an AGPR into a consumer which may support it.
1603 // I.e.:
1604 //
1605 // loop:                             // loop:
1606 //   %1:vreg = COPY %0:areg          // exit:
1607 // exit:                          => //   %1:areg = PHI %0:areg, %loop
1608 //   %2:vreg = PHI %1:vreg, %loop    //   %2:vreg = COPY %1:areg
1609 bool SIFoldOperands::tryFoldLCSSAPhi(MachineInstr &PHI) {
1610   assert(PHI.isPHI());
1611 
1612   if (PHI.getNumExplicitOperands() != 3) // Single input LCSSA PHI
1613     return false;
1614 
1615   Register PhiIn = PHI.getOperand(1).getReg();
1616   Register PhiOut = PHI.getOperand(0).getReg();
1617   if (PHI.getOperand(1).getSubReg() ||
1618       !TRI->isVGPR(*MRI, PhiIn) || !TRI->isVGPR(*MRI, PhiOut))
1619     return false;
1620 
1621   // A single use should not matter for correctness, but if it has another use
1622   // inside the loop we may perform copy twice in a worst case.
1623   if (!MRI->hasOneNonDBGUse(PhiIn))
1624     return false;
1625 
1626   MachineInstr *Copy = MRI->getVRegDef(PhiIn);
1627   if (!Copy || !Copy->isCopy())
1628     return false;
1629 
1630   Register CopyIn = Copy->getOperand(1).getReg();
1631   if (!TRI->isAGPR(*MRI, CopyIn) || Copy->getOperand(1).getSubReg())
1632     return false;
1633 
1634   const TargetRegisterClass *ARC = MRI->getRegClass(CopyIn);
1635   Register NewReg = MRI->createVirtualRegister(ARC);
1636   PHI.getOperand(1).setReg(CopyIn);
1637   PHI.getOperand(0).setReg(NewReg);
1638 
1639   MachineBasicBlock *MBB = PHI.getParent();
1640   BuildMI(*MBB, MBB->getFirstNonPHI(), Copy->getDebugLoc(),
1641           TII->get(AMDGPU::COPY), PhiOut)
1642     .addReg(NewReg, RegState::Kill);
1643   Copy->eraseFromParent(); // We know this copy had a single use.
1644 
1645   LLVM_DEBUG(dbgs() << "Folded " << PHI);
1646 
1647   return true;
1648 }
1649 
1650 // Attempt to convert VGPR load to an AGPR load.
1651 bool SIFoldOperands::tryFoldLoad(MachineInstr &MI) {
1652   assert(MI.mayLoad());
1653   if (!ST->hasGFX90AInsts() || !MI.getNumOperands())
1654     return false;
1655 
1656   MachineOperand &Def = MI.getOperand(0);
1657   if (!Def.isDef())
1658     return false;
1659 
1660   Register DefReg = Def.getReg();
1661 
1662   if (DefReg.isPhysical() || !TRI->isVGPR(*MRI, DefReg))
1663     return false;
1664 
1665   SmallVector<const MachineInstr*, 8> Users;
1666   SmallVector<Register, 8> MoveRegs;
1667   for (const MachineInstr &I : MRI->use_nodbg_instructions(DefReg)) {
1668     Users.push_back(&I);
1669   }
1670   if (Users.empty())
1671     return false;
1672 
1673   // Check that all uses a copy to an agpr or a reg_sequence producing an agpr.
1674   while (!Users.empty()) {
1675     const MachineInstr *I = Users.pop_back_val();
1676     if (!I->isCopy() && !I->isRegSequence())
1677       return false;
1678     Register DstReg = I->getOperand(0).getReg();
1679     if (TRI->isAGPR(*MRI, DstReg))
1680       continue;
1681     MoveRegs.push_back(DstReg);
1682     for (const MachineInstr &U : MRI->use_nodbg_instructions(DstReg)) {
1683       Users.push_back(&U);
1684     }
1685   }
1686 
1687   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
1688   MRI->setRegClass(DefReg, TRI->getEquivalentAGPRClass(RC));
1689   if (!TII->isOperandLegal(MI, 0, &Def)) {
1690     MRI->setRegClass(DefReg, RC);
1691     return false;
1692   }
1693 
1694   while (!MoveRegs.empty()) {
1695     Register Reg = MoveRegs.pop_back_val();
1696     MRI->setRegClass(Reg, TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg)));
1697   }
1698 
1699   LLVM_DEBUG(dbgs() << "Folded " << MI);
1700 
1701   return true;
1702 }
1703 
1704 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
1705   if (skipFunction(MF.getFunction()))
1706     return false;
1707 
1708   MRI = &MF.getRegInfo();
1709   ST = &MF.getSubtarget<GCNSubtarget>();
1710   TII = ST->getInstrInfo();
1711   TRI = &TII->getRegisterInfo();
1712   MFI = MF.getInfo<SIMachineFunctionInfo>();
1713 
1714   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
1715   // correctly handle signed zeros.
1716   //
1717   // FIXME: Also need to check strictfp
1718   bool IsIEEEMode = MFI->getMode().IEEE;
1719   bool HasNSZ = MFI->hasNoSignedZerosFPMath();
1720 
1721   for (MachineBasicBlock *MBB : depth_first(&MF)) {
1722     MachineOperand *CurrentKnownM0Val = nullptr;
1723     for (auto &MI : make_early_inc_range(*MBB)) {
1724       tryFoldCndMask(TII, &MI);
1725 
1726       if (MI.isRegSequence() && tryFoldRegSequence(MI))
1727         continue;
1728 
1729       if (MI.isPHI() && tryFoldLCSSAPhi(MI))
1730         continue;
1731 
1732       if (MI.mayLoad() && tryFoldLoad(MI))
1733         continue;
1734 
1735       if (!TII->isFoldableCopy(MI)) {
1736         // Saw an unknown clobber of m0, so we no longer know what it is.
1737         if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
1738           CurrentKnownM0Val = nullptr;
1739 
1740         // TODO: Omod might be OK if there is NSZ only on the source
1741         // instruction, and not the omod multiply.
1742         if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
1743             !tryFoldOMod(MI))
1744           tryFoldClamp(MI);
1745 
1746         continue;
1747       }
1748 
1749       // Specially track simple redefs of m0 to the same value in a block, so we
1750       // can erase the later ones.
1751       if (MI.getOperand(0).getReg() == AMDGPU::M0) {
1752         MachineOperand &NewM0Val = MI.getOperand(1);
1753         if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) {
1754           MI.eraseFromParent();
1755           continue;
1756         }
1757 
1758         // We aren't tracking other physical registers
1759         CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical()) ?
1760           nullptr : &NewM0Val;
1761         continue;
1762       }
1763 
1764       MachineOperand &OpToFold = MI.getOperand(1);
1765       bool FoldingImm =
1766           OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1767 
1768       // FIXME: We could also be folding things like TargetIndexes.
1769       if (!FoldingImm && !OpToFold.isReg())
1770         continue;
1771 
1772       if (OpToFold.isReg() && !OpToFold.getReg().isVirtual())
1773         continue;
1774 
1775       // Prevent folding operands backwards in the function. For example,
1776       // the COPY opcode must not be replaced by 1 in this example:
1777       //
1778       //    %3 = COPY %vgpr0; VGPR_32:%3
1779       //    ...
1780       //    %vgpr0 = V_MOV_B32_e32 1, implicit %exec
1781       MachineOperand &Dst = MI.getOperand(0);
1782       if (Dst.isReg() && !Dst.getReg().isVirtual())
1783         continue;
1784 
1785       foldInstOperand(MI, OpToFold);
1786     }
1787   }
1788   return true;
1789 }
1790