xref: /llvm-project/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp (revision eb522e68bc8ee92d9ee38aced7719e3a1789b631)
1 //===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 /// \file
9 //===----------------------------------------------------------------------===//
10 //
11 
12 #include "AMDGPU.h"
13 #include "AMDGPUSubtarget.h"
14 #include "SIInstrInfo.h"
15 #include "SIMachineFunctionInfo.h"
16 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetMachine.h"
23 
24 #define DEBUG_TYPE "si-fold-operands"
25 using namespace llvm;
26 
27 namespace {
28 
29 struct FoldCandidate {
30   MachineInstr *UseMI;
31   union {
32     MachineOperand *OpToFold;
33     uint64_t ImmToFold;
34     int FrameIndexToFold;
35   };
36   unsigned char UseOpNo;
37   MachineOperand::MachineOperandType Kind;
38 
39   FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp) :
40     UseMI(MI), OpToFold(nullptr), UseOpNo(OpNo), Kind(FoldOp->getType()) {
41     if (FoldOp->isImm()) {
42       ImmToFold = FoldOp->getImm();
43     } else if (FoldOp->isFI()) {
44       FrameIndexToFold = FoldOp->getIndex();
45     } else {
46       assert(FoldOp->isReg());
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 
64 class SIFoldOperands : public MachineFunctionPass {
65 public:
66   static char ID;
67   MachineRegisterInfo *MRI;
68   const SIInstrInfo *TII;
69   const SIRegisterInfo *TRI;
70   const SISubtarget *ST;
71 
72   void foldOperand(MachineOperand &OpToFold,
73                    MachineInstr *UseMI,
74                    unsigned UseOpIdx,
75                    SmallVectorImpl<FoldCandidate> &FoldList,
76                    SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
77 
78   void foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
79 
80   const MachineOperand *isClamp(const MachineInstr &MI) const;
81   bool tryFoldClamp(MachineInstr &MI);
82 
83   std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
84   bool tryFoldOMod(MachineInstr &MI);
85 
86 public:
87   SIFoldOperands() : MachineFunctionPass(ID) {
88     initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry());
89   }
90 
91   bool runOnMachineFunction(MachineFunction &MF) override;
92 
93   StringRef getPassName() const override { return "SI Fold Operands"; }
94 
95   void getAnalysisUsage(AnalysisUsage &AU) const override {
96     AU.setPreservesCFG();
97     MachineFunctionPass::getAnalysisUsage(AU);
98   }
99 };
100 
101 } // End anonymous namespace.
102 
103 INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE,
104                 "SI Fold Operands", false, false)
105 
106 char SIFoldOperands::ID = 0;
107 
108 char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
109 
110 // Wrapper around isInlineConstant that understands special cases when
111 // instruction types are replaced during operand folding.
112 static bool isInlineConstantIfFolded(const SIInstrInfo *TII,
113                                      const MachineInstr &UseMI,
114                                      unsigned OpNo,
115                                      const MachineOperand &OpToFold) {
116   if (TII->isInlineConstant(UseMI, OpNo, OpToFold))
117     return true;
118 
119   unsigned Opc = UseMI.getOpcode();
120   switch (Opc) {
121   case AMDGPU::V_MAC_F32_e64:
122   case AMDGPU::V_MAC_F16_e64: {
123     // Special case for mac. Since this is replaced with mad when folded into
124     // src2, we need to check the legality for the final instruction.
125     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
126     if (static_cast<int>(OpNo) == Src2Idx) {
127       bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
128       const MCInstrDesc &MadDesc
129         = TII->get(IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
130       return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType);
131     }
132   }
133   default:
134     return false;
135   }
136 }
137 
138 FunctionPass *llvm::createSIFoldOperandsPass() {
139   return new SIFoldOperands();
140 }
141 
142 static bool isFoldableCopy(const MachineInstr &MI) {
143   switch (MI.getOpcode()) {
144   case AMDGPU::V_MOV_B32_e32:
145   case AMDGPU::V_MOV_B32_e64:
146   case AMDGPU::V_MOV_B64_PSEUDO: {
147     // If there are additional implicit register operands, this may be used for
148     // register indexing so the source register operand isn't simply copied.
149     unsigned NumOps = MI.getDesc().getNumOperands() +
150       MI.getDesc().getNumImplicitUses();
151 
152     return MI.getNumOperands() == NumOps;
153   }
154   case AMDGPU::S_MOV_B32:
155   case AMDGPU::S_MOV_B64:
156   case AMDGPU::COPY:
157     return true;
158   default:
159     return false;
160   }
161 }
162 
163 static bool updateOperand(FoldCandidate &Fold,
164                           const TargetRegisterInfo &TRI) {
165   MachineInstr *MI = Fold.UseMI;
166   MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
167   assert(Old.isReg());
168 
169   if (Fold.isImm()) {
170     Old.ChangeToImmediate(Fold.ImmToFold);
171     return true;
172   }
173 
174   if (Fold.isFI()) {
175     Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
176     return true;
177   }
178 
179   MachineOperand *New = Fold.OpToFold;
180   if (TargetRegisterInfo::isVirtualRegister(Old.getReg()) &&
181       TargetRegisterInfo::isVirtualRegister(New->getReg())) {
182     Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
183     return true;
184   }
185 
186   // FIXME: Handle physical registers.
187 
188   return false;
189 }
190 
191 static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
192                               const MachineInstr *MI) {
193   for (auto Candidate : FoldList) {
194     if (Candidate.UseMI == MI)
195       return true;
196   }
197   return false;
198 }
199 
200 static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
201                              MachineInstr *MI, unsigned OpNo,
202                              MachineOperand *OpToFold,
203                              const SIInstrInfo *TII) {
204   if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
205 
206     // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
207     unsigned Opc = MI->getOpcode();
208     if ((Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64) &&
209         (int)OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)) {
210       bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
211 
212       // Check if changing this to a v_mad_{f16, f32} instruction will allow us
213       // to fold the operand.
214       MI->setDesc(TII->get(IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16));
215       bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII);
216       if (FoldAsMAD) {
217         MI->untieRegOperand(OpNo);
218         return true;
219       }
220       MI->setDesc(TII->get(Opc));
221     }
222 
223     // Special case for s_setreg_b32
224     if (Opc == AMDGPU::S_SETREG_B32 && OpToFold->isImm()) {
225       MI->setDesc(TII->get(AMDGPU::S_SETREG_IMM32_B32));
226       FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
227       return true;
228     }
229 
230     // If we are already folding into another operand of MI, then
231     // we can't commute the instruction, otherwise we risk making the
232     // other fold illegal.
233     if (isUseMIInFoldList(FoldList, MI))
234       return false;
235 
236     // Operand is not legal, so try to commute the instruction to
237     // see if this makes it possible to fold.
238     unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
239     unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
240     bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
241 
242     if (CanCommute) {
243       if (CommuteIdx0 == OpNo)
244         OpNo = CommuteIdx1;
245       else if (CommuteIdx1 == OpNo)
246         OpNo = CommuteIdx0;
247     }
248 
249     // One of operands might be an Imm operand, and OpNo may refer to it after
250     // the call of commuteInstruction() below. Such situations are avoided
251     // here explicitly as OpNo must be a register operand to be a candidate
252     // for memory folding.
253     if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
254                        !MI->getOperand(CommuteIdx1).isReg()))
255       return false;
256 
257     if (!CanCommute ||
258         !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
259       return false;
260 
261     if (!TII->isOperandLegal(*MI, OpNo, OpToFold))
262       return false;
263   }
264 
265   FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
266   return true;
267 }
268 
269 // If the use operand doesn't care about the value, this may be an operand only
270 // used for register indexing, in which case it is unsafe to fold.
271 static bool isUseSafeToFold(const MachineInstr &MI,
272                             const MachineOperand &UseMO) {
273   return !UseMO.isUndef();
274   //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
275 }
276 
277 void SIFoldOperands::foldOperand(
278   MachineOperand &OpToFold,
279   MachineInstr *UseMI,
280   unsigned UseOpIdx,
281   SmallVectorImpl<FoldCandidate> &FoldList,
282   SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
283   const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
284 
285   if (!isUseSafeToFold(*UseMI, UseOp))
286     return;
287 
288   // FIXME: Fold operands with subregs.
289   if (UseOp.isReg() && OpToFold.isReg()) {
290     if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
291       return;
292 
293     // Don't fold subregister extracts into tied operands, only if it is a full
294     // copy since a subregister use tied to a full register def doesn't really
295     // make sense. e.g. don't fold:
296     //
297     // %vreg1 = COPY %vreg0:sub1
298     // %vreg2<tied3> = V_MAC_{F16, F32} %vreg3, %vreg4, %vreg1<tied0>
299     //
300     //  into
301     // %vreg2<tied3> = V_MAC_{F16, F32} %vreg3, %vreg4, %vreg0:sub1<tied0>
302     if (UseOp.isTied() && OpToFold.getSubReg() != AMDGPU::NoSubRegister)
303       return;
304   }
305 
306   // Special case for REG_SEQUENCE: We can't fold literals into
307   // REG_SEQUENCE instructions, so we have to fold them into the
308   // uses of REG_SEQUENCE.
309   if (UseMI->isRegSequence()) {
310     unsigned RegSeqDstReg = UseMI->getOperand(0).getReg();
311     unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
312 
313     for (MachineRegisterInfo::use_iterator
314            RSUse = MRI->use_begin(RegSeqDstReg), RSE = MRI->use_end();
315          RSUse != RSE; ++RSUse) {
316 
317       MachineInstr *RSUseMI = RSUse->getParent();
318       if (RSUse->getSubReg() != RegSeqDstSubReg)
319         continue;
320 
321       foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList,
322                   CopiesToReplace);
323     }
324 
325     return;
326   }
327 
328 
329   bool FoldingImm = OpToFold.isImm();
330 
331   // In order to fold immediates into copies, we need to change the
332   // copy to a MOV.
333   if (FoldingImm && UseMI->isCopy()) {
334     unsigned DestReg = UseMI->getOperand(0).getReg();
335     const TargetRegisterClass *DestRC
336       = TargetRegisterInfo::isVirtualRegister(DestReg) ?
337       MRI->getRegClass(DestReg) :
338       TRI->getPhysRegClass(DestReg);
339 
340     unsigned MovOp = TII->getMovOpcode(DestRC);
341     if (MovOp == AMDGPU::COPY)
342       return;
343 
344     UseMI->setDesc(TII->get(MovOp));
345     CopiesToReplace.push_back(UseMI);
346   } else {
347     const MCInstrDesc &UseDesc = UseMI->getDesc();
348 
349     // Don't fold into target independent nodes.  Target independent opcodes
350     // don't have defined register classes.
351     if (UseDesc.isVariadic() ||
352         UseDesc.OpInfo[UseOpIdx].RegClass == -1)
353       return;
354   }
355 
356   if (!FoldingImm) {
357     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
358 
359     // FIXME: We could try to change the instruction from 64-bit to 32-bit
360     // to enable more folding opportunites.  The shrink operands pass
361     // already does this.
362     return;
363   }
364 
365 
366   const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
367   const TargetRegisterClass *FoldRC =
368     TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
369 
370 
371   // Split 64-bit constants into 32-bits for folding.
372   if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
373     unsigned UseReg = UseOp.getReg();
374     const TargetRegisterClass *UseRC
375       = TargetRegisterInfo::isVirtualRegister(UseReg) ?
376       MRI->getRegClass(UseReg) :
377       TRI->getPhysRegClass(UseReg);
378 
379     if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
380       return;
381 
382     APInt Imm(64, OpToFold.getImm());
383     if (UseOp.getSubReg() == AMDGPU::sub0) {
384       Imm = Imm.getLoBits(32);
385     } else {
386       assert(UseOp.getSubReg() == AMDGPU::sub1);
387       Imm = Imm.getHiBits(32);
388     }
389 
390     MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
391     tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
392     return;
393   }
394 
395 
396 
397   tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
398 }
399 
400 static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
401                                   uint32_t LHS, uint32_t RHS) {
402   switch (Opcode) {
403   case AMDGPU::V_AND_B32_e64:
404   case AMDGPU::V_AND_B32_e32:
405   case AMDGPU::S_AND_B32:
406     Result = LHS & RHS;
407     return true;
408   case AMDGPU::V_OR_B32_e64:
409   case AMDGPU::V_OR_B32_e32:
410   case AMDGPU::S_OR_B32:
411     Result = LHS | RHS;
412     return true;
413   case AMDGPU::V_XOR_B32_e64:
414   case AMDGPU::V_XOR_B32_e32:
415   case AMDGPU::S_XOR_B32:
416     Result = LHS ^ RHS;
417     return true;
418   case AMDGPU::V_LSHL_B32_e64:
419   case AMDGPU::V_LSHL_B32_e32:
420   case AMDGPU::S_LSHL_B32:
421     // The instruction ignores the high bits for out of bounds shifts.
422     Result = LHS << (RHS & 31);
423     return true;
424   case AMDGPU::V_LSHLREV_B32_e64:
425   case AMDGPU::V_LSHLREV_B32_e32:
426     Result = RHS << (LHS & 31);
427     return true;
428   case AMDGPU::V_LSHR_B32_e64:
429   case AMDGPU::V_LSHR_B32_e32:
430   case AMDGPU::S_LSHR_B32:
431     Result = LHS >> (RHS & 31);
432     return true;
433   case AMDGPU::V_LSHRREV_B32_e64:
434   case AMDGPU::V_LSHRREV_B32_e32:
435     Result = RHS >> (LHS & 31);
436     return true;
437   case AMDGPU::V_ASHR_I32_e64:
438   case AMDGPU::V_ASHR_I32_e32:
439   case AMDGPU::S_ASHR_I32:
440     Result = static_cast<int32_t>(LHS) >> (RHS & 31);
441     return true;
442   case AMDGPU::V_ASHRREV_I32_e64:
443   case AMDGPU::V_ASHRREV_I32_e32:
444     Result = static_cast<int32_t>(RHS) >> (LHS & 31);
445     return true;
446   default:
447     return false;
448   }
449 }
450 
451 static unsigned getMovOpc(bool IsScalar) {
452   return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
453 }
454 
455 /// Remove any leftover implicit operands from mutating the instruction. e.g.
456 /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
457 /// anymore.
458 static void stripExtraCopyOperands(MachineInstr &MI) {
459   const MCInstrDesc &Desc = MI.getDesc();
460   unsigned NumOps = Desc.getNumOperands() +
461                     Desc.getNumImplicitUses() +
462                     Desc.getNumImplicitDefs();
463 
464   for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
465     MI.RemoveOperand(I);
466 }
467 
468 static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
469   MI.setDesc(NewDesc);
470   stripExtraCopyOperands(MI);
471 }
472 
473 static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
474                                                MachineOperand &Op) {
475   if (Op.isReg()) {
476     // If this has a subregister, it obviously is a register source.
477     if (Op.getSubReg() != AMDGPU::NoSubRegister)
478       return &Op;
479 
480     MachineInstr *Def = MRI.getVRegDef(Op.getReg());
481     if (Def->isMoveImmediate()) {
482       MachineOperand &ImmSrc = Def->getOperand(1);
483       if (ImmSrc.isImm())
484         return &ImmSrc;
485     }
486   }
487 
488   return &Op;
489 }
490 
491 // Try to simplify operations with a constant that may appear after instruction
492 // selection.
493 // TODO: See if a frame index with a fixed offset can fold.
494 static bool tryConstantFoldOp(MachineRegisterInfo &MRI,
495                               const SIInstrInfo *TII,
496                               MachineInstr *MI,
497                               MachineOperand *ImmOp) {
498   unsigned Opc = MI->getOpcode();
499   if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
500       Opc == AMDGPU::S_NOT_B32) {
501     MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm());
502     mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
503     return true;
504   }
505 
506   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
507   if (Src1Idx == -1)
508     return false;
509 
510   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
511   MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
512   MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
513 
514   if (!Src0->isImm() && !Src1->isImm())
515     return false;
516 
517   // and k0, k1 -> v_mov_b32 (k0 & k1)
518   // or k0, k1 -> v_mov_b32 (k0 | k1)
519   // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
520   if (Src0->isImm() && Src1->isImm()) {
521     int32_t NewImm;
522     if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
523       return false;
524 
525     const SIRegisterInfo &TRI = TII->getRegisterInfo();
526     bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
527 
528     // Be careful to change the right operand, src0 may belong to a different
529     // instruction.
530     MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
531     MI->RemoveOperand(Src1Idx);
532     mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
533     return true;
534   }
535 
536   if (!MI->isCommutable())
537     return false;
538 
539   if (Src0->isImm() && !Src1->isImm()) {
540     std::swap(Src0, Src1);
541     std::swap(Src0Idx, Src1Idx);
542   }
543 
544   int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
545   if (Opc == AMDGPU::V_OR_B32_e64 ||
546       Opc == AMDGPU::V_OR_B32_e32 ||
547       Opc == AMDGPU::S_OR_B32) {
548     if (Src1Val == 0) {
549       // y = or x, 0 => y = copy x
550       MI->RemoveOperand(Src1Idx);
551       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
552     } else if (Src1Val == -1) {
553       // y = or x, -1 => y = v_mov_b32 -1
554       MI->RemoveOperand(Src1Idx);
555       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
556     } else
557       return false;
558 
559     return true;
560   }
561 
562   if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
563       MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
564       MI->getOpcode() == AMDGPU::S_AND_B32) {
565     if (Src1Val == 0) {
566       // y = and x, 0 => y = v_mov_b32 0
567       MI->RemoveOperand(Src0Idx);
568       mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
569     } else if (Src1Val == -1) {
570       // y = and x, -1 => y = copy x
571       MI->RemoveOperand(Src1Idx);
572       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
573       stripExtraCopyOperands(*MI);
574     } else
575       return false;
576 
577     return true;
578   }
579 
580   if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
581       MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
582       MI->getOpcode() == AMDGPU::S_XOR_B32) {
583     if (Src1Val == 0) {
584       // y = xor x, 0 => y = copy x
585       MI->RemoveOperand(Src1Idx);
586       mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
587       return true;
588     }
589   }
590 
591   return false;
592 }
593 
594 void SIFoldOperands::foldInstOperand(MachineInstr &MI,
595                                      MachineOperand &OpToFold) const {
596   // We need mutate the operands of new mov instructions to add implicit
597   // uses of EXEC, but adding them invalidates the use_iterator, so defer
598   // this.
599   SmallVector<MachineInstr *, 4> CopiesToReplace;
600   SmallVector<FoldCandidate, 4> FoldList;
601   MachineOperand &Dst = MI.getOperand(0);
602 
603   bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
604   if (FoldingImm) {
605     unsigned NumLiteralUses = 0;
606     MachineOperand *NonInlineUse = nullptr;
607     int NonInlineUseOpNo = -1;
608 
609     MachineRegisterInfo::use_iterator NextUse, NextInstUse;
610     for (MachineRegisterInfo::use_iterator
611            Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
612          Use != E; Use = NextUse) {
613       NextUse = std::next(Use);
614       MachineInstr *UseMI = Use->getParent();
615       unsigned OpNo = Use.getOperandNo();
616 
617       // Folding the immediate may reveal operations that can be constant
618       // folded or replaced with a copy. This can happen for example after
619       // frame indices are lowered to constants or from splitting 64-bit
620       // constants.
621       //
622       // We may also encounter cases where one or both operands are
623       // immediates materialized into a register, which would ordinarily not
624       // be folded due to multiple uses or operand constraints.
625 
626       if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) {
627         DEBUG(dbgs() << "Constant folded " << *UseMI <<'\n');
628 
629         // Some constant folding cases change the same immediate's use to a new
630         // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user
631         // again. The same constant folded instruction could also have a second
632         // use operand.
633         NextUse = MRI->use_begin(Dst.getReg());
634         continue;
635       }
636 
637       // Try to fold any inline immediate uses, and then only fold other
638       // constants if they have one use.
639       //
640       // The legality of the inline immediate must be checked based on the use
641       // operand, not the defining instruction, because 32-bit instructions
642       // with 32-bit inline immediate sources may be used to materialize
643       // constants used in 16-bit operands.
644       //
645       // e.g. it is unsafe to fold:
646       //  s_mov_b32 s0, 1.0    // materializes 0x3f800000
647       //  v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
648 
649       // Folding immediates with more than one use will increase program size.
650       // FIXME: This will also reduce register usage, which may be better
651       // in some cases. A better heuristic is needed.
652       if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
653         foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
654       } else {
655         if (++NumLiteralUses == 1) {
656           NonInlineUse = &*Use;
657           NonInlineUseOpNo = OpNo;
658         }
659       }
660     }
661 
662     if (NumLiteralUses == 1) {
663       MachineInstr *UseMI = NonInlineUse->getParent();
664       foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
665     }
666   } else {
667     // Folding register.
668     for (MachineRegisterInfo::use_iterator
669            Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
670          Use != E; ++Use) {
671       MachineInstr *UseMI = Use->getParent();
672 
673       foldOperand(OpToFold, UseMI, Use.getOperandNo(),
674                   FoldList, CopiesToReplace);
675     }
676   }
677 
678   MachineFunction *MF = MI.getParent()->getParent();
679   // Make sure we add EXEC uses to any new v_mov instructions created.
680   for (MachineInstr *Copy : CopiesToReplace)
681     Copy->addImplicitDefUseOperands(*MF);
682 
683   for (FoldCandidate &Fold : FoldList) {
684     if (updateOperand(Fold, *TRI)) {
685       // Clear kill flags.
686       if (Fold.isReg()) {
687         assert(Fold.OpToFold && Fold.OpToFold->isReg());
688         // FIXME: Probably shouldn't bother trying to fold if not an
689         // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
690         // copies.
691         MRI->clearKillFlags(Fold.OpToFold->getReg());
692       }
693       DEBUG(dbgs() << "Folded source from " << MI << " into OpNo " <<
694             static_cast<int>(Fold.UseOpNo) << " of " << *Fold.UseMI << '\n');
695     }
696   }
697 }
698 
699 const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
700   unsigned Op = MI.getOpcode();
701   switch (Op) {
702   case AMDGPU::V_MAX_F32_e64:
703   case AMDGPU::V_MAX_F16_e64:
704   case AMDGPU::V_MAX_F64: {
705     if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
706       return nullptr;
707 
708     // Make sure sources are identical.
709     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
710     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
711     if (!Src0->isReg() || Src0->getSubReg() != Src1->getSubReg() ||
712         Src0->getSubReg() != AMDGPU::NoSubRegister)
713       return nullptr;
714 
715     // Can't fold up if we have modifiers.
716     if (TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
717         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
718         TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
719       return nullptr;
720     return Src0;
721   }
722   default:
723     return nullptr;
724   }
725 }
726 
727 // We obviously have multiple uses in a clamp since the register is used twice
728 // in the same instruction.
729 static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) {
730   int Count = 0;
731   for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
732        I != E; ++I) {
733     if (++Count > 1)
734       return false;
735   }
736 
737   return true;
738 }
739 
740 bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
741   const MachineOperand *ClampSrc = isClamp(MI);
742   if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg()))
743     return false;
744 
745   MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
746   if (!TII->hasFPClamp(*Def))
747     return false;
748   MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
749   if (!DefClamp)
750     return false;
751 
752   DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def << '\n');
753 
754   // Clamp is applied after omod, so it is OK if omod is set.
755   DefClamp->setImm(1);
756   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
757   MI.eraseFromParent();
758   return true;
759 }
760 
761 static int getOModValue(unsigned Opc, int64_t Val) {
762   switch (Opc) {
763   case AMDGPU::V_MUL_F32_e64: {
764     switch (static_cast<uint32_t>(Val)) {
765     case 0x3f000000: // 0.5
766       return SIOutMods::DIV2;
767     case 0x40000000: // 2.0
768       return SIOutMods::MUL2;
769     case 0x40800000: // 4.0
770       return SIOutMods::MUL4;
771     default:
772       return SIOutMods::NONE;
773     }
774   }
775   case AMDGPU::V_MUL_F16_e64: {
776     switch (static_cast<uint16_t>(Val)) {
777     case 0x3800: // 0.5
778       return SIOutMods::DIV2;
779     case 0x4000: // 2.0
780       return SIOutMods::MUL2;
781     case 0x4400: // 4.0
782       return SIOutMods::MUL4;
783     default:
784       return SIOutMods::NONE;
785     }
786   }
787   default:
788     llvm_unreachable("invalid mul opcode");
789   }
790 }
791 
792 // FIXME: Does this really not support denormals with f16?
793 // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
794 // handled, so will anything other than that break?
795 std::pair<const MachineOperand *, int>
796 SIFoldOperands::isOMod(const MachineInstr &MI) const {
797   unsigned Op = MI.getOpcode();
798   switch (Op) {
799   case AMDGPU::V_MUL_F32_e64:
800   case AMDGPU::V_MUL_F16_e64: {
801     // If output denormals are enabled, omod is ignored.
802     if ((Op == AMDGPU::V_MUL_F32_e64 && ST->hasFP32Denormals()) ||
803         (Op == AMDGPU::V_MUL_F16_e64 && ST->hasFP16Denormals()))
804       return std::make_pair(nullptr, SIOutMods::NONE);
805 
806     const MachineOperand *RegOp = nullptr;
807     const MachineOperand *ImmOp = nullptr;
808     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
809     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
810     if (Src0->isImm()) {
811       ImmOp = Src0;
812       RegOp = Src1;
813     } else if (Src1->isImm()) {
814       ImmOp = Src1;
815       RegOp = Src0;
816     } else
817       return std::make_pair(nullptr, SIOutMods::NONE);
818 
819     int OMod = getOModValue(Op, ImmOp->getImm());
820     if (OMod == SIOutMods::NONE ||
821         TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
822         TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
823         TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
824         TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
825       return std::make_pair(nullptr, SIOutMods::NONE);
826 
827     return std::make_pair(RegOp, OMod);
828   }
829   case AMDGPU::V_ADD_F32_e64:
830   case AMDGPU::V_ADD_F16_e64: {
831     // If output denormals are enabled, omod is ignored.
832     if ((Op == AMDGPU::V_ADD_F32_e64 && ST->hasFP32Denormals()) ||
833         (Op == AMDGPU::V_ADD_F16_e64 && ST->hasFP16Denormals()))
834       return std::make_pair(nullptr, SIOutMods::NONE);
835 
836     // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
837     const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
838     const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
839 
840     if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
841         Src0->getSubReg() == Src1->getSubReg() &&
842         !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
843         !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
844         !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
845         !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
846       return std::make_pair(Src0, SIOutMods::MUL2);
847 
848     return std::make_pair(nullptr, SIOutMods::NONE);
849   }
850   default:
851     return std::make_pair(nullptr, SIOutMods::NONE);
852   }
853 }
854 
855 // FIXME: Does this need to check IEEE bit on function?
856 bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
857   const MachineOperand *RegOp;
858   int OMod;
859   std::tie(RegOp, OMod) = isOMod(MI);
860   if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
861       RegOp->getSubReg() != AMDGPU::NoSubRegister ||
862       !hasOneNonDBGUseInst(*MRI, RegOp->getReg()))
863     return false;
864 
865   MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
866   MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
867   if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
868     return false;
869 
870   // Clamp is applied after omod. If the source already has clamp set, don't
871   // fold it.
872   if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
873     return false;
874 
875   DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def << '\n');
876 
877   DefOMod->setImm(OMod);
878   MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
879   MI.eraseFromParent();
880   return true;
881 }
882 
883 bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
884   if (skipFunction(*MF.getFunction()))
885     return false;
886 
887   MRI = &MF.getRegInfo();
888   ST = &MF.getSubtarget<SISubtarget>();
889   TII = ST->getInstrInfo();
890   TRI = &TII->getRegisterInfo();
891 
892   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
893 
894   // omod is ignored by hardware if IEEE bit is enabled. omod also does not
895   // correctly handle signed zeros.
896   //
897   // TODO: Check nsz on instructions when fast math flags are preserved to MI
898   // level.
899   bool IsIEEEMode = ST->enableIEEEBit(MF) || !MFI->hasNoSignedZerosFPMath();
900 
901   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
902        BI != BE; ++BI) {
903 
904     MachineBasicBlock &MBB = *BI;
905     MachineBasicBlock::iterator I, Next;
906     for (I = MBB.begin(); I != MBB.end(); I = Next) {
907       Next = std::next(I);
908       MachineInstr &MI = *I;
909 
910       if (!isFoldableCopy(MI)) {
911         if (IsIEEEMode || !tryFoldOMod(MI))
912           tryFoldClamp(MI);
913         continue;
914       }
915 
916       MachineOperand &OpToFold = MI.getOperand(1);
917       bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
918 
919       // FIXME: We could also be folding things like TargetIndexes.
920       if (!FoldingImm && !OpToFold.isReg())
921         continue;
922 
923       if (OpToFold.isReg() &&
924           !TargetRegisterInfo::isVirtualRegister(OpToFold.getReg()))
925         continue;
926 
927       // Prevent folding operands backwards in the function. For example,
928       // the COPY opcode must not be replaced by 1 in this example:
929       //
930       //    %vreg3<def> = COPY %VGPR0; VGPR_32:%vreg3
931       //    ...
932       //    %VGPR0<def> = V_MOV_B32_e32 1, %EXEC<imp-use>
933       MachineOperand &Dst = MI.getOperand(0);
934       if (Dst.isReg() &&
935           !TargetRegisterInfo::isVirtualRegister(Dst.getReg()))
936         continue;
937 
938       foldInstOperand(MI, OpToFold);
939     }
940   }
941   return false;
942 }
943