blob: 481eb741af3510b01c16913d74a4c91375870a01 [file] [log] [blame]
Tom Stellard6596ba72014-11-21 22:06:37 +00001//===-- 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"
Matt Arsenault3cb39042017-02-27 19:35:42 +000015#include "SIMachineFunctionInfo.h"
Matt Arsenaultff3f9122017-06-20 18:56:32 +000016#include "llvm/ADT/DepthFirstIterator.h"
Matthias Braunf8422972017-12-13 02:51:04 +000017#include "llvm/CodeGen/LiveIntervals.h"
Tom Stellard6596ba72014-11-21 22:06:37 +000018#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
Tom Stellard6596ba72014-11-21 22:06:37 +000021#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000022#include "llvm/Support/raw_ostream.h"
Tom Stellard6596ba72014-11-21 22:06:37 +000023#include "llvm/Target/TargetMachine.h"
24
25#define DEBUG_TYPE "si-fold-operands"
26using namespace llvm;
27
28namespace {
29
Tom Stellardbb763e62015-01-07 17:42:16 +000030struct FoldCandidate {
31 MachineInstr *UseMI;
Matt Arsenault2bc198a2016-09-14 15:51:33 +000032 union {
33 MachineOperand *OpToFold;
34 uint64_t ImmToFold;
35 int FrameIndexToFold;
36 };
37 unsigned char UseOpNo;
38 MachineOperand::MachineOperandType Kind;
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +000039 bool Commuted;
Tom Stellardbb763e62015-01-07 17:42:16 +000040
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +000041 FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp,
42 bool Commuted_ = false) :
43 UseMI(MI), OpToFold(nullptr), UseOpNo(OpNo), Kind(FoldOp->getType()),
44 Commuted(Commuted_) {
Tom Stellard05992972015-01-07 22:44:19 +000045 if (FoldOp->isImm()) {
Tom Stellard05992972015-01-07 22:44:19 +000046 ImmToFold = FoldOp->getImm();
Matt Arsenault2bc198a2016-09-14 15:51:33 +000047 } else if (FoldOp->isFI()) {
48 FrameIndexToFold = FoldOp->getIndex();
Tom Stellard05992972015-01-07 22:44:19 +000049 } else {
50 assert(FoldOp->isReg());
51 OpToFold = FoldOp;
52 }
53 }
Tom Stellardbb763e62015-01-07 17:42:16 +000054
Matt Arsenault2bc198a2016-09-14 15:51:33 +000055 bool isFI() const {
56 return Kind == MachineOperand::MO_FrameIndex;
57 }
58
Tom Stellardbb763e62015-01-07 17:42:16 +000059 bool isImm() const {
Matt Arsenault2bc198a2016-09-14 15:51:33 +000060 return Kind == MachineOperand::MO_Immediate;
61 }
62
63 bool isReg() const {
64 return Kind == MachineOperand::MO_Register;
Tom Stellardbb763e62015-01-07 17:42:16 +000065 }
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +000066
67 bool isCommuted() const {
68 return Commuted;
69 }
Tom Stellardbb763e62015-01-07 17:42:16 +000070};
71
Matt Arsenault51818c12017-01-10 23:32:04 +000072class SIFoldOperands : public MachineFunctionPass {
73public:
74 static char ID;
75 MachineRegisterInfo *MRI;
76 const SIInstrInfo *TII;
77 const SIRegisterInfo *TRI;
Matt Arsenaultd5c65152017-02-22 23:27:53 +000078 const SISubtarget *ST;
Matt Arsenault51818c12017-01-10 23:32:04 +000079
80 void foldOperand(MachineOperand &OpToFold,
81 MachineInstr *UseMI,
82 unsigned UseOpIdx,
83 SmallVectorImpl<FoldCandidate> &FoldList,
84 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
85
86 void foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const;
87
Matt Arsenaultd5c65152017-02-22 23:27:53 +000088 const MachineOperand *isClamp(const MachineInstr &MI) const;
89 bool tryFoldClamp(MachineInstr &MI);
90
Matt Arsenault3cb39042017-02-27 19:35:42 +000091 std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
92 bool tryFoldOMod(MachineInstr &MI);
93
Matt Arsenault51818c12017-01-10 23:32:04 +000094public:
95 SIFoldOperands() : MachineFunctionPass(ID) {
96 initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry());
97 }
98
99 bool runOnMachineFunction(MachineFunction &MF) override;
100
101 StringRef getPassName() const override { return "SI Fold Operands"; }
102
103 void getAnalysisUsage(AnalysisUsage &AU) const override {
104 AU.setPreservesCFG();
105 MachineFunctionPass::getAnalysisUsage(AU);
106 }
107};
108
Tom Stellard6596ba72014-11-21 22:06:37 +0000109} // End anonymous namespace.
110
Matt Arsenault427c5482016-02-11 06:15:34 +0000111INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE,
112 "SI Fold Operands", false, false)
Tom Stellard6596ba72014-11-21 22:06:37 +0000113
114char SIFoldOperands::ID = 0;
115
116char &llvm::SIFoldOperandsID = SIFoldOperands::ID;
117
Matt Arsenault69e30012017-01-11 22:00:02 +0000118// Wrapper around isInlineConstant that understands special cases when
119// instruction types are replaced during operand folding.
120static bool isInlineConstantIfFolded(const SIInstrInfo *TII,
121 const MachineInstr &UseMI,
122 unsigned OpNo,
123 const MachineOperand &OpToFold) {
124 if (TII->isInlineConstant(UseMI, OpNo, OpToFold))
125 return true;
126
127 unsigned Opc = UseMI.getOpcode();
128 switch (Opc) {
129 case AMDGPU::V_MAC_F32_e64:
130 case AMDGPU::V_MAC_F16_e64: {
131 // Special case for mac. Since this is replaced with mad when folded into
132 // src2, we need to check the legality for the final instruction.
133 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
134 if (static_cast<int>(OpNo) == Src2Idx) {
135 bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
136 const MCInstrDesc &MadDesc
137 = TII->get(IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16);
138 return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType);
139 }
Simon Pilgrim0f5b3502017-07-07 10:18:57 +0000140 return false;
Matt Arsenault69e30012017-01-11 22:00:02 +0000141 }
142 default:
143 return false;
144 }
145}
146
Tom Stellard6596ba72014-11-21 22:06:37 +0000147FunctionPass *llvm::createSIFoldOperandsPass() {
148 return new SIFoldOperands();
149}
150
Tom Stellardbb763e62015-01-07 17:42:16 +0000151static bool updateOperand(FoldCandidate &Fold,
Tom Stellard6596ba72014-11-21 22:06:37 +0000152 const TargetRegisterInfo &TRI) {
Tom Stellardbb763e62015-01-07 17:42:16 +0000153 MachineInstr *MI = Fold.UseMI;
154 MachineOperand &Old = MI->getOperand(Fold.UseOpNo);
Tom Stellard6596ba72014-11-21 22:06:37 +0000155 assert(Old.isReg());
156
Tom Stellardbb763e62015-01-07 17:42:16 +0000157 if (Fold.isImm()) {
Stanislav Mekhanoshin8b20b7d2018-04-17 23:09:05 +0000158 if (MI->getDesc().TSFlags & SIInstrFlags::IsPacked) {
Stanislav Mekhanoshin160f8572018-04-19 21:16:50 +0000159 // Set op_sel/op_sel_hi on this operand or bail out if op_sel is
160 // already set.
Stanislav Mekhanoshin8b20b7d2018-04-17 23:09:05 +0000161 unsigned Opcode = MI->getOpcode();
162 int OpNo = MI->getOperandNo(&Old);
163 int ModIdx = -1;
164 if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0))
165 ModIdx = AMDGPU::OpName::src0_modifiers;
166 else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1))
167 ModIdx = AMDGPU::OpName::src1_modifiers;
168 else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2))
169 ModIdx = AMDGPU::OpName::src2_modifiers;
170 assert(ModIdx != -1);
171 ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModIdx);
172 MachineOperand &Mod = MI->getOperand(ModIdx);
173 unsigned Val = Mod.getImm();
174 if ((Val & SISrcMods::OP_SEL_0) || !(Val & SISrcMods::OP_SEL_1))
175 return false;
Stanislav Mekhanoshin160f8572018-04-19 21:16:50 +0000176 // If upper part is all zero we do not need op_sel_hi.
177 if (!isUInt<16>(Fold.ImmToFold)) {
178 if (!(Fold.ImmToFold & 0xffff)) {
179 Mod.setImm(Mod.getImm() | SISrcMods::OP_SEL_0);
180 Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
Stanislav Mekhanoshina4bfb3c2018-04-24 18:17:55 +0000181 Old.ChangeToImmediate((Fold.ImmToFold >> 16) & 0xffff);
Stanislav Mekhanoshin160f8572018-04-19 21:16:50 +0000182 return true;
183 }
184 Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1);
185 }
Stanislav Mekhanoshin8b20b7d2018-04-17 23:09:05 +0000186 }
Tom Stellardbb763e62015-01-07 17:42:16 +0000187 Old.ChangeToImmediate(Fold.ImmToFold);
Tom Stellard6596ba72014-11-21 22:06:37 +0000188 return true;
189 }
190
Matt Arsenault2bc198a2016-09-14 15:51:33 +0000191 if (Fold.isFI()) {
192 Old.ChangeToFrameIndex(Fold.FrameIndexToFold);
193 return true;
194 }
195
Tom Stellardbb763e62015-01-07 17:42:16 +0000196 MachineOperand *New = Fold.OpToFold;
197 if (TargetRegisterInfo::isVirtualRegister(Old.getReg()) &&
198 TargetRegisterInfo::isVirtualRegister(New->getReg())) {
199 Old.substVirtReg(New->getReg(), New->getSubReg(), TRI);
Matt Arsenault76858f52017-06-20 18:41:31 +0000200
201 Old.setIsUndef(New->isUndef());
Tom Stellard6596ba72014-11-21 22:06:37 +0000202 return true;
203 }
204
Tom Stellard6596ba72014-11-21 22:06:37 +0000205 // FIXME: Handle physical registers.
206
207 return false;
208}
209
Matt Arsenault51818c12017-01-10 23:32:04 +0000210static bool isUseMIInFoldList(ArrayRef<FoldCandidate> FoldList,
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000211 const MachineInstr *MI) {
212 for (auto Candidate : FoldList) {
213 if (Candidate.UseMI == MI)
214 return true;
215 }
216 return false;
217}
218
Matt Arsenault51818c12017-01-10 23:32:04 +0000219static bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
Tom Stellard05992972015-01-07 22:44:19 +0000220 MachineInstr *MI, unsigned OpNo,
221 MachineOperand *OpToFold,
222 const SIInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000223 if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000224
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000225 // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000226 unsigned Opc = MI->getOpcode();
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000227 if ((Opc == AMDGPU::V_MAC_F32_e64 || Opc == AMDGPU::V_MAC_F16_e64) &&
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000228 (int)OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)) {
Matt Arsenault69e30012017-01-11 22:00:02 +0000229 bool IsF32 = Opc == AMDGPU::V_MAC_F32_e64;
Konstantin Zhuravlyovf86e4b72016-11-13 07:01:11 +0000230
231 // Check if changing this to a v_mad_{f16, f32} instruction will allow us
232 // to fold the operand.
233 MI->setDesc(TII->get(IsF32 ? AMDGPU::V_MAD_F32 : AMDGPU::V_MAD_F16));
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000234 bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII);
235 if (FoldAsMAD) {
236 MI->untieRegOperand(OpNo);
237 return true;
238 }
239 MI->setDesc(TII->get(Opc));
240 }
241
Tom Stellard8485fa02016-12-07 02:42:15 +0000242 // Special case for s_setreg_b32
243 if (Opc == AMDGPU::S_SETREG_B32 && OpToFold->isImm()) {
244 MI->setDesc(TII->get(AMDGPU::S_SETREG_IMM32_B32));
245 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
246 return true;
247 }
248
Tom Stellarddb5a11f2015-07-13 15:47:57 +0000249 // If we are already folding into another operand of MI, then
250 // we can't commute the instruction, otherwise we risk making the
251 // other fold illegal.
252 if (isUseMIInFoldList(FoldList, MI))
253 return false;
254
Tom Stellard05992972015-01-07 22:44:19 +0000255 // Operand is not legal, so try to commute the instruction to
256 // see if this makes it possible to fold.
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000257 unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex;
258 unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000259 bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1);
Tom Stellard05992972015-01-07 22:44:19 +0000260
261 if (CanCommute) {
262 if (CommuteIdx0 == OpNo)
263 OpNo = CommuteIdx1;
264 else if (CommuteIdx1 == OpNo)
265 OpNo = CommuteIdx0;
266 }
267
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000268 // One of operands might be an Imm operand, and OpNo may refer to it after
269 // the call of commuteInstruction() below. Such situations are avoided
270 // here explicitly as OpNo must be a register operand to be a candidate
271 // for memory folding.
272 if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() ||
273 !MI->getOperand(CommuteIdx1).isReg()))
274 return false;
275
276 if (!CanCommute ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000277 !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1))
Tom Stellard05992972015-01-07 22:44:19 +0000278 return false;
279
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +0000280 if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) {
281 TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1);
Tom Stellard05992972015-01-07 22:44:19 +0000282 return false;
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +0000283 }
284
285 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold, true));
286 return true;
Tom Stellard05992972015-01-07 22:44:19 +0000287 }
288
289 FoldList.push_back(FoldCandidate(MI, OpNo, OpToFold));
290 return true;
291}
292
Matt Arsenault5e63a042016-10-06 18:12:13 +0000293// If the use operand doesn't care about the value, this may be an operand only
294// used for register indexing, in which case it is unsafe to fold.
Stanislav Mekhanoshin56ea4882017-05-30 16:49:24 +0000295static bool isUseSafeToFold(const SIInstrInfo *TII,
296 const MachineInstr &MI,
Matt Arsenault5e63a042016-10-06 18:12:13 +0000297 const MachineOperand &UseMO) {
Stanislav Mekhanoshin56ea4882017-05-30 16:49:24 +0000298 return !UseMO.isUndef() && !TII->isSDWA(MI);
Matt Arsenault5e63a042016-10-06 18:12:13 +0000299 //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg());
300}
301
Matt Arsenault51818c12017-01-10 23:32:04 +0000302void SIFoldOperands::foldOperand(
303 MachineOperand &OpToFold,
304 MachineInstr *UseMI,
305 unsigned UseOpIdx,
306 SmallVectorImpl<FoldCandidate> &FoldList,
307 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000308 const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
309
Stanislav Mekhanoshin56ea4882017-05-30 16:49:24 +0000310 if (!isUseSafeToFold(TII, *UseMI, UseOp))
Matt Arsenault5e63a042016-10-06 18:12:13 +0000311 return;
312
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000313 // FIXME: Fold operands with subregs.
Matt Arsenault3661e902016-08-15 16:18:36 +0000314 if (UseOp.isReg() && OpToFold.isReg()) {
315 if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister)
316 return;
317
318 // Don't fold subregister extracts into tied operands, only if it is a full
319 // copy since a subregister use tied to a full register def doesn't really
320 // make sense. e.g. don't fold:
321 //
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +0000322 // %1 = COPY %0:sub1
323 // %2<tied3> = V_MAC_{F16, F32} %3, %4, %1<tied0>
Matt Arsenault3661e902016-08-15 16:18:36 +0000324 //
325 // into
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +0000326 // %2<tied3> = V_MAC_{F16, F32} %3, %4, %0:sub1<tied0>
Matt Arsenault3661e902016-08-15 16:18:36 +0000327 if (UseOp.isTied() && OpToFold.getSubReg() != AMDGPU::NoSubRegister)
328 return;
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000329 }
330
Tom Stellard9a197672015-09-09 15:43:26 +0000331 // Special case for REG_SEQUENCE: We can't fold literals into
332 // REG_SEQUENCE instructions, so we have to fold them into the
333 // uses of REG_SEQUENCE.
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000334 if (UseMI->isRegSequence()) {
Tom Stellard9a197672015-09-09 15:43:26 +0000335 unsigned RegSeqDstReg = UseMI->getOperand(0).getReg();
336 unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
337
338 for (MachineRegisterInfo::use_iterator
Matt Arsenault51818c12017-01-10 23:32:04 +0000339 RSUse = MRI->use_begin(RegSeqDstReg), RSE = MRI->use_end();
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000340 RSUse != RSE; ++RSUse) {
Tom Stellard9a197672015-09-09 15:43:26 +0000341
342 MachineInstr *RSUseMI = RSUse->getParent();
343 if (RSUse->getSubReg() != RegSeqDstSubReg)
344 continue;
345
346 foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList,
Matt Arsenault51818c12017-01-10 23:32:04 +0000347 CopiesToReplace);
Tom Stellard9a197672015-09-09 15:43:26 +0000348 }
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000349
Tom Stellard9a197672015-09-09 15:43:26 +0000350 return;
351 }
352
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000353
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000354 bool FoldingImm = OpToFold.isImm();
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000355
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000356 // In order to fold immediates into copies, we need to change the
357 // copy to a MOV.
358 if (FoldingImm && UseMI->isCopy()) {
359 unsigned DestReg = UseMI->getOperand(0).getReg();
360 const TargetRegisterClass *DestRC
361 = TargetRegisterInfo::isVirtualRegister(DestReg) ?
Matt Arsenault51818c12017-01-10 23:32:04 +0000362 MRI->getRegClass(DestReg) :
363 TRI->getPhysRegClass(DestReg);
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000364
365 unsigned MovOp = TII->getMovOpcode(DestRC);
366 if (MovOp == AMDGPU::COPY)
367 return;
368
369 UseMI->setDesc(TII->get(MovOp));
370 CopiesToReplace.push_back(UseMI);
371 } else {
372 const MCInstrDesc &UseDesc = UseMI->getDesc();
373
374 // Don't fold into target independent nodes. Target independent opcodes
375 // don't have defined register classes.
376 if (UseDesc.isVariadic() ||
Matt Arsenaultc908e3f2018-02-08 01:12:46 +0000377 UseOp.isImplicit() ||
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000378 UseDesc.OpInfo[UseOpIdx].RegClass == -1)
379 return;
380 }
381
382 if (!FoldingImm) {
383 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
384
385 // FIXME: We could try to change the instruction from 64-bit to 32-bit
386 // to enable more folding opportunites. The shrink operands pass
387 // already does this.
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000388 return;
389 }
390
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000391
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000392 const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc();
393 const TargetRegisterClass *FoldRC =
Matt Arsenault51818c12017-01-10 23:32:04 +0000394 TRI->getRegClass(FoldDesc.OpInfo[0].RegClass);
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000395
Matt Arsenault4bd72362016-12-10 00:39:12 +0000396
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000397 // Split 64-bit constants into 32-bits for folding.
398 if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) {
399 unsigned UseReg = UseOp.getReg();
400 const TargetRegisterClass *UseRC
401 = TargetRegisterInfo::isVirtualRegister(UseReg) ?
Matt Arsenault51818c12017-01-10 23:32:04 +0000402 MRI->getRegClass(UseReg) :
403 TRI->getPhysRegClass(UseReg);
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000404
405 if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64)
406 return;
407
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000408 APInt Imm(64, OpToFold.getImm());
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000409 if (UseOp.getSubReg() == AMDGPU::sub0) {
410 Imm = Imm.getLoBits(32);
411 } else {
412 assert(UseOp.getSubReg() == AMDGPU::sub1);
413 Imm = Imm.getHiBits(32);
414 }
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000415
416 MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue());
417 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII);
418 return;
Matt Arsenaulta24d84b2016-11-23 21:51:07 +0000419 }
420
Matt Arsenaulteb522e62017-02-27 22:15:25 +0000421
422
423 tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII);
Tom Stellardb8ce14c2015-08-28 23:45:19 +0000424}
425
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000426static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
Matt Arsenault51818c12017-01-10 23:32:04 +0000427 uint32_t LHS, uint32_t RHS) {
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000428 switch (Opcode) {
429 case AMDGPU::V_AND_B32_e64:
Matt Arsenault51818c12017-01-10 23:32:04 +0000430 case AMDGPU::V_AND_B32_e32:
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000431 case AMDGPU::S_AND_B32:
432 Result = LHS & RHS;
433 return true;
434 case AMDGPU::V_OR_B32_e64:
Matt Arsenault51818c12017-01-10 23:32:04 +0000435 case AMDGPU::V_OR_B32_e32:
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000436 case AMDGPU::S_OR_B32:
437 Result = LHS | RHS;
438 return true;
439 case AMDGPU::V_XOR_B32_e64:
Matt Arsenault51818c12017-01-10 23:32:04 +0000440 case AMDGPU::V_XOR_B32_e32:
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000441 case AMDGPU::S_XOR_B32:
442 Result = LHS ^ RHS;
443 return true;
Matt Arsenault51818c12017-01-10 23:32:04 +0000444 case AMDGPU::V_LSHL_B32_e64:
445 case AMDGPU::V_LSHL_B32_e32:
446 case AMDGPU::S_LSHL_B32:
447 // The instruction ignores the high bits for out of bounds shifts.
448 Result = LHS << (RHS & 31);
449 return true;
450 case AMDGPU::V_LSHLREV_B32_e64:
451 case AMDGPU::V_LSHLREV_B32_e32:
452 Result = RHS << (LHS & 31);
453 return true;
454 case AMDGPU::V_LSHR_B32_e64:
455 case AMDGPU::V_LSHR_B32_e32:
456 case AMDGPU::S_LSHR_B32:
457 Result = LHS >> (RHS & 31);
458 return true;
459 case AMDGPU::V_LSHRREV_B32_e64:
460 case AMDGPU::V_LSHRREV_B32_e32:
461 Result = RHS >> (LHS & 31);
462 return true;
463 case AMDGPU::V_ASHR_I32_e64:
464 case AMDGPU::V_ASHR_I32_e32:
465 case AMDGPU::S_ASHR_I32:
466 Result = static_cast<int32_t>(LHS) >> (RHS & 31);
467 return true;
468 case AMDGPU::V_ASHRREV_I32_e64:
469 case AMDGPU::V_ASHRREV_I32_e32:
470 Result = static_cast<int32_t>(RHS) >> (LHS & 31);
471 return true;
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000472 default:
473 return false;
474 }
475}
476
477static unsigned getMovOpc(bool IsScalar) {
478 return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
479}
480
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000481/// Remove any leftover implicit operands from mutating the instruction. e.g.
482/// if we replace an s_and_b32 with a copy, we don't need the implicit scc def
483/// anymore.
484static void stripExtraCopyOperands(MachineInstr &MI) {
485 const MCInstrDesc &Desc = MI.getDesc();
486 unsigned NumOps = Desc.getNumOperands() +
487 Desc.getNumImplicitUses() +
488 Desc.getNumImplicitDefs();
489
490 for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
491 MI.RemoveOperand(I);
492}
493
494static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
495 MI.setDesc(NewDesc);
496 stripExtraCopyOperands(MI);
497}
498
Matt Arsenault51818c12017-01-10 23:32:04 +0000499static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI,
500 MachineOperand &Op) {
501 if (Op.isReg()) {
502 // If this has a subregister, it obviously is a register source.
Matt Arsenaultcbda7ff2018-03-10 16:05:35 +0000503 if (Op.getSubReg() != AMDGPU::NoSubRegister ||
504 !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
Matt Arsenault51818c12017-01-10 23:32:04 +0000505 return &Op;
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000506
Matt Arsenault51818c12017-01-10 23:32:04 +0000507 MachineInstr *Def = MRI.getVRegDef(Op.getReg());
Matt Arsenault7f67b352017-06-20 18:28:02 +0000508 if (Def && Def->isMoveImmediate()) {
Matt Arsenault51818c12017-01-10 23:32:04 +0000509 MachineOperand &ImmSrc = Def->getOperand(1);
510 if (ImmSrc.isImm())
511 return &ImmSrc;
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000512 }
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000513 }
514
Matt Arsenault51818c12017-01-10 23:32:04 +0000515 return &Op;
516}
517
518// Try to simplify operations with a constant that may appear after instruction
519// selection.
520// TODO: See if a frame index with a fixed offset can fold.
521static bool tryConstantFoldOp(MachineRegisterInfo &MRI,
522 const SIInstrInfo *TII,
523 MachineInstr *MI,
524 MachineOperand *ImmOp) {
525 unsigned Opc = MI->getOpcode();
526 if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
527 Opc == AMDGPU::S_NOT_B32) {
528 MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm());
529 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
530 return true;
531 }
532
533 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
534 if (Src1Idx == -1)
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000535 return false;
536
537 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
Matt Arsenault51818c12017-01-10 23:32:04 +0000538 MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx));
539 MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000540
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000541 if (!Src0->isImm() && !Src1->isImm())
542 return false;
543
544 // and k0, k1 -> v_mov_b32 (k0 & k1)
545 // or k0, k1 -> v_mov_b32 (k0 | k1)
546 // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
547 if (Src0->isImm() && Src1->isImm()) {
548 int32_t NewImm;
549 if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm()))
550 return false;
551
552 const SIRegisterInfo &TRI = TII->getRegisterInfo();
553 bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg());
554
Matt Arsenault51818c12017-01-10 23:32:04 +0000555 // Be careful to change the right operand, src0 may belong to a different
556 // instruction.
557 MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000558 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000559 mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000560 return true;
561 }
562
Matt Arsenault51818c12017-01-10 23:32:04 +0000563 if (!MI->isCommutable())
564 return false;
565
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000566 if (Src0->isImm() && !Src1->isImm()) {
567 std::swap(Src0, Src1);
568 std::swap(Src0Idx, Src1Idx);
569 }
570
571 int32_t Src1Val = static_cast<int32_t>(Src1->getImm());
Matt Arsenault51818c12017-01-10 23:32:04 +0000572 if (Opc == AMDGPU::V_OR_B32_e64 ||
573 Opc == AMDGPU::V_OR_B32_e32 ||
574 Opc == AMDGPU::S_OR_B32) {
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000575 if (Src1Val == 0) {
576 // y = or x, 0 => y = copy x
577 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000578 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000579 } else if (Src1Val == -1) {
580 // y = or x, -1 => y = v_mov_b32 -1
581 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000582 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000583 } else
584 return false;
585
586 return true;
587 }
588
589 if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 ||
Matt Arsenault51818c12017-01-10 23:32:04 +0000590 MI->getOpcode() == AMDGPU::V_AND_B32_e32 ||
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000591 MI->getOpcode() == AMDGPU::S_AND_B32) {
592 if (Src1Val == 0) {
593 // y = and x, 0 => y = v_mov_b32 0
594 MI->RemoveOperand(Src0Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000595 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000596 } else if (Src1Val == -1) {
597 // y = and x, -1 => y = copy x
598 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000599 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
600 stripExtraCopyOperands(*MI);
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000601 } else
602 return false;
603
604 return true;
605 }
606
607 if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 ||
Matt Arsenault51818c12017-01-10 23:32:04 +0000608 MI->getOpcode() == AMDGPU::V_XOR_B32_e32 ||
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000609 MI->getOpcode() == AMDGPU::S_XOR_B32) {
610 if (Src1Val == 0) {
611 // y = xor x, 0 => y = copy x
612 MI->RemoveOperand(Src1Idx);
Matt Arsenaultc2ee42c2016-10-06 17:54:30 +0000613 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
Matt Arsenault51818c12017-01-10 23:32:04 +0000614 return true;
Matt Arsenaultfa5f7672016-09-14 15:19:03 +0000615 }
616 }
617
618 return false;
619}
620
Stanislav Mekhanoshin70603dc2017-03-24 18:55:20 +0000621// Try to fold an instruction into a simpler one
622static bool tryFoldInst(const SIInstrInfo *TII,
623 MachineInstr *MI) {
624 unsigned Opc = MI->getOpcode();
625
626 if (Opc == AMDGPU::V_CNDMASK_B32_e32 ||
627 Opc == AMDGPU::V_CNDMASK_B32_e64 ||
628 Opc == AMDGPU::V_CNDMASK_B64_PSEUDO) {
629 const MachineOperand *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
630 const MachineOperand *Src1 = TII->getNamedOperand(*MI, AMDGPU::OpName::src1);
631 if (Src1->isIdenticalTo(*Src0)) {
632 DEBUG(dbgs() << "Folded " << *MI << " into ");
633 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
634 if (Src2Idx != -1)
635 MI->RemoveOperand(Src2Idx);
636 MI->RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
637 mutateCopyOp(*MI, TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY
638 : getMovOpc(false)));
639 DEBUG(dbgs() << *MI << '\n');
640 return true;
641 }
642 }
643
644 return false;
645}
646
Matt Arsenault51818c12017-01-10 23:32:04 +0000647void SIFoldOperands::foldInstOperand(MachineInstr &MI,
648 MachineOperand &OpToFold) const {
649 // We need mutate the operands of new mov instructions to add implicit
650 // uses of EXEC, but adding them invalidates the use_iterator, so defer
651 // this.
652 SmallVector<MachineInstr *, 4> CopiesToReplace;
653 SmallVector<FoldCandidate, 4> FoldList;
654 MachineOperand &Dst = MI.getOperand(0);
655
656 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
657 if (FoldingImm) {
658 unsigned NumLiteralUses = 0;
659 MachineOperand *NonInlineUse = nullptr;
660 int NonInlineUseOpNo = -1;
661
Vitaly Buka74503982017-10-15 05:35:02 +0000662 MachineRegisterInfo::use_iterator NextUse;
Matt Arsenault51818c12017-01-10 23:32:04 +0000663 for (MachineRegisterInfo::use_iterator
664 Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
665 Use != E; Use = NextUse) {
666 NextUse = std::next(Use);
667 MachineInstr *UseMI = Use->getParent();
668 unsigned OpNo = Use.getOperandNo();
669
670 // Folding the immediate may reveal operations that can be constant
671 // folded or replaced with a copy. This can happen for example after
672 // frame indices are lowered to constants or from splitting 64-bit
673 // constants.
674 //
675 // We may also encounter cases where one or both operands are
676 // immediates materialized into a register, which would ordinarily not
677 // be folded due to multiple uses or operand constraints.
678
679 if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) {
680 DEBUG(dbgs() << "Constant folded " << *UseMI <<'\n');
681
682 // Some constant folding cases change the same immediate's use to a new
683 // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user
684 // again. The same constant folded instruction could also have a second
685 // use operand.
686 NextUse = MRI->use_begin(Dst.getReg());
Nicolai Haehnlea253e4c2017-07-18 14:54:41 +0000687 FoldList.clear();
Matt Arsenault51818c12017-01-10 23:32:04 +0000688 continue;
689 }
690
691 // Try to fold any inline immediate uses, and then only fold other
692 // constants if they have one use.
693 //
694 // The legality of the inline immediate must be checked based on the use
695 // operand, not the defining instruction, because 32-bit instructions
696 // with 32-bit inline immediate sources may be used to materialize
697 // constants used in 16-bit operands.
698 //
699 // e.g. it is unsafe to fold:
700 // s_mov_b32 s0, 1.0 // materializes 0x3f800000
701 // v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00
702
703 // Folding immediates with more than one use will increase program size.
704 // FIXME: This will also reduce register usage, which may be better
705 // in some cases. A better heuristic is needed.
Matt Arsenault69e30012017-01-11 22:00:02 +0000706 if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) {
Matt Arsenault51818c12017-01-10 23:32:04 +0000707 foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace);
708 } else {
709 if (++NumLiteralUses == 1) {
710 NonInlineUse = &*Use;
711 NonInlineUseOpNo = OpNo;
712 }
713 }
714 }
715
716 if (NumLiteralUses == 1) {
717 MachineInstr *UseMI = NonInlineUse->getParent();
718 foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace);
719 }
720 } else {
721 // Folding register.
722 for (MachineRegisterInfo::use_iterator
723 Use = MRI->use_begin(Dst.getReg()), E = MRI->use_end();
724 Use != E; ++Use) {
725 MachineInstr *UseMI = Use->getParent();
726
727 foldOperand(OpToFold, UseMI, Use.getOperandNo(),
728 FoldList, CopiesToReplace);
729 }
730 }
731
732 MachineFunction *MF = MI.getParent()->getParent();
733 // Make sure we add EXEC uses to any new v_mov instructions created.
734 for (MachineInstr *Copy : CopiesToReplace)
735 Copy->addImplicitDefUseOperands(*MF);
736
737 for (FoldCandidate &Fold : FoldList) {
738 if (updateOperand(Fold, *TRI)) {
739 // Clear kill flags.
740 if (Fold.isReg()) {
741 assert(Fold.OpToFold && Fold.OpToFold->isReg());
742 // FIXME: Probably shouldn't bother trying to fold if not an
743 // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
744 // copies.
745 MRI->clearKillFlags(Fold.OpToFold->getReg());
746 }
747 DEBUG(dbgs() << "Folded source from " << MI << " into OpNo " <<
748 static_cast<int>(Fold.UseOpNo) << " of " << *Fold.UseMI << '\n');
Stanislav Mekhanoshin70603dc2017-03-24 18:55:20 +0000749 tryFoldInst(TII, Fold.UseMI);
Stanislav Mekhanoshinf154b4f2017-06-03 00:41:52 +0000750 } else if (Fold.isCommuted()) {
751 // Restoring instruction's original operand order if fold has failed.
752 TII->commuteInstruction(*Fold.UseMI, false);
Matt Arsenault51818c12017-01-10 23:32:04 +0000753 }
754 }
755}
756
Matt Arsenaultf48e5c92017-10-05 00:13:20 +0000757// Clamp patterns are canonically selected to v_max_* instructions, so only
758// handle them.
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000759const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const {
760 unsigned Op = MI.getOpcode();
761 switch (Op) {
762 case AMDGPU::V_MAX_F32_e64:
Matt Arsenault79a45db2017-02-22 23:53:37 +0000763 case AMDGPU::V_MAX_F16_e64:
Matt Arsenaultab4a5cd2017-08-31 23:53:50 +0000764 case AMDGPU::V_MAX_F64:
765 case AMDGPU::V_PK_MAX_F16: {
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000766 if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
767 return nullptr;
768
769 // Make sure sources are identical.
770 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
771 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
Stanislav Mekhanoshin286a4222017-06-05 01:03:04 +0000772 if (!Src0->isReg() || !Src1->isReg() ||
Matt Arsenaultaafff872017-10-05 00:13:17 +0000773 Src0->getReg() != Src1->getReg() ||
Stanislav Mekhanoshin286a4222017-06-05 01:03:04 +0000774 Src0->getSubReg() != Src1->getSubReg() ||
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000775 Src0->getSubReg() != AMDGPU::NoSubRegister)
776 return nullptr;
777
778 // Can't fold up if we have modifiers.
Matt Arsenaultab4a5cd2017-08-31 23:53:50 +0000779 if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
780 return nullptr;
781
782 unsigned Src0Mods
783 = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
784 unsigned Src1Mods
785 = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
786
787 // Having a 0 op_sel_hi would require swizzling the output in the source
788 // instruction, which we can't do.
789 unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1 : 0;
790 if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000791 return nullptr;
792 return Src0;
793 }
794 default:
795 return nullptr;
796 }
797}
798
799// We obviously have multiple uses in a clamp since the register is used twice
800// in the same instruction.
801static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) {
802 int Count = 0;
803 for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
804 I != E; ++I) {
805 if (++Count > 1)
806 return false;
807 }
808
809 return true;
810}
811
Matt Arsenault8cbb4882017-09-20 21:01:24 +0000812// FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000813bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) {
814 const MachineOperand *ClampSrc = isClamp(MI);
815 if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg()))
816 return false;
817
818 MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg());
Matt Arsenaultab4a5cd2017-08-31 23:53:50 +0000819
820 // The type of clamp must be compatible.
821 if (TII->getClampMask(*Def) != TII->getClampMask(MI))
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000822 return false;
Matt Arsenaultab4a5cd2017-08-31 23:53:50 +0000823
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000824 MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
825 if (!DefClamp)
826 return false;
827
828 DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def << '\n');
829
830 // Clamp is applied after omod, so it is OK if omod is set.
831 DefClamp->setImm(1);
832 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
833 MI.eraseFromParent();
834 return true;
835}
836
Matt Arsenault3cb39042017-02-27 19:35:42 +0000837static int getOModValue(unsigned Opc, int64_t Val) {
838 switch (Opc) {
839 case AMDGPU::V_MUL_F32_e64: {
840 switch (static_cast<uint32_t>(Val)) {
841 case 0x3f000000: // 0.5
842 return SIOutMods::DIV2;
843 case 0x40000000: // 2.0
844 return SIOutMods::MUL2;
845 case 0x40800000: // 4.0
846 return SIOutMods::MUL4;
847 default:
848 return SIOutMods::NONE;
849 }
850 }
851 case AMDGPU::V_MUL_F16_e64: {
852 switch (static_cast<uint16_t>(Val)) {
853 case 0x3800: // 0.5
854 return SIOutMods::DIV2;
855 case 0x4000: // 2.0
856 return SIOutMods::MUL2;
857 case 0x4400: // 4.0
858 return SIOutMods::MUL4;
859 default:
860 return SIOutMods::NONE;
861 }
862 }
863 default:
864 llvm_unreachable("invalid mul opcode");
865 }
866}
867
868// FIXME: Does this really not support denormals with f16?
869// FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
870// handled, so will anything other than that break?
871std::pair<const MachineOperand *, int>
872SIFoldOperands::isOMod(const MachineInstr &MI) const {
873 unsigned Op = MI.getOpcode();
874 switch (Op) {
875 case AMDGPU::V_MUL_F32_e64:
876 case AMDGPU::V_MUL_F16_e64: {
877 // If output denormals are enabled, omod is ignored.
878 if ((Op == AMDGPU::V_MUL_F32_e64 && ST->hasFP32Denormals()) ||
879 (Op == AMDGPU::V_MUL_F16_e64 && ST->hasFP16Denormals()))
880 return std::make_pair(nullptr, SIOutMods::NONE);
881
882 const MachineOperand *RegOp = nullptr;
883 const MachineOperand *ImmOp = nullptr;
884 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
885 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
886 if (Src0->isImm()) {
887 ImmOp = Src0;
888 RegOp = Src1;
889 } else if (Src1->isImm()) {
890 ImmOp = Src1;
891 RegOp = Src0;
892 } else
893 return std::make_pair(nullptr, SIOutMods::NONE);
894
895 int OMod = getOModValue(Op, ImmOp->getImm());
896 if (OMod == SIOutMods::NONE ||
897 TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
898 TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
899 TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
900 TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
901 return std::make_pair(nullptr, SIOutMods::NONE);
902
903 return std::make_pair(RegOp, OMod);
904 }
905 case AMDGPU::V_ADD_F32_e64:
906 case AMDGPU::V_ADD_F16_e64: {
907 // If output denormals are enabled, omod is ignored.
908 if ((Op == AMDGPU::V_ADD_F32_e64 && ST->hasFP32Denormals()) ||
909 (Op == AMDGPU::V_ADD_F16_e64 && ST->hasFP16Denormals()))
910 return std::make_pair(nullptr, SIOutMods::NONE);
911
912 // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
913 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
914 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
915
916 if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
917 Src0->getSubReg() == Src1->getSubReg() &&
918 !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
919 !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
920 !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
921 !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
922 return std::make_pair(Src0, SIOutMods::MUL2);
923
924 return std::make_pair(nullptr, SIOutMods::NONE);
925 }
926 default:
927 return std::make_pair(nullptr, SIOutMods::NONE);
928 }
929}
930
931// FIXME: Does this need to check IEEE bit on function?
932bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) {
933 const MachineOperand *RegOp;
934 int OMod;
935 std::tie(RegOp, OMod) = isOMod(MI);
936 if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
937 RegOp->getSubReg() != AMDGPU::NoSubRegister ||
938 !hasOneNonDBGUseInst(*MRI, RegOp->getReg()))
939 return false;
940
941 MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
942 MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
943 if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
944 return false;
945
946 // Clamp is applied after omod. If the source already has clamp set, don't
947 // fold it.
948 if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
949 return false;
950
951 DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def << '\n');
952
953 DefOMod->setImm(OMod);
954 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
955 MI.eraseFromParent();
956 return true;
957}
958
Tom Stellard6596ba72014-11-21 22:06:37 +0000959bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000960 if (skipFunction(MF.getFunction()))
Andrew Kaylor7de74af2016-04-25 22:23:44 +0000961 return false;
962
Matt Arsenault51818c12017-01-10 23:32:04 +0000963 MRI = &MF.getRegInfo();
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000964 ST = &MF.getSubtarget<SISubtarget>();
965 TII = ST->getInstrInfo();
Matt Arsenault51818c12017-01-10 23:32:04 +0000966 TRI = &TII->getRegisterInfo();
Tom Stellard6596ba72014-11-21 22:06:37 +0000967
Matt Arsenault3cb39042017-02-27 19:35:42 +0000968 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
969
970 // omod is ignored by hardware if IEEE bit is enabled. omod also does not
971 // correctly handle signed zeros.
972 //
973 // TODO: Check nsz on instructions when fast math flags are preserved to MI
974 // level.
975 bool IsIEEEMode = ST->enableIEEEBit(MF) || !MFI->hasNoSignedZerosFPMath();
976
Matt Arsenaultff3f9122017-06-20 18:56:32 +0000977 for (MachineBasicBlock *MBB : depth_first(&MF)) {
Tom Stellard6596ba72014-11-21 22:06:37 +0000978 MachineBasicBlock::iterator I, Next;
Matt Arsenaultff3f9122017-06-20 18:56:32 +0000979 for (I = MBB->begin(); I != MBB->end(); I = Next) {
Tom Stellard6596ba72014-11-21 22:06:37 +0000980 Next = std::next(I);
981 MachineInstr &MI = *I;
982
Stanislav Mekhanoshin70603dc2017-03-24 18:55:20 +0000983 tryFoldInst(TII, &MI);
984
Sam Kolton27e0f8b2017-03-31 11:42:43 +0000985 if (!TII->isFoldableCopy(MI)) {
Matt Arsenault3cb39042017-02-27 19:35:42 +0000986 if (IsIEEEMode || !tryFoldOMod(MI))
987 tryFoldClamp(MI);
Tom Stellard6596ba72014-11-21 22:06:37 +0000988 continue;
Matt Arsenaultd5c65152017-02-22 23:27:53 +0000989 }
Tom Stellard6596ba72014-11-21 22:06:37 +0000990
991 MachineOperand &OpToFold = MI.getOperand(1);
Matt Arsenault2bc198a2016-09-14 15:51:33 +0000992 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI();
Tom Stellard26cc18d2015-01-07 22:18:27 +0000993
Matt Arsenault51818c12017-01-10 23:32:04 +0000994 // FIXME: We could also be folding things like TargetIndexes.
Tom Stellard05992972015-01-07 22:44:19 +0000995 if (!FoldingImm && !OpToFold.isReg())
996 continue;
997
Tom Stellard6596ba72014-11-21 22:06:37 +0000998 if (OpToFold.isReg() &&
Nicolai Haehnle82fc9622016-01-07 17:10:29 +0000999 !TargetRegisterInfo::isVirtualRegister(OpToFold.getReg()))
Tom Stellard6596ba72014-11-21 22:06:37 +00001000 continue;
1001
Marek Olsak926c56f2016-01-13 11:44:29 +00001002 // Prevent folding operands backwards in the function. For example,
1003 // the COPY opcode must not be replaced by 1 in this example:
1004 //
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +00001005 // %3 = COPY %vgpr0; VGPR_32:%3
Marek Olsak926c56f2016-01-13 11:44:29 +00001006 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +00001007 // %vgpr0 = V_MOV_B32_e32 1, implicit %exec
Marek Olsak926c56f2016-01-13 11:44:29 +00001008 MachineOperand &Dst = MI.getOperand(0);
1009 if (Dst.isReg() &&
1010 !TargetRegisterInfo::isVirtualRegister(Dst.getReg()))
1011 continue;
1012
Matt Arsenault51818c12017-01-10 23:32:04 +00001013 foldInstOperand(MI, OpToFold);
Tom Stellard6596ba72014-11-21 22:06:37 +00001014 }
1015 }
1016 return false;
1017}