1 //===- AMDGPUInstructionSelector.cpp ----------------------------*- C++ -*-==//
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 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the targeting of the InstructionSelector class for
10 /// AMDGPU.
11 /// \todo This should be generated by TableGen.
12 //===----------------------------------------------------------------------===//
13 
14 #include "AMDGPUInstructionSelector.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUGlobalISelUtils.h"
17 #include "AMDGPUInstrInfo.h"
18 #include "AMDGPURegisterBankInfo.h"
19 #include "AMDGPUTargetMachine.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "Utils/AMDGPUBaseInfo.h"
22 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
23 #include "llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h"
24 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
25 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 
28 #define DEBUG_TYPE "amdgpu-isel"
29 
30 using namespace llvm;
31 using namespace MIPatternMatch;
32 
33 static cl::opt<bool> AllowRiskySelect(
34   "amdgpu-global-isel-risky-select",
35   cl::desc("Allow GlobalISel to select cases that are likely to not work yet"),
36   cl::init(false),
37   cl::ReallyHidden);
38 
39 #define GET_GLOBALISEL_IMPL
40 #define AMDGPUSubtarget GCNSubtarget
41 #include "AMDGPUGenGlobalISel.inc"
42 #undef GET_GLOBALISEL_IMPL
43 #undef AMDGPUSubtarget
44 
AMDGPUInstructionSelector(const GCNSubtarget & STI,const AMDGPURegisterBankInfo & RBI,const AMDGPUTargetMachine & TM)45 AMDGPUInstructionSelector::AMDGPUInstructionSelector(
46     const GCNSubtarget &STI, const AMDGPURegisterBankInfo &RBI,
47     const AMDGPUTargetMachine &TM)
48     : InstructionSelector(), TII(*STI.getInstrInfo()),
49       TRI(*STI.getRegisterInfo()), RBI(RBI), TM(TM),
50       STI(STI),
51       EnableLateStructurizeCFG(AMDGPUTargetMachine::EnableLateStructurizeCFG),
52 #define GET_GLOBALISEL_PREDICATES_INIT
53 #include "AMDGPUGenGlobalISel.inc"
54 #undef GET_GLOBALISEL_PREDICATES_INIT
55 #define GET_GLOBALISEL_TEMPORARIES_INIT
56 #include "AMDGPUGenGlobalISel.inc"
57 #undef GET_GLOBALISEL_TEMPORARIES_INIT
58 {
59 }
60 
getName()61 const char *AMDGPUInstructionSelector::getName() { return DEBUG_TYPE; }
62 
setupMF(MachineFunction & MF,GISelKnownBits * KB,CodeGenCoverage & CoverageInfo,ProfileSummaryInfo * PSI,BlockFrequencyInfo * BFI)63 void AMDGPUInstructionSelector::setupMF(MachineFunction &MF, GISelKnownBits *KB,
64                                         CodeGenCoverage &CoverageInfo,
65                                         ProfileSummaryInfo *PSI,
66                                         BlockFrequencyInfo *BFI) {
67   MRI = &MF.getRegInfo();
68   Subtarget = &MF.getSubtarget<GCNSubtarget>();
69   InstructionSelector::setupMF(MF, KB, CoverageInfo, PSI, BFI);
70 }
71 
isVCC(Register Reg,const MachineRegisterInfo & MRI) const72 bool AMDGPUInstructionSelector::isVCC(Register Reg,
73                                       const MachineRegisterInfo &MRI) const {
74   // The verifier is oblivious to s1 being a valid value for wavesize registers.
75   if (Reg.isPhysical())
76     return false;
77 
78   auto &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
79   const TargetRegisterClass *RC =
80       RegClassOrBank.dyn_cast<const TargetRegisterClass*>();
81   if (RC) {
82     const LLT Ty = MRI.getType(Reg);
83     return RC->hasSuperClassEq(TRI.getBoolRC()) &&
84            Ty.isValid() && Ty.getSizeInBits() == 1;
85   }
86 
87   const RegisterBank *RB = RegClassOrBank.get<const RegisterBank *>();
88   return RB->getID() == AMDGPU::VCCRegBankID;
89 }
90 
constrainCopyLikeIntrin(MachineInstr & MI,unsigned NewOpc) const91 bool AMDGPUInstructionSelector::constrainCopyLikeIntrin(MachineInstr &MI,
92                                                         unsigned NewOpc) const {
93   MI.setDesc(TII.get(NewOpc));
94   MI.RemoveOperand(1); // Remove intrinsic ID.
95   MI.addOperand(*MF, MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
96 
97   MachineOperand &Dst = MI.getOperand(0);
98   MachineOperand &Src = MI.getOperand(1);
99 
100   // TODO: This should be legalized to s32 if needed
101   if (MRI->getType(Dst.getReg()) == LLT::scalar(1))
102     return false;
103 
104   const TargetRegisterClass *DstRC
105     = TRI.getConstrainedRegClassForOperand(Dst, *MRI);
106   const TargetRegisterClass *SrcRC
107     = TRI.getConstrainedRegClassForOperand(Src, *MRI);
108   if (!DstRC || DstRC != SrcRC)
109     return false;
110 
111   return RBI.constrainGenericRegister(Dst.getReg(), *DstRC, *MRI) &&
112          RBI.constrainGenericRegister(Src.getReg(), *SrcRC, *MRI);
113 }
114 
selectCOPY(MachineInstr & I) const115 bool AMDGPUInstructionSelector::selectCOPY(MachineInstr &I) const {
116   const DebugLoc &DL = I.getDebugLoc();
117   MachineBasicBlock *BB = I.getParent();
118   I.setDesc(TII.get(TargetOpcode::COPY));
119 
120   const MachineOperand &Src = I.getOperand(1);
121   MachineOperand &Dst = I.getOperand(0);
122   Register DstReg = Dst.getReg();
123   Register SrcReg = Src.getReg();
124 
125   if (isVCC(DstReg, *MRI)) {
126     if (SrcReg == AMDGPU::SCC) {
127       const TargetRegisterClass *RC
128         = TRI.getConstrainedRegClassForOperand(Dst, *MRI);
129       if (!RC)
130         return true;
131       return RBI.constrainGenericRegister(DstReg, *RC, *MRI);
132     }
133 
134     if (!isVCC(SrcReg, *MRI)) {
135       // TODO: Should probably leave the copy and let copyPhysReg expand it.
136       if (!RBI.constrainGenericRegister(DstReg, *TRI.getBoolRC(), *MRI))
137         return false;
138 
139       const TargetRegisterClass *SrcRC
140         = TRI.getConstrainedRegClassForOperand(Src, *MRI);
141 
142       Optional<ValueAndVReg> ConstVal =
143           getConstantVRegValWithLookThrough(SrcReg, *MRI, true, true);
144       if (ConstVal) {
145         unsigned MovOpc =
146             STI.isWave64() ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
147         BuildMI(*BB, &I, DL, TII.get(MovOpc), DstReg)
148             .addImm(ConstVal->Value.getBoolValue() ? -1 : 0);
149       } else {
150         Register MaskedReg = MRI->createVirtualRegister(SrcRC);
151 
152         // We can't trust the high bits at this point, so clear them.
153 
154         // TODO: Skip masking high bits if def is known boolean.
155 
156         unsigned AndOpc =
157             TRI.isSGPRClass(SrcRC) ? AMDGPU::S_AND_B32 : AMDGPU::V_AND_B32_e32;
158         BuildMI(*BB, &I, DL, TII.get(AndOpc), MaskedReg)
159             .addImm(1)
160             .addReg(SrcReg);
161         BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_CMP_NE_U32_e64), DstReg)
162             .addImm(0)
163             .addReg(MaskedReg);
164       }
165 
166       if (!MRI->getRegClassOrNull(SrcReg))
167         MRI->setRegClass(SrcReg, SrcRC);
168       I.eraseFromParent();
169       return true;
170     }
171 
172     const TargetRegisterClass *RC =
173       TRI.getConstrainedRegClassForOperand(Dst, *MRI);
174     if (RC && !RBI.constrainGenericRegister(DstReg, *RC, *MRI))
175       return false;
176 
177     return true;
178   }
179 
180   for (const MachineOperand &MO : I.operands()) {
181     if (MO.getReg().isPhysical())
182       continue;
183 
184     const TargetRegisterClass *RC =
185             TRI.getConstrainedRegClassForOperand(MO, *MRI);
186     if (!RC)
187       continue;
188     RBI.constrainGenericRegister(MO.getReg(), *RC, *MRI);
189   }
190   return true;
191 }
192 
selectPHI(MachineInstr & I) const193 bool AMDGPUInstructionSelector::selectPHI(MachineInstr &I) const {
194   const Register DefReg = I.getOperand(0).getReg();
195   const LLT DefTy = MRI->getType(DefReg);
196   if (DefTy == LLT::scalar(1)) {
197     if (!AllowRiskySelect) {
198       LLVM_DEBUG(dbgs() << "Skipping risky boolean phi\n");
199       return false;
200     }
201 
202     LLVM_DEBUG(dbgs() << "Selecting risky boolean phi\n");
203   }
204 
205   // TODO: Verify this doesn't have insane operands (i.e. VGPR to SGPR copy)
206 
207   const RegClassOrRegBank &RegClassOrBank =
208     MRI->getRegClassOrRegBank(DefReg);
209 
210   const TargetRegisterClass *DefRC
211     = RegClassOrBank.dyn_cast<const TargetRegisterClass *>();
212   if (!DefRC) {
213     if (!DefTy.isValid()) {
214       LLVM_DEBUG(dbgs() << "PHI operand has no type, not a gvreg?\n");
215       return false;
216     }
217 
218     const RegisterBank &RB = *RegClassOrBank.get<const RegisterBank *>();
219     DefRC = TRI.getRegClassForTypeOnBank(DefTy, RB, *MRI);
220     if (!DefRC) {
221       LLVM_DEBUG(dbgs() << "PHI operand has unexpected size/bank\n");
222       return false;
223     }
224   }
225 
226   // TODO: Verify that all registers have the same bank
227   I.setDesc(TII.get(TargetOpcode::PHI));
228   return RBI.constrainGenericRegister(DefReg, *DefRC, *MRI);
229 }
230 
231 MachineOperand
getSubOperand64(MachineOperand & MO,const TargetRegisterClass & SubRC,unsigned SubIdx) const232 AMDGPUInstructionSelector::getSubOperand64(MachineOperand &MO,
233                                            const TargetRegisterClass &SubRC,
234                                            unsigned SubIdx) const {
235 
236   MachineInstr *MI = MO.getParent();
237   MachineBasicBlock *BB = MO.getParent()->getParent();
238   Register DstReg = MRI->createVirtualRegister(&SubRC);
239 
240   if (MO.isReg()) {
241     unsigned ComposedSubIdx = TRI.composeSubRegIndices(MO.getSubReg(), SubIdx);
242     Register Reg = MO.getReg();
243     BuildMI(*BB, MI, MI->getDebugLoc(), TII.get(AMDGPU::COPY), DstReg)
244             .addReg(Reg, 0, ComposedSubIdx);
245 
246     return MachineOperand::CreateReg(DstReg, MO.isDef(), MO.isImplicit(),
247                                      MO.isKill(), MO.isDead(), MO.isUndef(),
248                                      MO.isEarlyClobber(), 0, MO.isDebug(),
249                                      MO.isInternalRead());
250   }
251 
252   assert(MO.isImm());
253 
254   APInt Imm(64, MO.getImm());
255 
256   switch (SubIdx) {
257   default:
258     llvm_unreachable("do not know to split immediate with this sub index.");
259   case AMDGPU::sub0:
260     return MachineOperand::CreateImm(Imm.getLoBits(32).getSExtValue());
261   case AMDGPU::sub1:
262     return MachineOperand::CreateImm(Imm.getHiBits(32).getSExtValue());
263   }
264 }
265 
getLogicalBitOpcode(unsigned Opc,bool Is64)266 static unsigned getLogicalBitOpcode(unsigned Opc, bool Is64) {
267   switch (Opc) {
268   case AMDGPU::G_AND:
269     return Is64 ? AMDGPU::S_AND_B64 : AMDGPU::S_AND_B32;
270   case AMDGPU::G_OR:
271     return Is64 ? AMDGPU::S_OR_B64 : AMDGPU::S_OR_B32;
272   case AMDGPU::G_XOR:
273     return Is64 ? AMDGPU::S_XOR_B64 : AMDGPU::S_XOR_B32;
274   default:
275     llvm_unreachable("not a bit op");
276   }
277 }
278 
selectG_AND_OR_XOR(MachineInstr & I) const279 bool AMDGPUInstructionSelector::selectG_AND_OR_XOR(MachineInstr &I) const {
280   Register DstReg = I.getOperand(0).getReg();
281   unsigned Size = RBI.getSizeInBits(DstReg, *MRI, TRI);
282 
283   const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
284   if (DstRB->getID() != AMDGPU::SGPRRegBankID &&
285       DstRB->getID() != AMDGPU::VCCRegBankID)
286     return false;
287 
288   bool Is64 = Size > 32 || (DstRB->getID() == AMDGPU::VCCRegBankID &&
289                             STI.isWave64());
290   I.setDesc(TII.get(getLogicalBitOpcode(I.getOpcode(), Is64)));
291 
292   // Dead implicit-def of scc
293   I.addOperand(MachineOperand::CreateReg(AMDGPU::SCC, true, // isDef
294                                          true, // isImp
295                                          false, // isKill
296                                          true)); // isDead
297   return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
298 }
299 
selectG_ADD_SUB(MachineInstr & I) const300 bool AMDGPUInstructionSelector::selectG_ADD_SUB(MachineInstr &I) const {
301   MachineBasicBlock *BB = I.getParent();
302   MachineFunction *MF = BB->getParent();
303   Register DstReg = I.getOperand(0).getReg();
304   const DebugLoc &DL = I.getDebugLoc();
305   LLT Ty = MRI->getType(DstReg);
306   if (Ty.isVector())
307     return false;
308 
309   unsigned Size = Ty.getSizeInBits();
310   const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
311   const bool IsSALU = DstRB->getID() == AMDGPU::SGPRRegBankID;
312   const bool Sub = I.getOpcode() == TargetOpcode::G_SUB;
313 
314   if (Size == 32) {
315     if (IsSALU) {
316       const unsigned Opc = Sub ? AMDGPU::S_SUB_U32 : AMDGPU::S_ADD_U32;
317       MachineInstr *Add =
318         BuildMI(*BB, &I, DL, TII.get(Opc), DstReg)
319         .add(I.getOperand(1))
320         .add(I.getOperand(2));
321       I.eraseFromParent();
322       return constrainSelectedInstRegOperands(*Add, TII, TRI, RBI);
323     }
324 
325     if (STI.hasAddNoCarry()) {
326       const unsigned Opc = Sub ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_ADD_U32_e64;
327       I.setDesc(TII.get(Opc));
328       I.addOperand(*MF, MachineOperand::CreateImm(0));
329       I.addOperand(*MF, MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
330       return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
331     }
332 
333     const unsigned Opc = Sub ? AMDGPU::V_SUB_CO_U32_e64 : AMDGPU::V_ADD_CO_U32_e64;
334 
335     Register UnusedCarry = MRI->createVirtualRegister(TRI.getWaveMaskRegClass());
336     MachineInstr *Add
337       = BuildMI(*BB, &I, DL, TII.get(Opc), DstReg)
338       .addDef(UnusedCarry, RegState::Dead)
339       .add(I.getOperand(1))
340       .add(I.getOperand(2))
341       .addImm(0);
342     I.eraseFromParent();
343     return constrainSelectedInstRegOperands(*Add, TII, TRI, RBI);
344   }
345 
346   assert(!Sub && "illegal sub should not reach here");
347 
348   const TargetRegisterClass &RC
349     = IsSALU ? AMDGPU::SReg_64_XEXECRegClass : AMDGPU::VReg_64RegClass;
350   const TargetRegisterClass &HalfRC
351     = IsSALU ? AMDGPU::SReg_32RegClass : AMDGPU::VGPR_32RegClass;
352 
353   MachineOperand Lo1(getSubOperand64(I.getOperand(1), HalfRC, AMDGPU::sub0));
354   MachineOperand Lo2(getSubOperand64(I.getOperand(2), HalfRC, AMDGPU::sub0));
355   MachineOperand Hi1(getSubOperand64(I.getOperand(1), HalfRC, AMDGPU::sub1));
356   MachineOperand Hi2(getSubOperand64(I.getOperand(2), HalfRC, AMDGPU::sub1));
357 
358   Register DstLo = MRI->createVirtualRegister(&HalfRC);
359   Register DstHi = MRI->createVirtualRegister(&HalfRC);
360 
361   if (IsSALU) {
362     BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_ADD_U32), DstLo)
363       .add(Lo1)
364       .add(Lo2);
365     BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_ADDC_U32), DstHi)
366       .add(Hi1)
367       .add(Hi2);
368   } else {
369     const TargetRegisterClass *CarryRC = TRI.getWaveMaskRegClass();
370     Register CarryReg = MRI->createVirtualRegister(CarryRC);
371     BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_ADD_CO_U32_e64), DstLo)
372       .addDef(CarryReg)
373       .add(Lo1)
374       .add(Lo2)
375       .addImm(0);
376     MachineInstr *Addc = BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_ADDC_U32_e64), DstHi)
377       .addDef(MRI->createVirtualRegister(CarryRC), RegState::Dead)
378       .add(Hi1)
379       .add(Hi2)
380       .addReg(CarryReg, RegState::Kill)
381       .addImm(0);
382 
383     if (!constrainSelectedInstRegOperands(*Addc, TII, TRI, RBI))
384       return false;
385   }
386 
387   BuildMI(*BB, &I, DL, TII.get(AMDGPU::REG_SEQUENCE), DstReg)
388     .addReg(DstLo)
389     .addImm(AMDGPU::sub0)
390     .addReg(DstHi)
391     .addImm(AMDGPU::sub1);
392 
393 
394   if (!RBI.constrainGenericRegister(DstReg, RC, *MRI))
395     return false;
396 
397   I.eraseFromParent();
398   return true;
399 }
400 
selectG_UADDO_USUBO_UADDE_USUBE(MachineInstr & I) const401 bool AMDGPUInstructionSelector::selectG_UADDO_USUBO_UADDE_USUBE(
402   MachineInstr &I) const {
403   MachineBasicBlock *BB = I.getParent();
404   MachineFunction *MF = BB->getParent();
405   const DebugLoc &DL = I.getDebugLoc();
406   Register Dst0Reg = I.getOperand(0).getReg();
407   Register Dst1Reg = I.getOperand(1).getReg();
408   const bool IsAdd = I.getOpcode() == AMDGPU::G_UADDO ||
409                      I.getOpcode() == AMDGPU::G_UADDE;
410   const bool HasCarryIn = I.getOpcode() == AMDGPU::G_UADDE ||
411                           I.getOpcode() == AMDGPU::G_USUBE;
412 
413   if (isVCC(Dst1Reg, *MRI)) {
414     unsigned NoCarryOpc =
415         IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
416     unsigned CarryOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
417     I.setDesc(TII.get(HasCarryIn ? CarryOpc : NoCarryOpc));
418     I.addOperand(*MF, MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
419     I.addOperand(*MF, MachineOperand::CreateImm(0));
420     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
421   }
422 
423   Register Src0Reg = I.getOperand(2).getReg();
424   Register Src1Reg = I.getOperand(3).getReg();
425 
426   if (HasCarryIn) {
427     BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), AMDGPU::SCC)
428       .addReg(I.getOperand(4).getReg());
429   }
430 
431   unsigned NoCarryOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
432   unsigned CarryOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
433 
434   BuildMI(*BB, &I, DL, TII.get(HasCarryIn ? CarryOpc : NoCarryOpc), Dst0Reg)
435     .add(I.getOperand(2))
436     .add(I.getOperand(3));
437   BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), Dst1Reg)
438     .addReg(AMDGPU::SCC);
439 
440   if (!MRI->getRegClassOrNull(Dst1Reg))
441     MRI->setRegClass(Dst1Reg, &AMDGPU::SReg_32RegClass);
442 
443   if (!RBI.constrainGenericRegister(Dst0Reg, AMDGPU::SReg_32RegClass, *MRI) ||
444       !RBI.constrainGenericRegister(Src0Reg, AMDGPU::SReg_32RegClass, *MRI) ||
445       !RBI.constrainGenericRegister(Src1Reg, AMDGPU::SReg_32RegClass, *MRI))
446     return false;
447 
448   if (HasCarryIn &&
449       !RBI.constrainGenericRegister(I.getOperand(4).getReg(),
450                                     AMDGPU::SReg_32RegClass, *MRI))
451     return false;
452 
453   I.eraseFromParent();
454   return true;
455 }
456 
457 // TODO: We should probably legalize these to only using 32-bit results.
selectG_EXTRACT(MachineInstr & I) const458 bool AMDGPUInstructionSelector::selectG_EXTRACT(MachineInstr &I) const {
459   MachineBasicBlock *BB = I.getParent();
460   Register DstReg = I.getOperand(0).getReg();
461   Register SrcReg = I.getOperand(1).getReg();
462   LLT DstTy = MRI->getType(DstReg);
463   LLT SrcTy = MRI->getType(SrcReg);
464   const unsigned SrcSize = SrcTy.getSizeInBits();
465   unsigned DstSize = DstTy.getSizeInBits();
466 
467   // TODO: Should handle any multiple of 32 offset.
468   unsigned Offset = I.getOperand(2).getImm();
469   if (Offset % 32 != 0 || DstSize > 128)
470     return false;
471 
472   // 16-bit operations really use 32-bit registers.
473   // FIXME: Probably should not allow 16-bit G_EXTRACT results.
474   if (DstSize == 16)
475     DstSize = 32;
476 
477   const TargetRegisterClass *DstRC =
478     TRI.getConstrainedRegClassForOperand(I.getOperand(0), *MRI);
479   if (!DstRC || !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
480     return false;
481 
482   const RegisterBank *SrcBank = RBI.getRegBank(SrcReg, *MRI, TRI);
483   const TargetRegisterClass *SrcRC =
484     TRI.getRegClassForSizeOnBank(SrcSize, *SrcBank, *MRI);
485   if (!SrcRC)
486     return false;
487   unsigned SubReg = SIRegisterInfo::getSubRegFromChannel(Offset / 32,
488                                                          DstSize / 32);
489   SrcRC = TRI.getSubClassWithSubReg(SrcRC, SubReg);
490   if (!SrcRC)
491     return false;
492 
493   SrcReg = constrainOperandRegClass(*MF, TRI, *MRI, TII, RBI, I,
494                                     *SrcRC, I.getOperand(1));
495   const DebugLoc &DL = I.getDebugLoc();
496   BuildMI(*BB, &I, DL, TII.get(TargetOpcode::COPY), DstReg)
497     .addReg(SrcReg, 0, SubReg);
498 
499   I.eraseFromParent();
500   return true;
501 }
502 
selectG_MERGE_VALUES(MachineInstr & MI) const503 bool AMDGPUInstructionSelector::selectG_MERGE_VALUES(MachineInstr &MI) const {
504   MachineBasicBlock *BB = MI.getParent();
505   Register DstReg = MI.getOperand(0).getReg();
506   LLT DstTy = MRI->getType(DstReg);
507   LLT SrcTy = MRI->getType(MI.getOperand(1).getReg());
508 
509   const unsigned SrcSize = SrcTy.getSizeInBits();
510   if (SrcSize < 32)
511     return selectImpl(MI, *CoverageInfo);
512 
513   const DebugLoc &DL = MI.getDebugLoc();
514   const RegisterBank *DstBank = RBI.getRegBank(DstReg, *MRI, TRI);
515   const unsigned DstSize = DstTy.getSizeInBits();
516   const TargetRegisterClass *DstRC =
517     TRI.getRegClassForSizeOnBank(DstSize, *DstBank, *MRI);
518   if (!DstRC)
519     return false;
520 
521   ArrayRef<int16_t> SubRegs = TRI.getRegSplitParts(DstRC, SrcSize / 8);
522   MachineInstrBuilder MIB =
523     BuildMI(*BB, &MI, DL, TII.get(TargetOpcode::REG_SEQUENCE), DstReg);
524   for (int I = 0, E = MI.getNumOperands() - 1; I != E; ++I) {
525     MachineOperand &Src = MI.getOperand(I + 1);
526     MIB.addReg(Src.getReg(), getUndefRegState(Src.isUndef()));
527     MIB.addImm(SubRegs[I]);
528 
529     const TargetRegisterClass *SrcRC
530       = TRI.getConstrainedRegClassForOperand(Src, *MRI);
531     if (SrcRC && !RBI.constrainGenericRegister(Src.getReg(), *SrcRC, *MRI))
532       return false;
533   }
534 
535   if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
536     return false;
537 
538   MI.eraseFromParent();
539   return true;
540 }
541 
selectG_UNMERGE_VALUES(MachineInstr & MI) const542 bool AMDGPUInstructionSelector::selectG_UNMERGE_VALUES(MachineInstr &MI) const {
543   MachineBasicBlock *BB = MI.getParent();
544   const int NumDst = MI.getNumOperands() - 1;
545 
546   MachineOperand &Src = MI.getOperand(NumDst);
547 
548   Register SrcReg = Src.getReg();
549   Register DstReg0 = MI.getOperand(0).getReg();
550   LLT DstTy = MRI->getType(DstReg0);
551   LLT SrcTy = MRI->getType(SrcReg);
552 
553   const unsigned DstSize = DstTy.getSizeInBits();
554   const unsigned SrcSize = SrcTy.getSizeInBits();
555   const DebugLoc &DL = MI.getDebugLoc();
556   const RegisterBank *SrcBank = RBI.getRegBank(SrcReg, *MRI, TRI);
557 
558   const TargetRegisterClass *SrcRC =
559     TRI.getRegClassForSizeOnBank(SrcSize, *SrcBank, *MRI);
560   if (!SrcRC || !RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI))
561     return false;
562 
563   // Note we could have mixed SGPR and VGPR destination banks for an SGPR
564   // source, and this relies on the fact that the same subregister indices are
565   // used for both.
566   ArrayRef<int16_t> SubRegs = TRI.getRegSplitParts(SrcRC, DstSize / 8);
567   for (int I = 0, E = NumDst; I != E; ++I) {
568     MachineOperand &Dst = MI.getOperand(I);
569     BuildMI(*BB, &MI, DL, TII.get(TargetOpcode::COPY), Dst.getReg())
570       .addReg(SrcReg, 0, SubRegs[I]);
571 
572     // Make sure the subregister index is valid for the source register.
573     SrcRC = TRI.getSubClassWithSubReg(SrcRC, SubRegs[I]);
574     if (!SrcRC || !RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI))
575       return false;
576 
577     const TargetRegisterClass *DstRC =
578       TRI.getConstrainedRegClassForOperand(Dst, *MRI);
579     if (DstRC && !RBI.constrainGenericRegister(Dst.getReg(), *DstRC, *MRI))
580       return false;
581   }
582 
583   MI.eraseFromParent();
584   return true;
585 }
586 
selectG_BUILD_VECTOR_TRUNC(MachineInstr & MI) const587 bool AMDGPUInstructionSelector::selectG_BUILD_VECTOR_TRUNC(
588   MachineInstr &MI) const {
589   if (selectImpl(MI, *CoverageInfo))
590     return true;
591 
592   const LLT S32 = LLT::scalar(32);
593   const LLT V2S16 = LLT::fixed_vector(2, 16);
594 
595   Register Dst = MI.getOperand(0).getReg();
596   if (MRI->getType(Dst) != V2S16)
597     return false;
598 
599   const RegisterBank *DstBank = RBI.getRegBank(Dst, *MRI, TRI);
600   if (DstBank->getID() != AMDGPU::SGPRRegBankID)
601     return false;
602 
603   Register Src0 = MI.getOperand(1).getReg();
604   Register Src1 = MI.getOperand(2).getReg();
605   if (MRI->getType(Src0) != S32)
606     return false;
607 
608   const DebugLoc &DL = MI.getDebugLoc();
609   MachineBasicBlock *BB = MI.getParent();
610 
611   auto ConstSrc1 =
612       getConstantVRegValWithLookThrough(Src1, *MRI, true, true, true);
613   if (ConstSrc1) {
614     auto ConstSrc0 =
615         getConstantVRegValWithLookThrough(Src0, *MRI, true, true, true);
616     if (ConstSrc0) {
617       const int64_t K0 = ConstSrc0->Value.getSExtValue();
618       const int64_t K1 = ConstSrc1->Value.getSExtValue();
619       uint32_t Lo16 = static_cast<uint32_t>(K0) & 0xffff;
620       uint32_t Hi16 = static_cast<uint32_t>(K1) & 0xffff;
621 
622       BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_MOV_B32), Dst)
623         .addImm(Lo16 | (Hi16 << 16));
624       MI.eraseFromParent();
625       return RBI.constrainGenericRegister(Dst, AMDGPU::SReg_32RegClass, *MRI);
626     }
627   }
628 
629   // TODO: This should probably be a combine somewhere
630   // (build_vector_trunc $src0, undef -> copy $src0
631   MachineInstr *Src1Def = getDefIgnoringCopies(Src1, *MRI);
632   if (Src1Def && Src1Def->getOpcode() == AMDGPU::G_IMPLICIT_DEF) {
633     MI.setDesc(TII.get(AMDGPU::COPY));
634     MI.RemoveOperand(2);
635     return RBI.constrainGenericRegister(Dst, AMDGPU::SReg_32RegClass, *MRI) &&
636            RBI.constrainGenericRegister(Src0, AMDGPU::SReg_32RegClass, *MRI);
637   }
638 
639   Register ShiftSrc0;
640   Register ShiftSrc1;
641 
642   // With multiple uses of the shift, this will duplicate the shift and
643   // increase register pressure.
644   //
645   // (build_vector_trunc (lshr_oneuse $src0, 16), (lshr_oneuse $src1, 16)
646   //  => (S_PACK_HH_B32_B16 $src0, $src1)
647   // (build_vector_trunc $src0, (lshr_oneuse SReg_32:$src1, 16))
648   //  => (S_PACK_LH_B32_B16 $src0, $src1)
649   // (build_vector_trunc $src0, $src1)
650   //  => (S_PACK_LL_B32_B16 $src0, $src1)
651 
652   bool Shift0 = mi_match(
653       Src0, *MRI, m_OneUse(m_GLShr(m_Reg(ShiftSrc0), m_SpecificICst(16))));
654 
655   bool Shift1 = mi_match(
656       Src1, *MRI, m_OneUse(m_GLShr(m_Reg(ShiftSrc1), m_SpecificICst(16))));
657 
658   unsigned Opc = AMDGPU::S_PACK_LL_B32_B16;
659   if (Shift0 && Shift1) {
660     Opc = AMDGPU::S_PACK_HH_B32_B16;
661     MI.getOperand(1).setReg(ShiftSrc0);
662     MI.getOperand(2).setReg(ShiftSrc1);
663   } else if (Shift1) {
664     Opc = AMDGPU::S_PACK_LH_B32_B16;
665     MI.getOperand(2).setReg(ShiftSrc1);
666   } else if (Shift0 && ConstSrc1 && ConstSrc1->Value == 0) {
667     // build_vector_trunc (lshr $src0, 16), 0 -> s_lshr_b32 $src0, 16
668     auto MIB = BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_LSHR_B32), Dst)
669       .addReg(ShiftSrc0)
670       .addImm(16);
671 
672     MI.eraseFromParent();
673     return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
674   }
675 
676   MI.setDesc(TII.get(Opc));
677   return constrainSelectedInstRegOperands(MI, TII, TRI, RBI);
678 }
679 
selectG_PTR_ADD(MachineInstr & I) const680 bool AMDGPUInstructionSelector::selectG_PTR_ADD(MachineInstr &I) const {
681   return selectG_ADD_SUB(I);
682 }
683 
selectG_IMPLICIT_DEF(MachineInstr & I) const684 bool AMDGPUInstructionSelector::selectG_IMPLICIT_DEF(MachineInstr &I) const {
685   const MachineOperand &MO = I.getOperand(0);
686 
687   // FIXME: Interface for getConstrainedRegClassForOperand needs work. The
688   // regbank check here is to know why getConstrainedRegClassForOperand failed.
689   const TargetRegisterClass *RC = TRI.getConstrainedRegClassForOperand(MO, *MRI);
690   if ((!RC && !MRI->getRegBankOrNull(MO.getReg())) ||
691       (RC && RBI.constrainGenericRegister(MO.getReg(), *RC, *MRI))) {
692     I.setDesc(TII.get(TargetOpcode::IMPLICIT_DEF));
693     return true;
694   }
695 
696   return false;
697 }
698 
selectG_INSERT(MachineInstr & I) const699 bool AMDGPUInstructionSelector::selectG_INSERT(MachineInstr &I) const {
700   MachineBasicBlock *BB = I.getParent();
701 
702   Register DstReg = I.getOperand(0).getReg();
703   Register Src0Reg = I.getOperand(1).getReg();
704   Register Src1Reg = I.getOperand(2).getReg();
705   LLT Src1Ty = MRI->getType(Src1Reg);
706 
707   unsigned DstSize = MRI->getType(DstReg).getSizeInBits();
708   unsigned InsSize = Src1Ty.getSizeInBits();
709 
710   int64_t Offset = I.getOperand(3).getImm();
711 
712   // FIXME: These cases should have been illegal and unnecessary to check here.
713   if (Offset % 32 != 0 || InsSize % 32 != 0)
714     return false;
715 
716   // Currently not handled by getSubRegFromChannel.
717   if (InsSize > 128)
718     return false;
719 
720   unsigned SubReg = TRI.getSubRegFromChannel(Offset / 32, InsSize / 32);
721   if (SubReg == AMDGPU::NoSubRegister)
722     return false;
723 
724   const RegisterBank *DstBank = RBI.getRegBank(DstReg, *MRI, TRI);
725   const TargetRegisterClass *DstRC =
726     TRI.getRegClassForSizeOnBank(DstSize, *DstBank, *MRI);
727   if (!DstRC)
728     return false;
729 
730   const RegisterBank *Src0Bank = RBI.getRegBank(Src0Reg, *MRI, TRI);
731   const RegisterBank *Src1Bank = RBI.getRegBank(Src1Reg, *MRI, TRI);
732   const TargetRegisterClass *Src0RC =
733     TRI.getRegClassForSizeOnBank(DstSize, *Src0Bank, *MRI);
734   const TargetRegisterClass *Src1RC =
735     TRI.getRegClassForSizeOnBank(InsSize, *Src1Bank, *MRI);
736 
737   // Deal with weird cases where the class only partially supports the subreg
738   // index.
739   Src0RC = TRI.getSubClassWithSubReg(Src0RC, SubReg);
740   if (!Src0RC || !Src1RC)
741     return false;
742 
743   if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI) ||
744       !RBI.constrainGenericRegister(Src0Reg, *Src0RC, *MRI) ||
745       !RBI.constrainGenericRegister(Src1Reg, *Src1RC, *MRI))
746     return false;
747 
748   const DebugLoc &DL = I.getDebugLoc();
749   BuildMI(*BB, &I, DL, TII.get(TargetOpcode::INSERT_SUBREG), DstReg)
750     .addReg(Src0Reg)
751     .addReg(Src1Reg)
752     .addImm(SubReg);
753 
754   I.eraseFromParent();
755   return true;
756 }
757 
selectG_SBFX_UBFX(MachineInstr & MI) const758 bool AMDGPUInstructionSelector::selectG_SBFX_UBFX(MachineInstr &MI) const {
759   Register DstReg = MI.getOperand(0).getReg();
760   Register SrcReg = MI.getOperand(1).getReg();
761   Register OffsetReg = MI.getOperand(2).getReg();
762   Register WidthReg = MI.getOperand(3).getReg();
763 
764   assert(RBI.getRegBank(DstReg, *MRI, TRI)->getID() == AMDGPU::VGPRRegBankID &&
765          "scalar BFX instructions are expanded in regbankselect");
766   assert(MRI->getType(MI.getOperand(0).getReg()).getSizeInBits() == 32 &&
767          "64-bit vector BFX instructions are expanded in regbankselect");
768 
769   const DebugLoc &DL = MI.getDebugLoc();
770   MachineBasicBlock *MBB = MI.getParent();
771 
772   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SBFX;
773   unsigned Opc = IsSigned ? AMDGPU::V_BFE_I32_e64 : AMDGPU::V_BFE_U32_e64;
774   auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc), DstReg)
775                  .addReg(SrcReg)
776                  .addReg(OffsetReg)
777                  .addReg(WidthReg);
778   MI.eraseFromParent();
779   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
780 }
781 
selectInterpP1F16(MachineInstr & MI) const782 bool AMDGPUInstructionSelector::selectInterpP1F16(MachineInstr &MI) const {
783   if (STI.getLDSBankCount() != 16)
784     return selectImpl(MI, *CoverageInfo);
785 
786   Register Dst = MI.getOperand(0).getReg();
787   Register Src0 = MI.getOperand(2).getReg();
788   Register M0Val = MI.getOperand(6).getReg();
789   if (!RBI.constrainGenericRegister(M0Val, AMDGPU::SReg_32RegClass, *MRI) ||
790       !RBI.constrainGenericRegister(Dst, AMDGPU::VGPR_32RegClass, *MRI) ||
791       !RBI.constrainGenericRegister(Src0, AMDGPU::VGPR_32RegClass, *MRI))
792     return false;
793 
794   // This requires 2 instructions. It is possible to write a pattern to support
795   // this, but the generated isel emitter doesn't correctly deal with multiple
796   // output instructions using the same physical register input. The copy to m0
797   // is incorrectly placed before the second instruction.
798   //
799   // TODO: Match source modifiers.
800 
801   Register InterpMov = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
802   const DebugLoc &DL = MI.getDebugLoc();
803   MachineBasicBlock *MBB = MI.getParent();
804 
805   BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
806     .addReg(M0Val);
807   BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::V_INTERP_MOV_F32), InterpMov)
808     .addImm(2)
809     .addImm(MI.getOperand(4).getImm())  // $attr
810     .addImm(MI.getOperand(3).getImm()); // $attrchan
811 
812   BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::V_INTERP_P1LV_F16), Dst)
813     .addImm(0)                          // $src0_modifiers
814     .addReg(Src0)                       // $src0
815     .addImm(MI.getOperand(4).getImm())  // $attr
816     .addImm(MI.getOperand(3).getImm())  // $attrchan
817     .addImm(0)                          // $src2_modifiers
818     .addReg(InterpMov)                  // $src2 - 2 f16 values selected by high
819     .addImm(MI.getOperand(5).getImm())  // $high
820     .addImm(0)                          // $clamp
821     .addImm(0);                         // $omod
822 
823   MI.eraseFromParent();
824   return true;
825 }
826 
827 // Writelane is special in that it can use SGPR and M0 (which would normally
828 // count as using the constant bus twice - but in this case it is allowed since
829 // the lane selector doesn't count as a use of the constant bus). However, it is
830 // still required to abide by the 1 SGPR rule. Fix this up if we might have
831 // multiple SGPRs.
selectWritelane(MachineInstr & MI) const832 bool AMDGPUInstructionSelector::selectWritelane(MachineInstr &MI) const {
833   // With a constant bus limit of at least 2, there's no issue.
834   if (STI.getConstantBusLimit(AMDGPU::V_WRITELANE_B32) > 1)
835     return selectImpl(MI, *CoverageInfo);
836 
837   MachineBasicBlock *MBB = MI.getParent();
838   const DebugLoc &DL = MI.getDebugLoc();
839   Register VDst = MI.getOperand(0).getReg();
840   Register Val = MI.getOperand(2).getReg();
841   Register LaneSelect = MI.getOperand(3).getReg();
842   Register VDstIn = MI.getOperand(4).getReg();
843 
844   auto MIB = BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::V_WRITELANE_B32), VDst);
845 
846   Optional<ValueAndVReg> ConstSelect =
847     getConstantVRegValWithLookThrough(LaneSelect, *MRI, true, true);
848   if (ConstSelect) {
849     // The selector has to be an inline immediate, so we can use whatever for
850     // the other operands.
851     MIB.addReg(Val);
852     MIB.addImm(ConstSelect->Value.getSExtValue() &
853                maskTrailingOnes<uint64_t>(STI.getWavefrontSizeLog2()));
854   } else {
855     Optional<ValueAndVReg> ConstVal =
856       getConstantVRegValWithLookThrough(Val, *MRI, true, true);
857 
858     // If the value written is an inline immediate, we can get away without a
859     // copy to m0.
860     if (ConstVal && AMDGPU::isInlinableLiteral32(ConstVal->Value.getSExtValue(),
861                                                  STI.hasInv2PiInlineImm())) {
862       MIB.addImm(ConstVal->Value.getSExtValue());
863       MIB.addReg(LaneSelect);
864     } else {
865       MIB.addReg(Val);
866 
867       // If the lane selector was originally in a VGPR and copied with
868       // readfirstlane, there's a hazard to read the same SGPR from the
869       // VALU. Constrain to a different SGPR to help avoid needing a nop later.
870       RBI.constrainGenericRegister(LaneSelect, AMDGPU::SReg_32_XM0RegClass, *MRI);
871 
872       BuildMI(*MBB, *MIB, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
873         .addReg(LaneSelect);
874       MIB.addReg(AMDGPU::M0);
875     }
876   }
877 
878   MIB.addReg(VDstIn);
879 
880   MI.eraseFromParent();
881   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
882 }
883 
884 // We need to handle this here because tablegen doesn't support matching
885 // instructions with multiple outputs.
selectDivScale(MachineInstr & MI) const886 bool AMDGPUInstructionSelector::selectDivScale(MachineInstr &MI) const {
887   Register Dst0 = MI.getOperand(0).getReg();
888   Register Dst1 = MI.getOperand(1).getReg();
889 
890   LLT Ty = MRI->getType(Dst0);
891   unsigned Opc;
892   if (Ty == LLT::scalar(32))
893     Opc = AMDGPU::V_DIV_SCALE_F32_e64;
894   else if (Ty == LLT::scalar(64))
895     Opc = AMDGPU::V_DIV_SCALE_F64_e64;
896   else
897     return false;
898 
899   // TODO: Match source modifiers.
900 
901   const DebugLoc &DL = MI.getDebugLoc();
902   MachineBasicBlock *MBB = MI.getParent();
903 
904   Register Numer = MI.getOperand(3).getReg();
905   Register Denom = MI.getOperand(4).getReg();
906   unsigned ChooseDenom = MI.getOperand(5).getImm();
907 
908   Register Src0 = ChooseDenom != 0 ? Numer : Denom;
909 
910   auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc), Dst0)
911     .addDef(Dst1)
912     .addImm(0)     // $src0_modifiers
913     .addUse(Src0)  // $src0
914     .addImm(0)     // $src1_modifiers
915     .addUse(Denom) // $src1
916     .addImm(0)     // $src2_modifiers
917     .addUse(Numer) // $src2
918     .addImm(0)     // $clamp
919     .addImm(0);    // $omod
920 
921   MI.eraseFromParent();
922   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
923 }
924 
selectG_INTRINSIC(MachineInstr & I) const925 bool AMDGPUInstructionSelector::selectG_INTRINSIC(MachineInstr &I) const {
926   unsigned IntrinsicID = I.getIntrinsicID();
927   switch (IntrinsicID) {
928   case Intrinsic::amdgcn_if_break: {
929     MachineBasicBlock *BB = I.getParent();
930 
931     // FIXME: Manually selecting to avoid dealiing with the SReg_1 trick
932     // SelectionDAG uses for wave32 vs wave64.
933     BuildMI(*BB, &I, I.getDebugLoc(), TII.get(AMDGPU::SI_IF_BREAK))
934       .add(I.getOperand(0))
935       .add(I.getOperand(2))
936       .add(I.getOperand(3));
937 
938     Register DstReg = I.getOperand(0).getReg();
939     Register Src0Reg = I.getOperand(2).getReg();
940     Register Src1Reg = I.getOperand(3).getReg();
941 
942     I.eraseFromParent();
943 
944     for (Register Reg : { DstReg, Src0Reg, Src1Reg })
945       MRI->setRegClass(Reg, TRI.getWaveMaskRegClass());
946 
947     return true;
948   }
949   case Intrinsic::amdgcn_interp_p1_f16:
950     return selectInterpP1F16(I);
951   case Intrinsic::amdgcn_wqm:
952     return constrainCopyLikeIntrin(I, AMDGPU::WQM);
953   case Intrinsic::amdgcn_softwqm:
954     return constrainCopyLikeIntrin(I, AMDGPU::SOFT_WQM);
955   case Intrinsic::amdgcn_strict_wwm:
956   case Intrinsic::amdgcn_wwm:
957     return constrainCopyLikeIntrin(I, AMDGPU::STRICT_WWM);
958   case Intrinsic::amdgcn_strict_wqm:
959     return constrainCopyLikeIntrin(I, AMDGPU::STRICT_WQM);
960   case Intrinsic::amdgcn_writelane:
961     return selectWritelane(I);
962   case Intrinsic::amdgcn_div_scale:
963     return selectDivScale(I);
964   case Intrinsic::amdgcn_icmp:
965     return selectIntrinsicIcmp(I);
966   case Intrinsic::amdgcn_ballot:
967     return selectBallot(I);
968   case Intrinsic::amdgcn_reloc_constant:
969     return selectRelocConstant(I);
970   case Intrinsic::amdgcn_groupstaticsize:
971     return selectGroupStaticSize(I);
972   case Intrinsic::returnaddress:
973     return selectReturnAddress(I);
974   default:
975     return selectImpl(I, *CoverageInfo);
976   }
977 }
978 
getV_CMPOpcode(CmpInst::Predicate P,unsigned Size)979 static int getV_CMPOpcode(CmpInst::Predicate P, unsigned Size) {
980   if (Size != 32 && Size != 64)
981     return -1;
982   switch (P) {
983   default:
984     llvm_unreachable("Unknown condition code!");
985   case CmpInst::ICMP_NE:
986     return Size == 32 ? AMDGPU::V_CMP_NE_U32_e64 : AMDGPU::V_CMP_NE_U64_e64;
987   case CmpInst::ICMP_EQ:
988     return Size == 32 ? AMDGPU::V_CMP_EQ_U32_e64 : AMDGPU::V_CMP_EQ_U64_e64;
989   case CmpInst::ICMP_SGT:
990     return Size == 32 ? AMDGPU::V_CMP_GT_I32_e64 : AMDGPU::V_CMP_GT_I64_e64;
991   case CmpInst::ICMP_SGE:
992     return Size == 32 ? AMDGPU::V_CMP_GE_I32_e64 : AMDGPU::V_CMP_GE_I64_e64;
993   case CmpInst::ICMP_SLT:
994     return Size == 32 ? AMDGPU::V_CMP_LT_I32_e64 : AMDGPU::V_CMP_LT_I64_e64;
995   case CmpInst::ICMP_SLE:
996     return Size == 32 ? AMDGPU::V_CMP_LE_I32_e64 : AMDGPU::V_CMP_LE_I64_e64;
997   case CmpInst::ICMP_UGT:
998     return Size == 32 ? AMDGPU::V_CMP_GT_U32_e64 : AMDGPU::V_CMP_GT_U64_e64;
999   case CmpInst::ICMP_UGE:
1000     return Size == 32 ? AMDGPU::V_CMP_GE_U32_e64 : AMDGPU::V_CMP_GE_U64_e64;
1001   case CmpInst::ICMP_ULT:
1002     return Size == 32 ? AMDGPU::V_CMP_LT_U32_e64 : AMDGPU::V_CMP_LT_U64_e64;
1003   case CmpInst::ICMP_ULE:
1004     return Size == 32 ? AMDGPU::V_CMP_LE_U32_e64 : AMDGPU::V_CMP_LE_U64_e64;
1005   }
1006 }
1007 
getS_CMPOpcode(CmpInst::Predicate P,unsigned Size) const1008 int AMDGPUInstructionSelector::getS_CMPOpcode(CmpInst::Predicate P,
1009                                               unsigned Size) const {
1010   if (Size == 64) {
1011     if (!STI.hasScalarCompareEq64())
1012       return -1;
1013 
1014     switch (P) {
1015     case CmpInst::ICMP_NE:
1016       return AMDGPU::S_CMP_LG_U64;
1017     case CmpInst::ICMP_EQ:
1018       return AMDGPU::S_CMP_EQ_U64;
1019     default:
1020       return -1;
1021     }
1022   }
1023 
1024   if (Size != 32)
1025     return -1;
1026 
1027   switch (P) {
1028   case CmpInst::ICMP_NE:
1029     return AMDGPU::S_CMP_LG_U32;
1030   case CmpInst::ICMP_EQ:
1031     return AMDGPU::S_CMP_EQ_U32;
1032   case CmpInst::ICMP_SGT:
1033     return AMDGPU::S_CMP_GT_I32;
1034   case CmpInst::ICMP_SGE:
1035     return AMDGPU::S_CMP_GE_I32;
1036   case CmpInst::ICMP_SLT:
1037     return AMDGPU::S_CMP_LT_I32;
1038   case CmpInst::ICMP_SLE:
1039     return AMDGPU::S_CMP_LE_I32;
1040   case CmpInst::ICMP_UGT:
1041     return AMDGPU::S_CMP_GT_U32;
1042   case CmpInst::ICMP_UGE:
1043     return AMDGPU::S_CMP_GE_U32;
1044   case CmpInst::ICMP_ULT:
1045     return AMDGPU::S_CMP_LT_U32;
1046   case CmpInst::ICMP_ULE:
1047     return AMDGPU::S_CMP_LE_U32;
1048   default:
1049     llvm_unreachable("Unknown condition code!");
1050   }
1051 }
1052 
selectG_ICMP(MachineInstr & I) const1053 bool AMDGPUInstructionSelector::selectG_ICMP(MachineInstr &I) const {
1054   MachineBasicBlock *BB = I.getParent();
1055   const DebugLoc &DL = I.getDebugLoc();
1056 
1057   Register SrcReg = I.getOperand(2).getReg();
1058   unsigned Size = RBI.getSizeInBits(SrcReg, *MRI, TRI);
1059 
1060   auto Pred = (CmpInst::Predicate)I.getOperand(1).getPredicate();
1061 
1062   Register CCReg = I.getOperand(0).getReg();
1063   if (!isVCC(CCReg, *MRI)) {
1064     int Opcode = getS_CMPOpcode(Pred, Size);
1065     if (Opcode == -1)
1066       return false;
1067     MachineInstr *ICmp = BuildMI(*BB, &I, DL, TII.get(Opcode))
1068             .add(I.getOperand(2))
1069             .add(I.getOperand(3));
1070     BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), CCReg)
1071       .addReg(AMDGPU::SCC);
1072     bool Ret =
1073         constrainSelectedInstRegOperands(*ICmp, TII, TRI, RBI) &&
1074         RBI.constrainGenericRegister(CCReg, AMDGPU::SReg_32RegClass, *MRI);
1075     I.eraseFromParent();
1076     return Ret;
1077   }
1078 
1079   int Opcode = getV_CMPOpcode(Pred, Size);
1080   if (Opcode == -1)
1081     return false;
1082 
1083   MachineInstr *ICmp = BuildMI(*BB, &I, DL, TII.get(Opcode),
1084             I.getOperand(0).getReg())
1085             .add(I.getOperand(2))
1086             .add(I.getOperand(3));
1087   RBI.constrainGenericRegister(ICmp->getOperand(0).getReg(),
1088                                *TRI.getBoolRC(), *MRI);
1089   bool Ret = constrainSelectedInstRegOperands(*ICmp, TII, TRI, RBI);
1090   I.eraseFromParent();
1091   return Ret;
1092 }
1093 
selectIntrinsicIcmp(MachineInstr & I) const1094 bool AMDGPUInstructionSelector::selectIntrinsicIcmp(MachineInstr &I) const {
1095   Register Dst = I.getOperand(0).getReg();
1096   if (isVCC(Dst, *MRI))
1097     return false;
1098 
1099   if (MRI->getType(Dst).getSizeInBits() != STI.getWavefrontSize())
1100     return false;
1101 
1102   MachineBasicBlock *BB = I.getParent();
1103   const DebugLoc &DL = I.getDebugLoc();
1104   Register SrcReg = I.getOperand(2).getReg();
1105   unsigned Size = RBI.getSizeInBits(SrcReg, *MRI, TRI);
1106   auto Pred = static_cast<CmpInst::Predicate>(I.getOperand(4).getImm());
1107 
1108   int Opcode = getV_CMPOpcode(Pred, Size);
1109   if (Opcode == -1)
1110     return false;
1111 
1112   MachineInstr *ICmp = BuildMI(*BB, &I, DL, TII.get(Opcode), Dst)
1113                            .add(I.getOperand(2))
1114                            .add(I.getOperand(3));
1115   RBI.constrainGenericRegister(ICmp->getOperand(0).getReg(), *TRI.getBoolRC(),
1116                                *MRI);
1117   bool Ret = constrainSelectedInstRegOperands(*ICmp, TII, TRI, RBI);
1118   I.eraseFromParent();
1119   return Ret;
1120 }
1121 
selectBallot(MachineInstr & I) const1122 bool AMDGPUInstructionSelector::selectBallot(MachineInstr &I) const {
1123   MachineBasicBlock *BB = I.getParent();
1124   const DebugLoc &DL = I.getDebugLoc();
1125   Register DstReg = I.getOperand(0).getReg();
1126   const unsigned Size = MRI->getType(DstReg).getSizeInBits();
1127   const bool Is64 = Size == 64;
1128 
1129   if (Size != STI.getWavefrontSize())
1130     return false;
1131 
1132   Optional<ValueAndVReg> Arg =
1133       getConstantVRegValWithLookThrough(I.getOperand(2).getReg(), *MRI, true);
1134 
1135   if (Arg.hasValue()) {
1136     const int64_t Value = Arg.getValue().Value.getSExtValue();
1137     if (Value == 0) {
1138       unsigned Opcode = Is64 ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
1139       BuildMI(*BB, &I, DL, TII.get(Opcode), DstReg).addImm(0);
1140     } else if (Value == -1) { // all ones
1141       Register SrcReg = Is64 ? AMDGPU::EXEC : AMDGPU::EXEC_LO;
1142       BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), DstReg).addReg(SrcReg);
1143     } else
1144       return false;
1145   } else {
1146     Register SrcReg = I.getOperand(2).getReg();
1147     BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), DstReg).addReg(SrcReg);
1148   }
1149 
1150   I.eraseFromParent();
1151   return true;
1152 }
1153 
selectRelocConstant(MachineInstr & I) const1154 bool AMDGPUInstructionSelector::selectRelocConstant(MachineInstr &I) const {
1155   Register DstReg = I.getOperand(0).getReg();
1156   const RegisterBank *DstBank = RBI.getRegBank(DstReg, *MRI, TRI);
1157   const TargetRegisterClass *DstRC =
1158     TRI.getRegClassForSizeOnBank(32, *DstBank, *MRI);
1159   if (!DstRC || !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
1160     return false;
1161 
1162   const bool IsVALU = DstBank->getID() == AMDGPU::VGPRRegBankID;
1163 
1164   Module *M = MF->getFunction().getParent();
1165   const MDNode *Metadata = I.getOperand(2).getMetadata();
1166   auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
1167   auto RelocSymbol = cast<GlobalVariable>(
1168     M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
1169 
1170   MachineBasicBlock *BB = I.getParent();
1171   BuildMI(*BB, &I, I.getDebugLoc(),
1172           TII.get(IsVALU ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32), DstReg)
1173     .addGlobalAddress(RelocSymbol, 0, SIInstrInfo::MO_ABS32_LO);
1174 
1175   I.eraseFromParent();
1176   return true;
1177 }
1178 
selectGroupStaticSize(MachineInstr & I) const1179 bool AMDGPUInstructionSelector::selectGroupStaticSize(MachineInstr &I) const {
1180   Triple::OSType OS = MF->getTarget().getTargetTriple().getOS();
1181 
1182   Register DstReg = I.getOperand(0).getReg();
1183   const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
1184   unsigned Mov = DstRB->getID() == AMDGPU::SGPRRegBankID ?
1185     AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1186 
1187   MachineBasicBlock *MBB = I.getParent();
1188   const DebugLoc &DL = I.getDebugLoc();
1189 
1190   auto MIB = BuildMI(*MBB, &I, DL, TII.get(Mov), DstReg);
1191 
1192   if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) {
1193     const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1194     MIB.addImm(MFI->getLDSSize());
1195   } else {
1196     Module *M = MF->getFunction().getParent();
1197     const GlobalValue *GV
1198       = Intrinsic::getDeclaration(M, Intrinsic::amdgcn_groupstaticsize);
1199     MIB.addGlobalAddress(GV, 0, SIInstrInfo::MO_ABS32_LO);
1200   }
1201 
1202   I.eraseFromParent();
1203   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1204 }
1205 
selectReturnAddress(MachineInstr & I) const1206 bool AMDGPUInstructionSelector::selectReturnAddress(MachineInstr &I) const {
1207   MachineBasicBlock *MBB = I.getParent();
1208   MachineFunction &MF = *MBB->getParent();
1209   const DebugLoc &DL = I.getDebugLoc();
1210 
1211   MachineOperand &Dst = I.getOperand(0);
1212   Register DstReg = Dst.getReg();
1213   unsigned Depth = I.getOperand(2).getImm();
1214 
1215   const TargetRegisterClass *RC
1216     = TRI.getConstrainedRegClassForOperand(Dst, *MRI);
1217   if (!RC->hasSubClassEq(&AMDGPU::SGPR_64RegClass) ||
1218       !RBI.constrainGenericRegister(DstReg, *RC, *MRI))
1219     return false;
1220 
1221   // Check for kernel and shader functions
1222   if (Depth != 0 ||
1223       MF.getInfo<SIMachineFunctionInfo>()->isEntryFunction()) {
1224     BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_MOV_B64), DstReg)
1225       .addImm(0);
1226     I.eraseFromParent();
1227     return true;
1228   }
1229 
1230   MachineFrameInfo &MFI = MF.getFrameInfo();
1231   // There is a call to @llvm.returnaddress in this function
1232   MFI.setReturnAddressIsTaken(true);
1233 
1234   // Get the return address reg and mark it as an implicit live-in
1235   Register ReturnAddrReg = TRI.getReturnAddressReg(MF);
1236   Register LiveIn = getFunctionLiveInPhysReg(MF, TII, ReturnAddrReg,
1237                                              AMDGPU::SReg_64RegClass);
1238   BuildMI(*MBB, &I, DL, TII.get(AMDGPU::COPY), DstReg)
1239     .addReg(LiveIn);
1240   I.eraseFromParent();
1241   return true;
1242 }
1243 
selectEndCfIntrinsic(MachineInstr & MI) const1244 bool AMDGPUInstructionSelector::selectEndCfIntrinsic(MachineInstr &MI) const {
1245   // FIXME: Manually selecting to avoid dealiing with the SReg_1 trick
1246   // SelectionDAG uses for wave32 vs wave64.
1247   MachineBasicBlock *BB = MI.getParent();
1248   BuildMI(*BB, &MI, MI.getDebugLoc(), TII.get(AMDGPU::SI_END_CF))
1249       .add(MI.getOperand(1));
1250 
1251   Register Reg = MI.getOperand(1).getReg();
1252   MI.eraseFromParent();
1253 
1254   if (!MRI->getRegClassOrNull(Reg))
1255     MRI->setRegClass(Reg, TRI.getWaveMaskRegClass());
1256   return true;
1257 }
1258 
selectDSOrderedIntrinsic(MachineInstr & MI,Intrinsic::ID IntrID) const1259 bool AMDGPUInstructionSelector::selectDSOrderedIntrinsic(
1260   MachineInstr &MI, Intrinsic::ID IntrID) const {
1261   MachineBasicBlock *MBB = MI.getParent();
1262   MachineFunction *MF = MBB->getParent();
1263   const DebugLoc &DL = MI.getDebugLoc();
1264 
1265   unsigned IndexOperand = MI.getOperand(7).getImm();
1266   bool WaveRelease = MI.getOperand(8).getImm() != 0;
1267   bool WaveDone = MI.getOperand(9).getImm() != 0;
1268 
1269   if (WaveDone && !WaveRelease)
1270     report_fatal_error("ds_ordered_count: wave_done requires wave_release");
1271 
1272   unsigned OrderedCountIndex = IndexOperand & 0x3f;
1273   IndexOperand &= ~0x3f;
1274   unsigned CountDw = 0;
1275 
1276   if (STI.getGeneration() >= AMDGPUSubtarget::GFX10) {
1277     CountDw = (IndexOperand >> 24) & 0xf;
1278     IndexOperand &= ~(0xf << 24);
1279 
1280     if (CountDw < 1 || CountDw > 4) {
1281       report_fatal_error(
1282         "ds_ordered_count: dword count must be between 1 and 4");
1283     }
1284   }
1285 
1286   if (IndexOperand)
1287     report_fatal_error("ds_ordered_count: bad index operand");
1288 
1289   unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
1290   unsigned ShaderType = SIInstrInfo::getDSShaderTypeValue(*MF);
1291 
1292   unsigned Offset0 = OrderedCountIndex << 2;
1293   unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
1294                      (Instruction << 4);
1295 
1296   if (STI.getGeneration() >= AMDGPUSubtarget::GFX10)
1297     Offset1 |= (CountDw - 1) << 6;
1298 
1299   unsigned Offset = Offset0 | (Offset1 << 8);
1300 
1301   Register M0Val = MI.getOperand(2).getReg();
1302   BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
1303     .addReg(M0Val);
1304 
1305   Register DstReg = MI.getOperand(0).getReg();
1306   Register ValReg = MI.getOperand(3).getReg();
1307   MachineInstrBuilder DS =
1308     BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::DS_ORDERED_COUNT), DstReg)
1309       .addReg(ValReg)
1310       .addImm(Offset)
1311       .cloneMemRefs(MI);
1312 
1313   if (!RBI.constrainGenericRegister(M0Val, AMDGPU::SReg_32RegClass, *MRI))
1314     return false;
1315 
1316   bool Ret = constrainSelectedInstRegOperands(*DS, TII, TRI, RBI);
1317   MI.eraseFromParent();
1318   return Ret;
1319 }
1320 
gwsIntrinToOpcode(unsigned IntrID)1321 static unsigned gwsIntrinToOpcode(unsigned IntrID) {
1322   switch (IntrID) {
1323   case Intrinsic::amdgcn_ds_gws_init:
1324     return AMDGPU::DS_GWS_INIT;
1325   case Intrinsic::amdgcn_ds_gws_barrier:
1326     return AMDGPU::DS_GWS_BARRIER;
1327   case Intrinsic::amdgcn_ds_gws_sema_v:
1328     return AMDGPU::DS_GWS_SEMA_V;
1329   case Intrinsic::amdgcn_ds_gws_sema_br:
1330     return AMDGPU::DS_GWS_SEMA_BR;
1331   case Intrinsic::amdgcn_ds_gws_sema_p:
1332     return AMDGPU::DS_GWS_SEMA_P;
1333   case Intrinsic::amdgcn_ds_gws_sema_release_all:
1334     return AMDGPU::DS_GWS_SEMA_RELEASE_ALL;
1335   default:
1336     llvm_unreachable("not a gws intrinsic");
1337   }
1338 }
1339 
selectDSGWSIntrinsic(MachineInstr & MI,Intrinsic::ID IID) const1340 bool AMDGPUInstructionSelector::selectDSGWSIntrinsic(MachineInstr &MI,
1341                                                      Intrinsic::ID IID) const {
1342   if (IID == Intrinsic::amdgcn_ds_gws_sema_release_all &&
1343       !STI.hasGWSSemaReleaseAll())
1344     return false;
1345 
1346   // intrinsic ID, vsrc, offset
1347   const bool HasVSrc = MI.getNumOperands() == 3;
1348   assert(HasVSrc || MI.getNumOperands() == 2);
1349 
1350   Register BaseOffset = MI.getOperand(HasVSrc ? 2 : 1).getReg();
1351   const RegisterBank *OffsetRB = RBI.getRegBank(BaseOffset, *MRI, TRI);
1352   if (OffsetRB->getID() != AMDGPU::SGPRRegBankID)
1353     return false;
1354 
1355   MachineInstr *OffsetDef = getDefIgnoringCopies(BaseOffset, *MRI);
1356   assert(OffsetDef);
1357 
1358   unsigned ImmOffset;
1359 
1360   MachineBasicBlock *MBB = MI.getParent();
1361   const DebugLoc &DL = MI.getDebugLoc();
1362 
1363   MachineInstr *Readfirstlane = nullptr;
1364 
1365   // If we legalized the VGPR input, strip out the readfirstlane to analyze the
1366   // incoming offset, in case there's an add of a constant. We'll have to put it
1367   // back later.
1368   if (OffsetDef->getOpcode() == AMDGPU::V_READFIRSTLANE_B32) {
1369     Readfirstlane = OffsetDef;
1370     BaseOffset = OffsetDef->getOperand(1).getReg();
1371     OffsetDef = getDefIgnoringCopies(BaseOffset, *MRI);
1372   }
1373 
1374   if (OffsetDef->getOpcode() == AMDGPU::G_CONSTANT) {
1375     // If we have a constant offset, try to use the 0 in m0 as the base.
1376     // TODO: Look into changing the default m0 initialization value. If the
1377     // default -1 only set the low 16-bits, we could leave it as-is and add 1 to
1378     // the immediate offset.
1379 
1380     ImmOffset = OffsetDef->getOperand(1).getCImm()->getZExtValue();
1381     BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1382       .addImm(0);
1383   } else {
1384     std::tie(BaseOffset, ImmOffset) =
1385         AMDGPU::getBaseWithConstantOffset(*MRI, BaseOffset);
1386 
1387     if (Readfirstlane) {
1388       // We have the constant offset now, so put the readfirstlane back on the
1389       // variable component.
1390       if (!RBI.constrainGenericRegister(BaseOffset, AMDGPU::VGPR_32RegClass, *MRI))
1391         return false;
1392 
1393       Readfirstlane->getOperand(1).setReg(BaseOffset);
1394       BaseOffset = Readfirstlane->getOperand(0).getReg();
1395     } else {
1396       if (!RBI.constrainGenericRegister(BaseOffset,
1397                                         AMDGPU::SReg_32RegClass, *MRI))
1398         return false;
1399     }
1400 
1401     Register M0Base = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1402     BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::S_LSHL_B32), M0Base)
1403       .addReg(BaseOffset)
1404       .addImm(16);
1405 
1406     BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
1407       .addReg(M0Base);
1408   }
1409 
1410   // The resource id offset is computed as (<isa opaque base> + M0[21:16] +
1411   // offset field) % 64. Some versions of the programming guide omit the m0
1412   // part, or claim it's from offset 0.
1413   auto MIB = BuildMI(*MBB, &MI, DL, TII.get(gwsIntrinToOpcode(IID)));
1414 
1415   if (HasVSrc) {
1416     Register VSrc = MI.getOperand(1).getReg();
1417 
1418     if (STI.needsAlignedVGPRs()) {
1419       // Add implicit aligned super-reg to force alignment on the data operand.
1420       Register Undef = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1421       BuildMI(*MBB, &*MIB, DL, TII.get(AMDGPU::IMPLICIT_DEF), Undef);
1422       Register NewVR =
1423           MRI->createVirtualRegister(&AMDGPU::VReg_64_Align2RegClass);
1424       BuildMI(*MBB, &*MIB, DL, TII.get(AMDGPU::REG_SEQUENCE), NewVR)
1425           .addReg(VSrc, 0, MI.getOperand(1).getSubReg())
1426           .addImm(AMDGPU::sub0)
1427           .addReg(Undef)
1428           .addImm(AMDGPU::sub1);
1429       MIB.addReg(NewVR, 0, AMDGPU::sub0);
1430       MIB.addReg(NewVR, RegState::Implicit);
1431     } else {
1432       MIB.addReg(VSrc);
1433     }
1434 
1435     if (!RBI.constrainGenericRegister(VSrc, AMDGPU::VGPR_32RegClass, *MRI))
1436       return false;
1437   }
1438 
1439   MIB.addImm(ImmOffset)
1440      .cloneMemRefs(MI);
1441 
1442   MI.eraseFromParent();
1443   return true;
1444 }
1445 
selectDSAppendConsume(MachineInstr & MI,bool IsAppend) const1446 bool AMDGPUInstructionSelector::selectDSAppendConsume(MachineInstr &MI,
1447                                                       bool IsAppend) const {
1448   Register PtrBase = MI.getOperand(2).getReg();
1449   LLT PtrTy = MRI->getType(PtrBase);
1450   bool IsGDS = PtrTy.getAddressSpace() == AMDGPUAS::REGION_ADDRESS;
1451 
1452   unsigned Offset;
1453   std::tie(PtrBase, Offset) = selectDS1Addr1OffsetImpl(MI.getOperand(2));
1454 
1455   // TODO: Should this try to look through readfirstlane like GWS?
1456   if (!isDSOffsetLegal(PtrBase, Offset)) {
1457     PtrBase = MI.getOperand(2).getReg();
1458     Offset = 0;
1459   }
1460 
1461   MachineBasicBlock *MBB = MI.getParent();
1462   const DebugLoc &DL = MI.getDebugLoc();
1463   const unsigned Opc = IsAppend ? AMDGPU::DS_APPEND : AMDGPU::DS_CONSUME;
1464 
1465   BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
1466     .addReg(PtrBase);
1467   if (!RBI.constrainGenericRegister(PtrBase, AMDGPU::SReg_32RegClass, *MRI))
1468     return false;
1469 
1470   auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc), MI.getOperand(0).getReg())
1471     .addImm(Offset)
1472     .addImm(IsGDS ? -1 : 0)
1473     .cloneMemRefs(MI);
1474   MI.eraseFromParent();
1475   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1476 }
1477 
selectSBarrier(MachineInstr & MI) const1478 bool AMDGPUInstructionSelector::selectSBarrier(MachineInstr &MI) const {
1479   if (TM.getOptLevel() > CodeGenOpt::None) {
1480     unsigned WGSize = STI.getFlatWorkGroupSizes(MF->getFunction()).second;
1481     if (WGSize <= STI.getWavefrontSize()) {
1482       MachineBasicBlock *MBB = MI.getParent();
1483       const DebugLoc &DL = MI.getDebugLoc();
1484       BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::WAVE_BARRIER));
1485       MI.eraseFromParent();
1486       return true;
1487     }
1488   }
1489   return selectImpl(MI, *CoverageInfo);
1490 }
1491 
parseTexFail(uint64_t TexFailCtrl,bool & TFE,bool & LWE,bool & IsTexFail)1492 static bool parseTexFail(uint64_t TexFailCtrl, bool &TFE, bool &LWE,
1493                          bool &IsTexFail) {
1494   if (TexFailCtrl)
1495     IsTexFail = true;
1496 
1497   TFE = (TexFailCtrl & 0x1) ? 1 : 0;
1498   TexFailCtrl &= ~(uint64_t)0x1;
1499   LWE = (TexFailCtrl & 0x2) ? 1 : 0;
1500   TexFailCtrl &= ~(uint64_t)0x2;
1501 
1502   return TexFailCtrl == 0;
1503 }
1504 
selectImageIntrinsic(MachineInstr & MI,const AMDGPU::ImageDimIntrinsicInfo * Intr) const1505 bool AMDGPUInstructionSelector::selectImageIntrinsic(
1506   MachineInstr &MI, const AMDGPU::ImageDimIntrinsicInfo *Intr) const {
1507   MachineBasicBlock *MBB = MI.getParent();
1508   const DebugLoc &DL = MI.getDebugLoc();
1509 
1510   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1511     AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1512 
1513   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
1514   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
1515       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
1516   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
1517       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
1518   unsigned IntrOpcode = Intr->BaseOpcode;
1519   const bool IsGFX10Plus = AMDGPU::isGFX10Plus(STI);
1520 
1521   const unsigned ArgOffset = MI.getNumExplicitDefs() + 1;
1522 
1523   Register VDataIn, VDataOut;
1524   LLT VDataTy;
1525   int NumVDataDwords = -1;
1526   bool IsD16 = false;
1527 
1528   bool Unorm;
1529   if (!BaseOpcode->Sampler)
1530     Unorm = true;
1531   else
1532     Unorm = MI.getOperand(ArgOffset + Intr->UnormIndex).getImm() != 0;
1533 
1534   bool TFE;
1535   bool LWE;
1536   bool IsTexFail = false;
1537   if (!parseTexFail(MI.getOperand(ArgOffset + Intr->TexFailCtrlIndex).getImm(),
1538                     TFE, LWE, IsTexFail))
1539     return false;
1540 
1541   const int Flags = MI.getOperand(ArgOffset + Intr->NumArgs).getImm();
1542   const bool IsA16 = (Flags & 1) != 0;
1543   const bool IsG16 = (Flags & 2) != 0;
1544 
1545   // A16 implies 16 bit gradients if subtarget doesn't support G16
1546   if (IsA16 && !STI.hasG16() && !IsG16)
1547     return false;
1548 
1549   unsigned DMask = 0;
1550   unsigned DMaskLanes = 0;
1551 
1552   if (BaseOpcode->Atomic) {
1553     VDataOut = MI.getOperand(0).getReg();
1554     VDataIn = MI.getOperand(2).getReg();
1555     LLT Ty = MRI->getType(VDataIn);
1556 
1557     // Be careful to allow atomic swap on 16-bit element vectors.
1558     const bool Is64Bit = BaseOpcode->AtomicX2 ?
1559       Ty.getSizeInBits() == 128 :
1560       Ty.getSizeInBits() == 64;
1561 
1562     if (BaseOpcode->AtomicX2) {
1563       assert(MI.getOperand(3).getReg() == AMDGPU::NoRegister);
1564 
1565       DMask = Is64Bit ? 0xf : 0x3;
1566       NumVDataDwords = Is64Bit ? 4 : 2;
1567     } else {
1568       DMask = Is64Bit ? 0x3 : 0x1;
1569       NumVDataDwords = Is64Bit ? 2 : 1;
1570     }
1571   } else {
1572     DMask = MI.getOperand(ArgOffset + Intr->DMaskIndex).getImm();
1573     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
1574 
1575     // One memoperand is mandatory, except for getresinfo.
1576     // FIXME: Check this in verifier.
1577     if (!MI.memoperands_empty()) {
1578       const MachineMemOperand *MMO = *MI.memoperands_begin();
1579 
1580       // Infer d16 from the memory size, as the register type will be mangled by
1581       // unpacked subtargets, or by TFE.
1582       IsD16 = ((8 * MMO->getSize()) / DMaskLanes) < 32;
1583     }
1584 
1585     if (BaseOpcode->Store) {
1586       VDataIn = MI.getOperand(1).getReg();
1587       VDataTy = MRI->getType(VDataIn);
1588       NumVDataDwords = (VDataTy.getSizeInBits() + 31) / 32;
1589     } else {
1590       VDataOut = MI.getOperand(0).getReg();
1591       VDataTy = MRI->getType(VDataOut);
1592       NumVDataDwords = DMaskLanes;
1593 
1594       if (IsD16 && !STI.hasUnpackedD16VMem())
1595         NumVDataDwords = (DMaskLanes + 1) / 2;
1596     }
1597   }
1598 
1599   // Optimize _L to _LZ when _L is zero
1600   if (LZMappingInfo) {
1601     // The legalizer replaced the register with an immediate 0 if we need to
1602     // change the opcode.
1603     const MachineOperand &Lod = MI.getOperand(ArgOffset + Intr->LodIndex);
1604     if (Lod.isImm()) {
1605       assert(Lod.getImm() == 0);
1606       IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
1607     }
1608   }
1609 
1610   // Optimize _mip away, when 'lod' is zero
1611   if (MIPMappingInfo) {
1612     const MachineOperand &Lod = MI.getOperand(ArgOffset + Intr->MipIndex);
1613     if (Lod.isImm()) {
1614       assert(Lod.getImm() == 0);
1615       IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
1616     }
1617   }
1618 
1619   // Set G16 opcode
1620   if (IsG16 && !IsA16) {
1621     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
1622         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
1623     assert(G16MappingInfo);
1624     IntrOpcode = G16MappingInfo->G16; // set opcode to variant with _g16
1625   }
1626 
1627   // TODO: Check this in verifier.
1628   assert((!IsTexFail || DMaskLanes >= 1) && "should have legalized this");
1629 
1630   unsigned CPol = MI.getOperand(ArgOffset + Intr->CachePolicyIndex).getImm();
1631   if (BaseOpcode->Atomic)
1632     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
1633   if (CPol & ~AMDGPU::CPol::ALL)
1634     return false;
1635 
1636   int NumVAddrRegs = 0;
1637   int NumVAddrDwords = 0;
1638   for (unsigned I = Intr->VAddrStart; I < Intr->VAddrEnd; I++) {
1639     // Skip the $noregs and 0s inserted during legalization.
1640     MachineOperand &AddrOp = MI.getOperand(ArgOffset + I);
1641     if (!AddrOp.isReg())
1642       continue; // XXX - Break?
1643 
1644     Register Addr = AddrOp.getReg();
1645     if (!Addr)
1646       break;
1647 
1648     ++NumVAddrRegs;
1649     NumVAddrDwords += (MRI->getType(Addr).getSizeInBits() + 31) / 32;
1650   }
1651 
1652   // The legalizer preprocessed the intrinsic arguments. If we aren't using
1653   // NSA, these should have beeen packed into a single value in the first
1654   // address register
1655   const bool UseNSA = NumVAddrRegs != 1 && NumVAddrDwords == NumVAddrRegs;
1656   if (UseNSA && !STI.hasFeature(AMDGPU::FeatureNSAEncoding)) {
1657     LLVM_DEBUG(dbgs() << "Trying to use NSA on non-NSA target\n");
1658     return false;
1659   }
1660 
1661   if (IsTexFail)
1662     ++NumVDataDwords;
1663 
1664   int Opcode = -1;
1665   if (IsGFX10Plus) {
1666     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
1667                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
1668                                           : AMDGPU::MIMGEncGfx10Default,
1669                                    NumVDataDwords, NumVAddrDwords);
1670   } else {
1671     if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1672       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
1673                                      NumVDataDwords, NumVAddrDwords);
1674     if (Opcode == -1)
1675       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
1676                                      NumVDataDwords, NumVAddrDwords);
1677   }
1678   assert(Opcode != -1);
1679 
1680   auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opcode))
1681     .cloneMemRefs(MI);
1682 
1683   if (VDataOut) {
1684     if (BaseOpcode->AtomicX2) {
1685       const bool Is64 = MRI->getType(VDataOut).getSizeInBits() == 64;
1686 
1687       Register TmpReg = MRI->createVirtualRegister(
1688         Is64 ? &AMDGPU::VReg_128RegClass : &AMDGPU::VReg_64RegClass);
1689       unsigned SubReg = Is64 ? AMDGPU::sub0_sub1 : AMDGPU::sub0;
1690 
1691       MIB.addDef(TmpReg);
1692       if (!MRI->use_empty(VDataOut)) {
1693         BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), VDataOut)
1694             .addReg(TmpReg, RegState::Kill, SubReg);
1695       }
1696 
1697     } else {
1698       MIB.addDef(VDataOut); // vdata output
1699     }
1700   }
1701 
1702   if (VDataIn)
1703     MIB.addReg(VDataIn); // vdata input
1704 
1705   for (int I = 0; I != NumVAddrRegs; ++I) {
1706     MachineOperand &SrcOp = MI.getOperand(ArgOffset + Intr->VAddrStart + I);
1707     if (SrcOp.isReg()) {
1708       assert(SrcOp.getReg() != 0);
1709       MIB.addReg(SrcOp.getReg());
1710     }
1711   }
1712 
1713   MIB.addReg(MI.getOperand(ArgOffset + Intr->RsrcIndex).getReg());
1714   if (BaseOpcode->Sampler)
1715     MIB.addReg(MI.getOperand(ArgOffset + Intr->SampIndex).getReg());
1716 
1717   MIB.addImm(DMask); // dmask
1718 
1719   if (IsGFX10Plus)
1720     MIB.addImm(DimInfo->Encoding);
1721   MIB.addImm(Unorm);
1722 
1723   MIB.addImm(CPol);
1724   MIB.addImm(IsA16 &&  // a16 or r128
1725              STI.hasFeature(AMDGPU::FeatureR128A16) ? -1 : 0);
1726   if (IsGFX10Plus)
1727     MIB.addImm(IsA16 ? -1 : 0);
1728 
1729   MIB.addImm(TFE); // tfe
1730   MIB.addImm(LWE); // lwe
1731   if (!IsGFX10Plus)
1732     MIB.addImm(DimInfo->DA ? -1 : 0);
1733   if (BaseOpcode->HasD16)
1734     MIB.addImm(IsD16 ? -1 : 0);
1735 
1736   if (IsTexFail) {
1737     // An image load instruction with TFE/LWE only conditionally writes to its
1738     // result registers. Initialize them to zero so that we always get well
1739     // defined result values.
1740     assert(VDataOut && !VDataIn);
1741     Register Tied = MRI->cloneVirtualRegister(VDataOut);
1742     Register Zero = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1743     BuildMI(*MBB, *MIB, DL, TII.get(AMDGPU::V_MOV_B32_e32), Zero)
1744       .addImm(0);
1745     auto Parts = TRI.getRegSplitParts(MRI->getRegClass(Tied), 4);
1746     if (STI.usePRTStrictNull()) {
1747       // With enable-prt-strict-null enabled, initialize all result registers to
1748       // zero.
1749       auto RegSeq =
1750           BuildMI(*MBB, *MIB, DL, TII.get(AMDGPU::REG_SEQUENCE), Tied);
1751       for (auto Sub : Parts)
1752         RegSeq.addReg(Zero).addImm(Sub);
1753     } else {
1754       // With enable-prt-strict-null disabled, only initialize the extra TFE/LWE
1755       // result register.
1756       Register Undef = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1757       BuildMI(*MBB, *MIB, DL, TII.get(AMDGPU::IMPLICIT_DEF), Undef);
1758       auto RegSeq =
1759           BuildMI(*MBB, *MIB, DL, TII.get(AMDGPU::REG_SEQUENCE), Tied);
1760       for (auto Sub : Parts.drop_back(1))
1761         RegSeq.addReg(Undef).addImm(Sub);
1762       RegSeq.addReg(Zero).addImm(Parts.back());
1763     }
1764     MIB.addReg(Tied, RegState::Implicit);
1765     MIB->tieOperands(0, MIB->getNumOperands() - 1);
1766   }
1767 
1768   MI.eraseFromParent();
1769   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1770 }
1771 
selectG_INTRINSIC_W_SIDE_EFFECTS(MachineInstr & I) const1772 bool AMDGPUInstructionSelector::selectG_INTRINSIC_W_SIDE_EFFECTS(
1773     MachineInstr &I) const {
1774   unsigned IntrinsicID = I.getIntrinsicID();
1775   switch (IntrinsicID) {
1776   case Intrinsic::amdgcn_end_cf:
1777     return selectEndCfIntrinsic(I);
1778   case Intrinsic::amdgcn_ds_ordered_add:
1779   case Intrinsic::amdgcn_ds_ordered_swap:
1780     return selectDSOrderedIntrinsic(I, IntrinsicID);
1781   case Intrinsic::amdgcn_ds_gws_init:
1782   case Intrinsic::amdgcn_ds_gws_barrier:
1783   case Intrinsic::amdgcn_ds_gws_sema_v:
1784   case Intrinsic::amdgcn_ds_gws_sema_br:
1785   case Intrinsic::amdgcn_ds_gws_sema_p:
1786   case Intrinsic::amdgcn_ds_gws_sema_release_all:
1787     return selectDSGWSIntrinsic(I, IntrinsicID);
1788   case Intrinsic::amdgcn_ds_append:
1789     return selectDSAppendConsume(I, true);
1790   case Intrinsic::amdgcn_ds_consume:
1791     return selectDSAppendConsume(I, false);
1792   case Intrinsic::amdgcn_s_barrier:
1793     return selectSBarrier(I);
1794   case Intrinsic::amdgcn_global_atomic_fadd:
1795     return selectGlobalAtomicFadd(I, I.getOperand(2), I.getOperand(3));
1796   default: {
1797     return selectImpl(I, *CoverageInfo);
1798   }
1799   }
1800 }
1801 
selectG_SELECT(MachineInstr & I) const1802 bool AMDGPUInstructionSelector::selectG_SELECT(MachineInstr &I) const {
1803   if (selectImpl(I, *CoverageInfo))
1804     return true;
1805 
1806   MachineBasicBlock *BB = I.getParent();
1807   const DebugLoc &DL = I.getDebugLoc();
1808 
1809   Register DstReg = I.getOperand(0).getReg();
1810   unsigned Size = RBI.getSizeInBits(DstReg, *MRI, TRI);
1811   assert(Size <= 32 || Size == 64);
1812   const MachineOperand &CCOp = I.getOperand(1);
1813   Register CCReg = CCOp.getReg();
1814   if (!isVCC(CCReg, *MRI)) {
1815     unsigned SelectOpcode = Size == 64 ? AMDGPU::S_CSELECT_B64 :
1816                                          AMDGPU::S_CSELECT_B32;
1817     MachineInstr *CopySCC = BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), AMDGPU::SCC)
1818             .addReg(CCReg);
1819 
1820     // The generic constrainSelectedInstRegOperands doesn't work for the scc register
1821     // bank, because it does not cover the register class that we used to represent
1822     // for it.  So we need to manually set the register class here.
1823     if (!MRI->getRegClassOrNull(CCReg))
1824         MRI->setRegClass(CCReg, TRI.getConstrainedRegClassForOperand(CCOp, *MRI));
1825     MachineInstr *Select = BuildMI(*BB, &I, DL, TII.get(SelectOpcode), DstReg)
1826             .add(I.getOperand(2))
1827             .add(I.getOperand(3));
1828 
1829     bool Ret = constrainSelectedInstRegOperands(*Select, TII, TRI, RBI) |
1830                constrainSelectedInstRegOperands(*CopySCC, TII, TRI, RBI);
1831     I.eraseFromParent();
1832     return Ret;
1833   }
1834 
1835   // Wide VGPR select should have been split in RegBankSelect.
1836   if (Size > 32)
1837     return false;
1838 
1839   MachineInstr *Select =
1840       BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1841               .addImm(0)
1842               .add(I.getOperand(3))
1843               .addImm(0)
1844               .add(I.getOperand(2))
1845               .add(I.getOperand(1));
1846 
1847   bool Ret = constrainSelectedInstRegOperands(*Select, TII, TRI, RBI);
1848   I.eraseFromParent();
1849   return Ret;
1850 }
1851 
sizeToSubRegIndex(unsigned Size)1852 static int sizeToSubRegIndex(unsigned Size) {
1853   switch (Size) {
1854   case 32:
1855     return AMDGPU::sub0;
1856   case 64:
1857     return AMDGPU::sub0_sub1;
1858   case 96:
1859     return AMDGPU::sub0_sub1_sub2;
1860   case 128:
1861     return AMDGPU::sub0_sub1_sub2_sub3;
1862   case 256:
1863     return AMDGPU::sub0_sub1_sub2_sub3_sub4_sub5_sub6_sub7;
1864   default:
1865     if (Size < 32)
1866       return AMDGPU::sub0;
1867     if (Size > 256)
1868       return -1;
1869     return sizeToSubRegIndex(PowerOf2Ceil(Size));
1870   }
1871 }
1872 
selectG_TRUNC(MachineInstr & I) const1873 bool AMDGPUInstructionSelector::selectG_TRUNC(MachineInstr &I) const {
1874   Register DstReg = I.getOperand(0).getReg();
1875   Register SrcReg = I.getOperand(1).getReg();
1876   const LLT DstTy = MRI->getType(DstReg);
1877   const LLT SrcTy = MRI->getType(SrcReg);
1878   const LLT S1 = LLT::scalar(1);
1879 
1880   const RegisterBank *SrcRB = RBI.getRegBank(SrcReg, *MRI, TRI);
1881   const RegisterBank *DstRB;
1882   if (DstTy == S1) {
1883     // This is a special case. We don't treat s1 for legalization artifacts as
1884     // vcc booleans.
1885     DstRB = SrcRB;
1886   } else {
1887     DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
1888     if (SrcRB != DstRB)
1889       return false;
1890   }
1891 
1892   const bool IsVALU = DstRB->getID() == AMDGPU::VGPRRegBankID;
1893 
1894   unsigned DstSize = DstTy.getSizeInBits();
1895   unsigned SrcSize = SrcTy.getSizeInBits();
1896 
1897   const TargetRegisterClass *SrcRC
1898     = TRI.getRegClassForSizeOnBank(SrcSize, *SrcRB, *MRI);
1899   const TargetRegisterClass *DstRC
1900     = TRI.getRegClassForSizeOnBank(DstSize, *DstRB, *MRI);
1901   if (!SrcRC || !DstRC)
1902     return false;
1903 
1904   if (!RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI) ||
1905       !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI)) {
1906     LLVM_DEBUG(dbgs() << "Failed to constrain G_TRUNC\n");
1907     return false;
1908   }
1909 
1910   if (DstTy == LLT::fixed_vector(2, 16) && SrcTy == LLT::fixed_vector(2, 32)) {
1911     MachineBasicBlock *MBB = I.getParent();
1912     const DebugLoc &DL = I.getDebugLoc();
1913 
1914     Register LoReg = MRI->createVirtualRegister(DstRC);
1915     Register HiReg = MRI->createVirtualRegister(DstRC);
1916     BuildMI(*MBB, I, DL, TII.get(AMDGPU::COPY), LoReg)
1917       .addReg(SrcReg, 0, AMDGPU::sub0);
1918     BuildMI(*MBB, I, DL, TII.get(AMDGPU::COPY), HiReg)
1919       .addReg(SrcReg, 0, AMDGPU::sub1);
1920 
1921     if (IsVALU && STI.hasSDWA()) {
1922       // Write the low 16-bits of the high element into the high 16-bits of the
1923       // low element.
1924       MachineInstr *MovSDWA =
1925         BuildMI(*MBB, I, DL, TII.get(AMDGPU::V_MOV_B32_sdwa), DstReg)
1926         .addImm(0)                             // $src0_modifiers
1927         .addReg(HiReg)                         // $src0
1928         .addImm(0)                             // $clamp
1929         .addImm(AMDGPU::SDWA::WORD_1)          // $dst_sel
1930         .addImm(AMDGPU::SDWA::UNUSED_PRESERVE) // $dst_unused
1931         .addImm(AMDGPU::SDWA::WORD_0)          // $src0_sel
1932         .addReg(LoReg, RegState::Implicit);
1933       MovSDWA->tieOperands(0, MovSDWA->getNumOperands() - 1);
1934     } else {
1935       Register TmpReg0 = MRI->createVirtualRegister(DstRC);
1936       Register TmpReg1 = MRI->createVirtualRegister(DstRC);
1937       Register ImmReg = MRI->createVirtualRegister(DstRC);
1938       if (IsVALU) {
1939         BuildMI(*MBB, I, DL, TII.get(AMDGPU::V_LSHLREV_B32_e64), TmpReg0)
1940           .addImm(16)
1941           .addReg(HiReg);
1942       } else {
1943         BuildMI(*MBB, I, DL, TII.get(AMDGPU::S_LSHL_B32), TmpReg0)
1944           .addReg(HiReg)
1945           .addImm(16);
1946       }
1947 
1948       unsigned MovOpc = IsVALU ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32;
1949       unsigned AndOpc = IsVALU ? AMDGPU::V_AND_B32_e64 : AMDGPU::S_AND_B32;
1950       unsigned OrOpc = IsVALU ? AMDGPU::V_OR_B32_e64 : AMDGPU::S_OR_B32;
1951 
1952       BuildMI(*MBB, I, DL, TII.get(MovOpc), ImmReg)
1953         .addImm(0xffff);
1954       BuildMI(*MBB, I, DL, TII.get(AndOpc), TmpReg1)
1955         .addReg(LoReg)
1956         .addReg(ImmReg);
1957       BuildMI(*MBB, I, DL, TII.get(OrOpc), DstReg)
1958         .addReg(TmpReg0)
1959         .addReg(TmpReg1);
1960     }
1961 
1962     I.eraseFromParent();
1963     return true;
1964   }
1965 
1966   if (!DstTy.isScalar())
1967     return false;
1968 
1969   if (SrcSize > 32) {
1970     int SubRegIdx = sizeToSubRegIndex(DstSize);
1971     if (SubRegIdx == -1)
1972       return false;
1973 
1974     // Deal with weird cases where the class only partially supports the subreg
1975     // index.
1976     const TargetRegisterClass *SrcWithSubRC
1977       = TRI.getSubClassWithSubReg(SrcRC, SubRegIdx);
1978     if (!SrcWithSubRC)
1979       return false;
1980 
1981     if (SrcWithSubRC != SrcRC) {
1982       if (!RBI.constrainGenericRegister(SrcReg, *SrcWithSubRC, *MRI))
1983         return false;
1984     }
1985 
1986     I.getOperand(1).setSubReg(SubRegIdx);
1987   }
1988 
1989   I.setDesc(TII.get(TargetOpcode::COPY));
1990   return true;
1991 }
1992 
1993 /// \returns true if a bitmask for \p Size bits will be an inline immediate.
shouldUseAndMask(unsigned Size,unsigned & Mask)1994 static bool shouldUseAndMask(unsigned Size, unsigned &Mask) {
1995   Mask = maskTrailingOnes<unsigned>(Size);
1996   int SignedMask = static_cast<int>(Mask);
1997   return SignedMask >= -16 && SignedMask <= 64;
1998 }
1999 
2000 // Like RegisterBankInfo::getRegBank, but don't assume vcc for s1.
getArtifactRegBank(Register Reg,const MachineRegisterInfo & MRI,const TargetRegisterInfo & TRI) const2001 const RegisterBank *AMDGPUInstructionSelector::getArtifactRegBank(
2002   Register Reg, const MachineRegisterInfo &MRI,
2003   const TargetRegisterInfo &TRI) const {
2004   const RegClassOrRegBank &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
2005   if (auto *RB = RegClassOrBank.dyn_cast<const RegisterBank *>())
2006     return RB;
2007 
2008   // Ignore the type, since we don't use vcc in artifacts.
2009   if (auto *RC = RegClassOrBank.dyn_cast<const TargetRegisterClass *>())
2010     return &RBI.getRegBankFromRegClass(*RC, LLT());
2011   return nullptr;
2012 }
2013 
selectG_SZA_EXT(MachineInstr & I) const2014 bool AMDGPUInstructionSelector::selectG_SZA_EXT(MachineInstr &I) const {
2015   bool InReg = I.getOpcode() == AMDGPU::G_SEXT_INREG;
2016   bool Signed = I.getOpcode() == AMDGPU::G_SEXT || InReg;
2017   const DebugLoc &DL = I.getDebugLoc();
2018   MachineBasicBlock &MBB = *I.getParent();
2019   const Register DstReg = I.getOperand(0).getReg();
2020   const Register SrcReg = I.getOperand(1).getReg();
2021 
2022   const LLT DstTy = MRI->getType(DstReg);
2023   const LLT SrcTy = MRI->getType(SrcReg);
2024   const unsigned SrcSize = I.getOpcode() == AMDGPU::G_SEXT_INREG ?
2025     I.getOperand(2).getImm() : SrcTy.getSizeInBits();
2026   const unsigned DstSize = DstTy.getSizeInBits();
2027   if (!DstTy.isScalar())
2028     return false;
2029 
2030   // Artifact casts should never use vcc.
2031   const RegisterBank *SrcBank = getArtifactRegBank(SrcReg, *MRI, TRI);
2032 
2033   // FIXME: This should probably be illegal and split earlier.
2034   if (I.getOpcode() == AMDGPU::G_ANYEXT) {
2035     if (DstSize <= 32)
2036       return selectCOPY(I);
2037 
2038     const TargetRegisterClass *SrcRC =
2039         TRI.getRegClassForTypeOnBank(SrcTy, *SrcBank, *MRI);
2040     const RegisterBank *DstBank = RBI.getRegBank(DstReg, *MRI, TRI);
2041     const TargetRegisterClass *DstRC =
2042         TRI.getRegClassForSizeOnBank(DstSize, *DstBank, *MRI);
2043 
2044     Register UndefReg = MRI->createVirtualRegister(SrcRC);
2045     BuildMI(MBB, I, DL, TII.get(AMDGPU::IMPLICIT_DEF), UndefReg);
2046     BuildMI(MBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), DstReg)
2047       .addReg(SrcReg)
2048       .addImm(AMDGPU::sub0)
2049       .addReg(UndefReg)
2050       .addImm(AMDGPU::sub1);
2051     I.eraseFromParent();
2052 
2053     return RBI.constrainGenericRegister(DstReg, *DstRC, *MRI) &&
2054            RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI);
2055   }
2056 
2057   if (SrcBank->getID() == AMDGPU::VGPRRegBankID && DstSize <= 32) {
2058     // 64-bit should have been split up in RegBankSelect
2059 
2060     // Try to use an and with a mask if it will save code size.
2061     unsigned Mask;
2062     if (!Signed && shouldUseAndMask(SrcSize, Mask)) {
2063       MachineInstr *ExtI =
2064       BuildMI(MBB, I, DL, TII.get(AMDGPU::V_AND_B32_e32), DstReg)
2065         .addImm(Mask)
2066         .addReg(SrcReg);
2067       I.eraseFromParent();
2068       return constrainSelectedInstRegOperands(*ExtI, TII, TRI, RBI);
2069     }
2070 
2071     const unsigned BFE = Signed ? AMDGPU::V_BFE_I32_e64 : AMDGPU::V_BFE_U32_e64;
2072     MachineInstr *ExtI =
2073       BuildMI(MBB, I, DL, TII.get(BFE), DstReg)
2074       .addReg(SrcReg)
2075       .addImm(0) // Offset
2076       .addImm(SrcSize); // Width
2077     I.eraseFromParent();
2078     return constrainSelectedInstRegOperands(*ExtI, TII, TRI, RBI);
2079   }
2080 
2081   if (SrcBank->getID() == AMDGPU::SGPRRegBankID && DstSize <= 64) {
2082     const TargetRegisterClass &SrcRC = InReg && DstSize > 32 ?
2083       AMDGPU::SReg_64RegClass : AMDGPU::SReg_32RegClass;
2084     if (!RBI.constrainGenericRegister(SrcReg, SrcRC, *MRI))
2085       return false;
2086 
2087     if (Signed && DstSize == 32 && (SrcSize == 8 || SrcSize == 16)) {
2088       const unsigned SextOpc = SrcSize == 8 ?
2089         AMDGPU::S_SEXT_I32_I8 : AMDGPU::S_SEXT_I32_I16;
2090       BuildMI(MBB, I, DL, TII.get(SextOpc), DstReg)
2091         .addReg(SrcReg);
2092       I.eraseFromParent();
2093       return RBI.constrainGenericRegister(DstReg, AMDGPU::SReg_32RegClass, *MRI);
2094     }
2095 
2096     const unsigned BFE64 = Signed ? AMDGPU::S_BFE_I64 : AMDGPU::S_BFE_U64;
2097     const unsigned BFE32 = Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32;
2098 
2099     // Scalar BFE is encoded as S1[5:0] = offset, S1[22:16]= width.
2100     if (DstSize > 32 && (SrcSize <= 32 || InReg)) {
2101       // We need a 64-bit register source, but the high bits don't matter.
2102       Register ExtReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
2103       Register UndefReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2104       unsigned SubReg = InReg ? AMDGPU::sub0 : 0;
2105 
2106       BuildMI(MBB, I, DL, TII.get(AMDGPU::IMPLICIT_DEF), UndefReg);
2107       BuildMI(MBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), ExtReg)
2108         .addReg(SrcReg, 0, SubReg)
2109         .addImm(AMDGPU::sub0)
2110         .addReg(UndefReg)
2111         .addImm(AMDGPU::sub1);
2112 
2113       BuildMI(MBB, I, DL, TII.get(BFE64), DstReg)
2114         .addReg(ExtReg)
2115         .addImm(SrcSize << 16);
2116 
2117       I.eraseFromParent();
2118       return RBI.constrainGenericRegister(DstReg, AMDGPU::SReg_64RegClass, *MRI);
2119     }
2120 
2121     unsigned Mask;
2122     if (!Signed && shouldUseAndMask(SrcSize, Mask)) {
2123       BuildMI(MBB, I, DL, TII.get(AMDGPU::S_AND_B32), DstReg)
2124         .addReg(SrcReg)
2125         .addImm(Mask);
2126     } else {
2127       BuildMI(MBB, I, DL, TII.get(BFE32), DstReg)
2128         .addReg(SrcReg)
2129         .addImm(SrcSize << 16);
2130     }
2131 
2132     I.eraseFromParent();
2133     return RBI.constrainGenericRegister(DstReg, AMDGPU::SReg_32RegClass, *MRI);
2134   }
2135 
2136   return false;
2137 }
2138 
selectG_CONSTANT(MachineInstr & I) const2139 bool AMDGPUInstructionSelector::selectG_CONSTANT(MachineInstr &I) const {
2140   MachineBasicBlock *BB = I.getParent();
2141   MachineOperand &ImmOp = I.getOperand(1);
2142   Register DstReg = I.getOperand(0).getReg();
2143   unsigned Size = MRI->getType(DstReg).getSizeInBits();
2144 
2145   // The AMDGPU backend only supports Imm operands and not CImm or FPImm.
2146   if (ImmOp.isFPImm()) {
2147     const APInt &Imm = ImmOp.getFPImm()->getValueAPF().bitcastToAPInt();
2148     ImmOp.ChangeToImmediate(Imm.getZExtValue());
2149   } else if (ImmOp.isCImm()) {
2150     ImmOp.ChangeToImmediate(ImmOp.getCImm()->getSExtValue());
2151   } else {
2152     llvm_unreachable("Not supported by g_constants");
2153   }
2154 
2155   const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
2156   const bool IsSgpr = DstRB->getID() == AMDGPU::SGPRRegBankID;
2157 
2158   unsigned Opcode;
2159   if (DstRB->getID() == AMDGPU::VCCRegBankID) {
2160     Opcode = STI.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
2161   } else {
2162     Opcode = IsSgpr ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
2163 
2164     // We should never produce s1 values on banks other than VCC. If the user of
2165     // this already constrained the register, we may incorrectly think it's VCC
2166     // if it wasn't originally.
2167     if (Size == 1)
2168       return false;
2169   }
2170 
2171   if (Size != 64) {
2172     I.setDesc(TII.get(Opcode));
2173     I.addImplicitDefUseOperands(*MF);
2174     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2175   }
2176 
2177   const DebugLoc &DL = I.getDebugLoc();
2178 
2179   APInt Imm(Size, I.getOperand(1).getImm());
2180 
2181   MachineInstr *ResInst;
2182   if (IsSgpr && TII.isInlineConstant(Imm)) {
2183     ResInst = BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_MOV_B64), DstReg)
2184       .addImm(I.getOperand(1).getImm());
2185   } else {
2186     const TargetRegisterClass *RC = IsSgpr ?
2187       &AMDGPU::SReg_32RegClass : &AMDGPU::VGPR_32RegClass;
2188     Register LoReg = MRI->createVirtualRegister(RC);
2189     Register HiReg = MRI->createVirtualRegister(RC);
2190 
2191     BuildMI(*BB, &I, DL, TII.get(Opcode), LoReg)
2192       .addImm(Imm.trunc(32).getZExtValue());
2193 
2194     BuildMI(*BB, &I, DL, TII.get(Opcode), HiReg)
2195       .addImm(Imm.ashr(32).getZExtValue());
2196 
2197     ResInst = BuildMI(*BB, &I, DL, TII.get(AMDGPU::REG_SEQUENCE), DstReg)
2198       .addReg(LoReg)
2199       .addImm(AMDGPU::sub0)
2200       .addReg(HiReg)
2201       .addImm(AMDGPU::sub1);
2202   }
2203 
2204   // We can't call constrainSelectedInstRegOperands here, because it doesn't
2205   // work for target independent opcodes
2206   I.eraseFromParent();
2207   const TargetRegisterClass *DstRC =
2208     TRI.getConstrainedRegClassForOperand(ResInst->getOperand(0), *MRI);
2209   if (!DstRC)
2210     return true;
2211   return RBI.constrainGenericRegister(DstReg, *DstRC, *MRI);
2212 }
2213 
selectG_FNEG(MachineInstr & MI) const2214 bool AMDGPUInstructionSelector::selectG_FNEG(MachineInstr &MI) const {
2215   // Only manually handle the f64 SGPR case.
2216   //
2217   // FIXME: This is a workaround for 2.5 different tablegen problems. Because
2218   // the bit ops theoretically have a second result due to the implicit def of
2219   // SCC, the GlobalISelEmitter is overly conservative and rejects it. Fixing
2220   // that is easy by disabling the check. The result works, but uses a
2221   // nonsensical sreg32orlds_and_sreg_1 regclass.
2222   //
2223   // The DAG emitter is more problematic, and incorrectly adds both S_XOR_B32 to
2224   // the variadic REG_SEQUENCE operands.
2225 
2226   Register Dst = MI.getOperand(0).getReg();
2227   const RegisterBank *DstRB = RBI.getRegBank(Dst, *MRI, TRI);
2228   if (DstRB->getID() != AMDGPU::SGPRRegBankID ||
2229       MRI->getType(Dst) != LLT::scalar(64))
2230     return false;
2231 
2232   Register Src = MI.getOperand(1).getReg();
2233   MachineInstr *Fabs = getOpcodeDef(TargetOpcode::G_FABS, Src, *MRI);
2234   if (Fabs)
2235     Src = Fabs->getOperand(1).getReg();
2236 
2237   if (!RBI.constrainGenericRegister(Src, AMDGPU::SReg_64RegClass, *MRI) ||
2238       !RBI.constrainGenericRegister(Dst, AMDGPU::SReg_64RegClass, *MRI))
2239     return false;
2240 
2241   MachineBasicBlock *BB = MI.getParent();
2242   const DebugLoc &DL = MI.getDebugLoc();
2243   Register LoReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2244   Register HiReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2245   Register ConstReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2246   Register OpReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2247 
2248   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), LoReg)
2249     .addReg(Src, 0, AMDGPU::sub0);
2250   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), HiReg)
2251     .addReg(Src, 0, AMDGPU::sub1);
2252   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_MOV_B32), ConstReg)
2253     .addImm(0x80000000);
2254 
2255   // Set or toggle sign bit.
2256   unsigned Opc = Fabs ? AMDGPU::S_OR_B32 : AMDGPU::S_XOR_B32;
2257   BuildMI(*BB, &MI, DL, TII.get(Opc), OpReg)
2258     .addReg(HiReg)
2259     .addReg(ConstReg);
2260   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::REG_SEQUENCE), Dst)
2261     .addReg(LoReg)
2262     .addImm(AMDGPU::sub0)
2263     .addReg(OpReg)
2264     .addImm(AMDGPU::sub1);
2265   MI.eraseFromParent();
2266   return true;
2267 }
2268 
2269 // FIXME: This is a workaround for the same tablegen problems as G_FNEG
selectG_FABS(MachineInstr & MI) const2270 bool AMDGPUInstructionSelector::selectG_FABS(MachineInstr &MI) const {
2271   Register Dst = MI.getOperand(0).getReg();
2272   const RegisterBank *DstRB = RBI.getRegBank(Dst, *MRI, TRI);
2273   if (DstRB->getID() != AMDGPU::SGPRRegBankID ||
2274       MRI->getType(Dst) != LLT::scalar(64))
2275     return false;
2276 
2277   Register Src = MI.getOperand(1).getReg();
2278   MachineBasicBlock *BB = MI.getParent();
2279   const DebugLoc &DL = MI.getDebugLoc();
2280   Register LoReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2281   Register HiReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2282   Register ConstReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2283   Register OpReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2284 
2285   if (!RBI.constrainGenericRegister(Src, AMDGPU::SReg_64RegClass, *MRI) ||
2286       !RBI.constrainGenericRegister(Dst, AMDGPU::SReg_64RegClass, *MRI))
2287     return false;
2288 
2289   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), LoReg)
2290     .addReg(Src, 0, AMDGPU::sub0);
2291   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), HiReg)
2292     .addReg(Src, 0, AMDGPU::sub1);
2293   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_MOV_B32), ConstReg)
2294     .addImm(0x7fffffff);
2295 
2296   // Clear sign bit.
2297   // TODO: Should this used S_BITSET0_*?
2298   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_AND_B32), OpReg)
2299     .addReg(HiReg)
2300     .addReg(ConstReg);
2301   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::REG_SEQUENCE), Dst)
2302     .addReg(LoReg)
2303     .addImm(AMDGPU::sub0)
2304     .addReg(OpReg)
2305     .addImm(AMDGPU::sub1);
2306 
2307   MI.eraseFromParent();
2308   return true;
2309 }
2310 
isConstant(const MachineInstr & MI)2311 static bool isConstant(const MachineInstr &MI) {
2312   return MI.getOpcode() == TargetOpcode::G_CONSTANT;
2313 }
2314 
getAddrModeInfo(const MachineInstr & Load,const MachineRegisterInfo & MRI,SmallVectorImpl<GEPInfo> & AddrInfo) const2315 void AMDGPUInstructionSelector::getAddrModeInfo(const MachineInstr &Load,
2316     const MachineRegisterInfo &MRI, SmallVectorImpl<GEPInfo> &AddrInfo) const {
2317 
2318   const MachineInstr *PtrMI = MRI.getUniqueVRegDef(Load.getOperand(1).getReg());
2319 
2320   assert(PtrMI);
2321 
2322   if (PtrMI->getOpcode() != TargetOpcode::G_PTR_ADD)
2323     return;
2324 
2325   GEPInfo GEPInfo(*PtrMI);
2326 
2327   for (unsigned i = 1; i != 3; ++i) {
2328     const MachineOperand &GEPOp = PtrMI->getOperand(i);
2329     const MachineInstr *OpDef = MRI.getUniqueVRegDef(GEPOp.getReg());
2330     assert(OpDef);
2331     if (i == 2 && isConstant(*OpDef)) {
2332       // TODO: Could handle constant base + variable offset, but a combine
2333       // probably should have commuted it.
2334       assert(GEPInfo.Imm == 0);
2335       GEPInfo.Imm = OpDef->getOperand(1).getCImm()->getSExtValue();
2336       continue;
2337     }
2338     const RegisterBank *OpBank = RBI.getRegBank(GEPOp.getReg(), MRI, TRI);
2339     if (OpBank->getID() == AMDGPU::SGPRRegBankID)
2340       GEPInfo.SgprParts.push_back(GEPOp.getReg());
2341     else
2342       GEPInfo.VgprParts.push_back(GEPOp.getReg());
2343   }
2344 
2345   AddrInfo.push_back(GEPInfo);
2346   getAddrModeInfo(*PtrMI, MRI, AddrInfo);
2347 }
2348 
isSGPR(Register Reg) const2349 bool AMDGPUInstructionSelector::isSGPR(Register Reg) const {
2350   return RBI.getRegBank(Reg, *MRI, TRI)->getID() == AMDGPU::SGPRRegBankID;
2351 }
2352 
isInstrUniform(const MachineInstr & MI) const2353 bool AMDGPUInstructionSelector::isInstrUniform(const MachineInstr &MI) const {
2354   if (!MI.hasOneMemOperand())
2355     return false;
2356 
2357   const MachineMemOperand *MMO = *MI.memoperands_begin();
2358   const Value *Ptr = MMO->getValue();
2359 
2360   // UndefValue means this is a load of a kernel input.  These are uniform.
2361   // Sometimes LDS instructions have constant pointers.
2362   // If Ptr is null, then that means this mem operand contains a
2363   // PseudoSourceValue like GOT.
2364   if (!Ptr || isa<UndefValue>(Ptr) || isa<Argument>(Ptr) ||
2365       isa<Constant>(Ptr) || isa<GlobalValue>(Ptr))
2366     return true;
2367 
2368   if (MMO->getAddrSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT)
2369     return true;
2370 
2371   const Instruction *I = dyn_cast<Instruction>(Ptr);
2372   return I && I->getMetadata("amdgpu.uniform");
2373 }
2374 
hasVgprParts(ArrayRef<GEPInfo> AddrInfo) const2375 bool AMDGPUInstructionSelector::hasVgprParts(ArrayRef<GEPInfo> AddrInfo) const {
2376   for (const GEPInfo &GEPInfo : AddrInfo) {
2377     if (!GEPInfo.VgprParts.empty())
2378       return true;
2379   }
2380   return false;
2381 }
2382 
initM0(MachineInstr & I) const2383 void AMDGPUInstructionSelector::initM0(MachineInstr &I) const {
2384   const LLT PtrTy = MRI->getType(I.getOperand(1).getReg());
2385   unsigned AS = PtrTy.getAddressSpace();
2386   if ((AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) &&
2387       STI.ldsRequiresM0Init()) {
2388     MachineBasicBlock *BB = I.getParent();
2389 
2390     // If DS instructions require M0 initializtion, insert it before selecting.
2391     BuildMI(*BB, &I, I.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2392       .addImm(-1);
2393   }
2394 }
2395 
selectG_LOAD_STORE_ATOMICRMW(MachineInstr & I) const2396 bool AMDGPUInstructionSelector::selectG_LOAD_STORE_ATOMICRMW(
2397   MachineInstr &I) const {
2398   if (I.getOpcode() == TargetOpcode::G_ATOMICRMW_FADD) {
2399     const LLT PtrTy = MRI->getType(I.getOperand(1).getReg());
2400     unsigned AS = PtrTy.getAddressSpace();
2401     if (AS == AMDGPUAS::GLOBAL_ADDRESS)
2402       return selectGlobalAtomicFadd(I, I.getOperand(1), I.getOperand(2));
2403   }
2404 
2405   initM0(I);
2406   return selectImpl(I, *CoverageInfo);
2407 }
2408 
2409 // TODO: No rtn optimization.
selectG_AMDGPU_ATOMIC_CMPXCHG(MachineInstr & MI) const2410 bool AMDGPUInstructionSelector::selectG_AMDGPU_ATOMIC_CMPXCHG(
2411   MachineInstr &MI) const {
2412   Register PtrReg = MI.getOperand(1).getReg();
2413   const LLT PtrTy = MRI->getType(PtrReg);
2414   if (PtrTy.getAddressSpace() == AMDGPUAS::FLAT_ADDRESS ||
2415       STI.useFlatForGlobal())
2416     return selectImpl(MI, *CoverageInfo);
2417 
2418   Register DstReg = MI.getOperand(0).getReg();
2419   const LLT Ty = MRI->getType(DstReg);
2420   const bool Is64 = Ty.getSizeInBits() == 64;
2421   const unsigned SubReg = Is64 ? AMDGPU::sub0_sub1 : AMDGPU::sub0;
2422   Register TmpReg = MRI->createVirtualRegister(
2423     Is64 ? &AMDGPU::VReg_128RegClass : &AMDGPU::VReg_64RegClass);
2424 
2425   const DebugLoc &DL = MI.getDebugLoc();
2426   MachineBasicBlock *BB = MI.getParent();
2427 
2428   Register VAddr, RSrcReg, SOffset;
2429   int64_t Offset = 0;
2430 
2431   unsigned Opcode;
2432   if (selectMUBUFOffsetImpl(MI.getOperand(1), RSrcReg, SOffset, Offset)) {
2433     Opcode = Is64 ? AMDGPU::BUFFER_ATOMIC_CMPSWAP_X2_OFFSET_RTN :
2434                              AMDGPU::BUFFER_ATOMIC_CMPSWAP_OFFSET_RTN;
2435   } else if (selectMUBUFAddr64Impl(MI.getOperand(1), VAddr,
2436                                    RSrcReg, SOffset, Offset)) {
2437     Opcode = Is64 ? AMDGPU::BUFFER_ATOMIC_CMPSWAP_X2_ADDR64_RTN :
2438                     AMDGPU::BUFFER_ATOMIC_CMPSWAP_ADDR64_RTN;
2439   } else
2440     return selectImpl(MI, *CoverageInfo);
2441 
2442   auto MIB = BuildMI(*BB, &MI, DL, TII.get(Opcode), TmpReg)
2443     .addReg(MI.getOperand(2).getReg());
2444 
2445   if (VAddr)
2446     MIB.addReg(VAddr);
2447 
2448   MIB.addReg(RSrcReg);
2449   if (SOffset)
2450     MIB.addReg(SOffset);
2451   else
2452     MIB.addImm(0);
2453 
2454   MIB.addImm(Offset);
2455   MIB.addImm(AMDGPU::CPol::GLC);
2456   MIB.cloneMemRefs(MI);
2457 
2458   BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), DstReg)
2459     .addReg(TmpReg, RegState::Kill, SubReg);
2460 
2461   MI.eraseFromParent();
2462 
2463   MRI->setRegClass(
2464     DstReg, Is64 ? &AMDGPU::VReg_64RegClass : &AMDGPU::VGPR_32RegClass);
2465   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
2466 }
2467 
selectG_BRCOND(MachineInstr & I) const2468 bool AMDGPUInstructionSelector::selectG_BRCOND(MachineInstr &I) const {
2469   MachineBasicBlock *BB = I.getParent();
2470   MachineOperand &CondOp = I.getOperand(0);
2471   Register CondReg = CondOp.getReg();
2472   const DebugLoc &DL = I.getDebugLoc();
2473 
2474   unsigned BrOpcode;
2475   Register CondPhysReg;
2476   const TargetRegisterClass *ConstrainRC;
2477 
2478   // In SelectionDAG, we inspect the IR block for uniformity metadata to decide
2479   // whether the branch is uniform when selecting the instruction. In
2480   // GlobalISel, we should push that decision into RegBankSelect. Assume for now
2481   // RegBankSelect knows what it's doing if the branch condition is scc, even
2482   // though it currently does not.
2483   if (!isVCC(CondReg, *MRI)) {
2484     if (MRI->getType(CondReg) != LLT::scalar(32))
2485       return false;
2486 
2487     CondPhysReg = AMDGPU::SCC;
2488     BrOpcode = AMDGPU::S_CBRANCH_SCC1;
2489     ConstrainRC = &AMDGPU::SReg_32RegClass;
2490   } else {
2491     // FIXME: Do we have to insert an and with exec here, like in SelectionDAG?
2492     // We sort of know that a VCC producer based on the register bank, that ands
2493     // inactive lanes with 0. What if there was a logical operation with vcc
2494     // producers in different blocks/with different exec masks?
2495     // FIXME: Should scc->vcc copies and with exec?
2496     CondPhysReg = TRI.getVCC();
2497     BrOpcode = AMDGPU::S_CBRANCH_VCCNZ;
2498     ConstrainRC = TRI.getBoolRC();
2499   }
2500 
2501   if (!MRI->getRegClassOrNull(CondReg))
2502     MRI->setRegClass(CondReg, ConstrainRC);
2503 
2504   BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), CondPhysReg)
2505     .addReg(CondReg);
2506   BuildMI(*BB, &I, DL, TII.get(BrOpcode))
2507     .addMBB(I.getOperand(1).getMBB());
2508 
2509   I.eraseFromParent();
2510   return true;
2511 }
2512 
selectG_GLOBAL_VALUE(MachineInstr & I) const2513 bool AMDGPUInstructionSelector::selectG_GLOBAL_VALUE(
2514   MachineInstr &I) const {
2515   Register DstReg = I.getOperand(0).getReg();
2516   const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
2517   const bool IsVGPR = DstRB->getID() == AMDGPU::VGPRRegBankID;
2518   I.setDesc(TII.get(IsVGPR ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32));
2519   if (IsVGPR)
2520     I.addOperand(*MF, MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
2521 
2522   return RBI.constrainGenericRegister(
2523     DstReg, IsVGPR ? AMDGPU::VGPR_32RegClass : AMDGPU::SReg_32RegClass, *MRI);
2524 }
2525 
selectG_PTRMASK(MachineInstr & I) const2526 bool AMDGPUInstructionSelector::selectG_PTRMASK(MachineInstr &I) const {
2527   Register DstReg = I.getOperand(0).getReg();
2528   Register SrcReg = I.getOperand(1).getReg();
2529   Register MaskReg = I.getOperand(2).getReg();
2530   LLT Ty = MRI->getType(DstReg);
2531   LLT MaskTy = MRI->getType(MaskReg);
2532 
2533   const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
2534   const RegisterBank *SrcRB = RBI.getRegBank(SrcReg, *MRI, TRI);
2535   const RegisterBank *MaskRB = RBI.getRegBank(MaskReg, *MRI, TRI);
2536   const bool IsVGPR = DstRB->getID() == AMDGPU::VGPRRegBankID;
2537   if (DstRB != SrcRB) // Should only happen for hand written MIR.
2538     return false;
2539 
2540   unsigned NewOpc = IsVGPR ? AMDGPU::V_AND_B32_e64 : AMDGPU::S_AND_B32;
2541   const TargetRegisterClass &RegRC
2542     = IsVGPR ? AMDGPU::VGPR_32RegClass : AMDGPU::SReg_32RegClass;
2543 
2544   const TargetRegisterClass *DstRC = TRI.getRegClassForTypeOnBank(Ty, *DstRB,
2545                                                                   *MRI);
2546   const TargetRegisterClass *SrcRC = TRI.getRegClassForTypeOnBank(Ty, *SrcRB,
2547                                                                   *MRI);
2548   const TargetRegisterClass *MaskRC =
2549       TRI.getRegClassForTypeOnBank(MaskTy, *MaskRB, *MRI);
2550 
2551   if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI) ||
2552       !RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI) ||
2553       !RBI.constrainGenericRegister(MaskReg, *MaskRC, *MRI))
2554     return false;
2555 
2556   MachineBasicBlock *BB = I.getParent();
2557   const DebugLoc &DL = I.getDebugLoc();
2558   if (Ty.getSizeInBits() == 32) {
2559     assert(MaskTy.getSizeInBits() == 32 &&
2560            "ptrmask should have been narrowed during legalize");
2561 
2562     BuildMI(*BB, &I, DL, TII.get(NewOpc), DstReg)
2563       .addReg(SrcReg)
2564       .addReg(MaskReg);
2565     I.eraseFromParent();
2566     return true;
2567   }
2568 
2569   Register HiReg = MRI->createVirtualRegister(&RegRC);
2570   Register LoReg = MRI->createVirtualRegister(&RegRC);
2571 
2572   // Extract the subregisters from the source pointer.
2573   BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), LoReg)
2574     .addReg(SrcReg, 0, AMDGPU::sub0);
2575   BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), HiReg)
2576     .addReg(SrcReg, 0, AMDGPU::sub1);
2577 
2578   Register MaskedLo, MaskedHi;
2579 
2580   // Try to avoid emitting a bit operation when we only need to touch half of
2581   // the 64-bit pointer.
2582   APInt MaskOnes = KnownBits->getKnownOnes(MaskReg).zextOrSelf(64);
2583 
2584   const APInt MaskHi32 = APInt::getHighBitsSet(64, 32);
2585   const APInt MaskLo32 = APInt::getLowBitsSet(64, 32);
2586   if ((MaskOnes & MaskLo32) == MaskLo32) {
2587     // If all the bits in the low half are 1, we only need a copy for it.
2588     MaskedLo = LoReg;
2589   } else {
2590     // Extract the mask subregister and apply the and.
2591     Register MaskLo = MRI->createVirtualRegister(&RegRC);
2592     MaskedLo = MRI->createVirtualRegister(&RegRC);
2593 
2594     BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), MaskLo)
2595       .addReg(MaskReg, 0, AMDGPU::sub0);
2596     BuildMI(*BB, &I, DL, TII.get(NewOpc), MaskedLo)
2597       .addReg(LoReg)
2598       .addReg(MaskLo);
2599   }
2600 
2601   if ((MaskOnes & MaskHi32) == MaskHi32) {
2602     // If all the bits in the high half are 1, we only need a copy for it.
2603     MaskedHi = HiReg;
2604   } else {
2605     Register MaskHi = MRI->createVirtualRegister(&RegRC);
2606     MaskedHi = MRI->createVirtualRegister(&RegRC);
2607 
2608     BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), MaskHi)
2609       .addReg(MaskReg, 0, AMDGPU::sub1);
2610     BuildMI(*BB, &I, DL, TII.get(NewOpc), MaskedHi)
2611       .addReg(HiReg)
2612       .addReg(MaskHi);
2613   }
2614 
2615   BuildMI(*BB, &I, DL, TII.get(AMDGPU::REG_SEQUENCE), DstReg)
2616     .addReg(MaskedLo)
2617     .addImm(AMDGPU::sub0)
2618     .addReg(MaskedHi)
2619     .addImm(AMDGPU::sub1);
2620   I.eraseFromParent();
2621   return true;
2622 }
2623 
2624 /// Return the register to use for the index value, and the subregister to use
2625 /// for the indirectly accessed register.
2626 static std::pair<Register, unsigned>
computeIndirectRegIndex(MachineRegisterInfo & MRI,const SIRegisterInfo & TRI,const TargetRegisterClass * SuperRC,Register IdxReg,unsigned EltSize)2627 computeIndirectRegIndex(MachineRegisterInfo &MRI,
2628                         const SIRegisterInfo &TRI,
2629                         const TargetRegisterClass *SuperRC,
2630                         Register IdxReg,
2631                         unsigned EltSize) {
2632   Register IdxBaseReg;
2633   int Offset;
2634 
2635   std::tie(IdxBaseReg, Offset) = AMDGPU::getBaseWithConstantOffset(MRI, IdxReg);
2636   if (IdxBaseReg == AMDGPU::NoRegister) {
2637     // This will happen if the index is a known constant. This should ordinarily
2638     // be legalized out, but handle it as a register just in case.
2639     assert(Offset == 0);
2640     IdxBaseReg = IdxReg;
2641   }
2642 
2643   ArrayRef<int16_t> SubRegs = TRI.getRegSplitParts(SuperRC, EltSize);
2644 
2645   // Skip out of bounds offsets, or else we would end up using an undefined
2646   // register.
2647   if (static_cast<unsigned>(Offset) >= SubRegs.size())
2648     return std::make_pair(IdxReg, SubRegs[0]);
2649   return std::make_pair(IdxBaseReg, SubRegs[Offset]);
2650 }
2651 
selectG_EXTRACT_VECTOR_ELT(MachineInstr & MI) const2652 bool AMDGPUInstructionSelector::selectG_EXTRACT_VECTOR_ELT(
2653   MachineInstr &MI) const {
2654   Register DstReg = MI.getOperand(0).getReg();
2655   Register SrcReg = MI.getOperand(1).getReg();
2656   Register IdxReg = MI.getOperand(2).getReg();
2657 
2658   LLT DstTy = MRI->getType(DstReg);
2659   LLT SrcTy = MRI->getType(SrcReg);
2660 
2661   const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
2662   const RegisterBank *SrcRB = RBI.getRegBank(SrcReg, *MRI, TRI);
2663   const RegisterBank *IdxRB = RBI.getRegBank(IdxReg, *MRI, TRI);
2664 
2665   // The index must be scalar. If it wasn't RegBankSelect should have moved this
2666   // into a waterfall loop.
2667   if (IdxRB->getID() != AMDGPU::SGPRRegBankID)
2668     return false;
2669 
2670   const TargetRegisterClass *SrcRC = TRI.getRegClassForTypeOnBank(SrcTy, *SrcRB,
2671                                                                   *MRI);
2672   const TargetRegisterClass *DstRC = TRI.getRegClassForTypeOnBank(DstTy, *DstRB,
2673                                                                   *MRI);
2674   if (!SrcRC || !DstRC)
2675     return false;
2676   if (!RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI) ||
2677       !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI) ||
2678       !RBI.constrainGenericRegister(IdxReg, AMDGPU::SReg_32RegClass, *MRI))
2679     return false;
2680 
2681   MachineBasicBlock *BB = MI.getParent();
2682   const DebugLoc &DL = MI.getDebugLoc();
2683   const bool Is64 = DstTy.getSizeInBits() == 64;
2684 
2685   unsigned SubReg;
2686   std::tie(IdxReg, SubReg) = computeIndirectRegIndex(*MRI, TRI, SrcRC, IdxReg,
2687                                                      DstTy.getSizeInBits() / 8);
2688 
2689   if (SrcRB->getID() == AMDGPU::SGPRRegBankID) {
2690     if (DstTy.getSizeInBits() != 32 && !Is64)
2691       return false;
2692 
2693     BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
2694       .addReg(IdxReg);
2695 
2696     unsigned Opc = Is64 ? AMDGPU::S_MOVRELS_B64 : AMDGPU::S_MOVRELS_B32;
2697     BuildMI(*BB, &MI, DL, TII.get(Opc), DstReg)
2698       .addReg(SrcReg, 0, SubReg)
2699       .addReg(SrcReg, RegState::Implicit);
2700     MI.eraseFromParent();
2701     return true;
2702   }
2703 
2704   if (SrcRB->getID() != AMDGPU::VGPRRegBankID || DstTy.getSizeInBits() != 32)
2705     return false;
2706 
2707   if (!STI.useVGPRIndexMode()) {
2708     BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
2709       .addReg(IdxReg);
2710     BuildMI(*BB, &MI, DL, TII.get(AMDGPU::V_MOVRELS_B32_e32), DstReg)
2711       .addReg(SrcReg, 0, SubReg)
2712       .addReg(SrcReg, RegState::Implicit);
2713     MI.eraseFromParent();
2714     return true;
2715   }
2716 
2717   const MCInstrDesc &GPRIDXDesc =
2718       TII.getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*SrcRC), true);
2719   BuildMI(*BB, MI, DL, GPRIDXDesc, DstReg)
2720       .addReg(SrcReg)
2721       .addReg(IdxReg)
2722       .addImm(SubReg);
2723 
2724   MI.eraseFromParent();
2725   return true;
2726 }
2727 
2728 // TODO: Fold insert_vector_elt (extract_vector_elt) into movrelsd
selectG_INSERT_VECTOR_ELT(MachineInstr & MI) const2729 bool AMDGPUInstructionSelector::selectG_INSERT_VECTOR_ELT(
2730   MachineInstr &MI) const {
2731   Register DstReg = MI.getOperand(0).getReg();
2732   Register VecReg = MI.getOperand(1).getReg();
2733   Register ValReg = MI.getOperand(2).getReg();
2734   Register IdxReg = MI.getOperand(3).getReg();
2735 
2736   LLT VecTy = MRI->getType(DstReg);
2737   LLT ValTy = MRI->getType(ValReg);
2738   unsigned VecSize = VecTy.getSizeInBits();
2739   unsigned ValSize = ValTy.getSizeInBits();
2740 
2741   const RegisterBank *VecRB = RBI.getRegBank(VecReg, *MRI, TRI);
2742   const RegisterBank *ValRB = RBI.getRegBank(ValReg, *MRI, TRI);
2743   const RegisterBank *IdxRB = RBI.getRegBank(IdxReg, *MRI, TRI);
2744 
2745   assert(VecTy.getElementType() == ValTy);
2746 
2747   // The index must be scalar. If it wasn't RegBankSelect should have moved this
2748   // into a waterfall loop.
2749   if (IdxRB->getID() != AMDGPU::SGPRRegBankID)
2750     return false;
2751 
2752   const TargetRegisterClass *VecRC = TRI.getRegClassForTypeOnBank(VecTy, *VecRB,
2753                                                                   *MRI);
2754   const TargetRegisterClass *ValRC = TRI.getRegClassForTypeOnBank(ValTy, *ValRB,
2755                                                                   *MRI);
2756 
2757   if (!RBI.constrainGenericRegister(VecReg, *VecRC, *MRI) ||
2758       !RBI.constrainGenericRegister(DstReg, *VecRC, *MRI) ||
2759       !RBI.constrainGenericRegister(ValReg, *ValRC, *MRI) ||
2760       !RBI.constrainGenericRegister(IdxReg, AMDGPU::SReg_32RegClass, *MRI))
2761     return false;
2762 
2763   if (VecRB->getID() == AMDGPU::VGPRRegBankID && ValSize != 32)
2764     return false;
2765 
2766   unsigned SubReg;
2767   std::tie(IdxReg, SubReg) = computeIndirectRegIndex(*MRI, TRI, VecRC, IdxReg,
2768                                                      ValSize / 8);
2769 
2770   const bool IndexMode = VecRB->getID() == AMDGPU::VGPRRegBankID &&
2771                          STI.useVGPRIndexMode();
2772 
2773   MachineBasicBlock *BB = MI.getParent();
2774   const DebugLoc &DL = MI.getDebugLoc();
2775 
2776   if (!IndexMode) {
2777     BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
2778       .addReg(IdxReg);
2779 
2780     const MCInstrDesc &RegWriteOp = TII.getIndirectRegWriteMovRelPseudo(
2781         VecSize, ValSize, VecRB->getID() == AMDGPU::SGPRRegBankID);
2782     BuildMI(*BB, MI, DL, RegWriteOp, DstReg)
2783         .addReg(VecReg)
2784         .addReg(ValReg)
2785         .addImm(SubReg);
2786     MI.eraseFromParent();
2787     return true;
2788   }
2789 
2790   const MCInstrDesc &GPRIDXDesc =
2791       TII.getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
2792   BuildMI(*BB, MI, DL, GPRIDXDesc, DstReg)
2793       .addReg(VecReg)
2794       .addReg(ValReg)
2795       .addReg(IdxReg)
2796       .addImm(SubReg);
2797 
2798   MI.eraseFromParent();
2799   return true;
2800 }
2801 
isZeroOrUndef(int X)2802 static bool isZeroOrUndef(int X) {
2803   return X == 0 || X == -1;
2804 }
2805 
isOneOrUndef(int X)2806 static bool isOneOrUndef(int X) {
2807   return X == 1 || X == -1;
2808 }
2809 
isZeroOrOneOrUndef(int X)2810 static bool isZeroOrOneOrUndef(int X) {
2811   return X == 0 || X == 1 || X == -1;
2812 }
2813 
2814 // Normalize a VOP3P shuffle mask to refer to the low/high half of a single
2815 // 32-bit register.
normalizeVOP3PMask(int NewMask[2],Register Src0,Register Src1,ArrayRef<int> Mask)2816 static Register normalizeVOP3PMask(int NewMask[2], Register Src0, Register Src1,
2817                                    ArrayRef<int> Mask) {
2818   NewMask[0] = Mask[0];
2819   NewMask[1] = Mask[1];
2820   if (isZeroOrOneOrUndef(Mask[0]) && isZeroOrOneOrUndef(Mask[1]))
2821     return Src0;
2822 
2823   assert(NewMask[0] == 2 || NewMask[0] == 3 || NewMask[0] == -1);
2824   assert(NewMask[1] == 2 || NewMask[1] == 3 || NewMask[1] == -1);
2825 
2826   // Shift the mask inputs to be 0/1;
2827   NewMask[0] = NewMask[0] == -1 ? -1 : NewMask[0] - 2;
2828   NewMask[1] = NewMask[1] == -1 ? -1 : NewMask[1] - 2;
2829   return Src1;
2830 }
2831 
2832 // This is only legal with VOP3P instructions as an aid to op_sel matching.
selectG_SHUFFLE_VECTOR(MachineInstr & MI) const2833 bool AMDGPUInstructionSelector::selectG_SHUFFLE_VECTOR(
2834   MachineInstr &MI) const {
2835   Register DstReg = MI.getOperand(0).getReg();
2836   Register Src0Reg = MI.getOperand(1).getReg();
2837   Register Src1Reg = MI.getOperand(2).getReg();
2838   ArrayRef<int> ShufMask = MI.getOperand(3).getShuffleMask();
2839 
2840   const LLT V2S16 = LLT::fixed_vector(2, 16);
2841   if (MRI->getType(DstReg) != V2S16 || MRI->getType(Src0Reg) != V2S16)
2842     return false;
2843 
2844   if (!AMDGPU::isLegalVOP3PShuffleMask(ShufMask))
2845     return false;
2846 
2847   assert(ShufMask.size() == 2);
2848   assert(STI.hasSDWA() && "no target has VOP3P but not SDWA");
2849 
2850   MachineBasicBlock *MBB = MI.getParent();
2851   const DebugLoc &DL = MI.getDebugLoc();
2852 
2853   const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
2854   const bool IsVALU = DstRB->getID() == AMDGPU::VGPRRegBankID;
2855   const TargetRegisterClass &RC = IsVALU ?
2856     AMDGPU::VGPR_32RegClass : AMDGPU::SReg_32RegClass;
2857 
2858   // Handle the degenerate case which should have folded out.
2859   if (ShufMask[0] == -1 && ShufMask[1] == -1) {
2860     BuildMI(*MBB, MI, DL, TII.get(AMDGPU::IMPLICIT_DEF), DstReg);
2861 
2862     MI.eraseFromParent();
2863     return RBI.constrainGenericRegister(DstReg, RC, *MRI);
2864   }
2865 
2866   // A legal VOP3P mask only reads one of the sources.
2867   int Mask[2];
2868   Register SrcVec = normalizeVOP3PMask(Mask, Src0Reg, Src1Reg, ShufMask);
2869 
2870   if (!RBI.constrainGenericRegister(DstReg, RC, *MRI) ||
2871       !RBI.constrainGenericRegister(SrcVec, RC, *MRI))
2872     return false;
2873 
2874   // TODO: This also should have been folded out
2875   if (isZeroOrUndef(Mask[0]) && isOneOrUndef(Mask[1])) {
2876     BuildMI(*MBB, MI, DL, TII.get(AMDGPU::COPY), DstReg)
2877       .addReg(SrcVec);
2878 
2879     MI.eraseFromParent();
2880     return true;
2881   }
2882 
2883   if (Mask[0] == 1 && Mask[1] == -1) {
2884     if (IsVALU) {
2885       BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_LSHRREV_B32_e64), DstReg)
2886         .addImm(16)
2887         .addReg(SrcVec);
2888     } else {
2889       BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_LSHR_B32), DstReg)
2890         .addReg(SrcVec)
2891         .addImm(16);
2892     }
2893   } else if (Mask[0] == -1 && Mask[1] == 0) {
2894     if (IsVALU) {
2895       BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_LSHLREV_B32_e64), DstReg)
2896         .addImm(16)
2897         .addReg(SrcVec);
2898     } else {
2899       BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_LSHL_B32), DstReg)
2900         .addReg(SrcVec)
2901         .addImm(16);
2902     }
2903   } else if (Mask[0] == 0 && Mask[1] == 0) {
2904     if (IsVALU) {
2905       // Write low half of the register into the high half.
2906       MachineInstr *MovSDWA =
2907         BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_MOV_B32_sdwa), DstReg)
2908         .addImm(0)                             // $src0_modifiers
2909         .addReg(SrcVec)                        // $src0
2910         .addImm(0)                             // $clamp
2911         .addImm(AMDGPU::SDWA::WORD_1)          // $dst_sel
2912         .addImm(AMDGPU::SDWA::UNUSED_PRESERVE) // $dst_unused
2913         .addImm(AMDGPU::SDWA::WORD_0)          // $src0_sel
2914         .addReg(SrcVec, RegState::Implicit);
2915       MovSDWA->tieOperands(0, MovSDWA->getNumOperands() - 1);
2916     } else {
2917       BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_PACK_LL_B32_B16), DstReg)
2918         .addReg(SrcVec)
2919         .addReg(SrcVec);
2920     }
2921   } else if (Mask[0] == 1 && Mask[1] == 1) {
2922     if (IsVALU) {
2923       // Write high half of the register into the low half.
2924       MachineInstr *MovSDWA =
2925         BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_MOV_B32_sdwa), DstReg)
2926         .addImm(0)                             // $src0_modifiers
2927         .addReg(SrcVec)                        // $src0
2928         .addImm(0)                             // $clamp
2929         .addImm(AMDGPU::SDWA::WORD_0)          // $dst_sel
2930         .addImm(AMDGPU::SDWA::UNUSED_PRESERVE) // $dst_unused
2931         .addImm(AMDGPU::SDWA::WORD_1)          // $src0_sel
2932         .addReg(SrcVec, RegState::Implicit);
2933       MovSDWA->tieOperands(0, MovSDWA->getNumOperands() - 1);
2934     } else {
2935       BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_PACK_HH_B32_B16), DstReg)
2936         .addReg(SrcVec)
2937         .addReg(SrcVec);
2938     }
2939   } else if (Mask[0] == 1 && Mask[1] == 0) {
2940     if (IsVALU) {
2941       BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_ALIGNBIT_B32_e64), DstReg)
2942         .addReg(SrcVec)
2943         .addReg(SrcVec)
2944         .addImm(16);
2945     } else {
2946       Register TmpReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2947       BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_LSHR_B32), TmpReg)
2948         .addReg(SrcVec)
2949         .addImm(16);
2950       BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_PACK_LL_B32_B16), DstReg)
2951         .addReg(TmpReg)
2952         .addReg(SrcVec);
2953     }
2954   } else
2955     llvm_unreachable("all shuffle masks should be handled");
2956 
2957   MI.eraseFromParent();
2958   return true;
2959 }
2960 
selectAMDGPU_BUFFER_ATOMIC_FADD(MachineInstr & MI) const2961 bool AMDGPUInstructionSelector::selectAMDGPU_BUFFER_ATOMIC_FADD(
2962   MachineInstr &MI) const {
2963   if (STI.hasGFX90AInsts())
2964     return selectImpl(MI, *CoverageInfo);
2965 
2966   MachineBasicBlock *MBB = MI.getParent();
2967   const DebugLoc &DL = MI.getDebugLoc();
2968 
2969   if (!MRI->use_nodbg_empty(MI.getOperand(0).getReg())) {
2970     Function &F = MBB->getParent()->getFunction();
2971     DiagnosticInfoUnsupported
2972       NoFpRet(F, "return versions of fp atomics not supported",
2973               MI.getDebugLoc(), DS_Error);
2974     F.getContext().diagnose(NoFpRet);
2975     return false;
2976   }
2977 
2978   // FIXME: This is only needed because tablegen requires number of dst operands
2979   // in match and replace pattern to be the same. Otherwise patterns can be
2980   // exported from SDag path.
2981   MachineOperand &VDataIn = MI.getOperand(1);
2982   MachineOperand &VIndex = MI.getOperand(3);
2983   MachineOperand &VOffset = MI.getOperand(4);
2984   MachineOperand &SOffset = MI.getOperand(5);
2985   int16_t Offset = MI.getOperand(6).getImm();
2986 
2987   bool HasVOffset = !isOperandImmEqual(VOffset, 0, *MRI);
2988   bool HasVIndex = !isOperandImmEqual(VIndex, 0, *MRI);
2989 
2990   unsigned Opcode;
2991   if (HasVOffset) {
2992     Opcode = HasVIndex ? AMDGPU::BUFFER_ATOMIC_ADD_F32_BOTHEN
2993                        : AMDGPU::BUFFER_ATOMIC_ADD_F32_OFFEN;
2994   } else {
2995     Opcode = HasVIndex ? AMDGPU::BUFFER_ATOMIC_ADD_F32_IDXEN
2996                        : AMDGPU::BUFFER_ATOMIC_ADD_F32_OFFSET;
2997   }
2998 
2999   if (MRI->getType(VDataIn.getReg()).isVector()) {
3000     switch (Opcode) {
3001     case AMDGPU::BUFFER_ATOMIC_ADD_F32_BOTHEN:
3002       Opcode = AMDGPU::BUFFER_ATOMIC_PK_ADD_F16_BOTHEN;
3003       break;
3004     case AMDGPU::BUFFER_ATOMIC_ADD_F32_OFFEN:
3005       Opcode = AMDGPU::BUFFER_ATOMIC_PK_ADD_F16_OFFEN;
3006       break;
3007     case AMDGPU::BUFFER_ATOMIC_ADD_F32_IDXEN:
3008       Opcode = AMDGPU::BUFFER_ATOMIC_PK_ADD_F16_IDXEN;
3009       break;
3010     case AMDGPU::BUFFER_ATOMIC_ADD_F32_OFFSET:
3011       Opcode = AMDGPU::BUFFER_ATOMIC_PK_ADD_F16_OFFSET;
3012       break;
3013     }
3014   }
3015 
3016   auto I = BuildMI(*MBB, MI, DL, TII.get(Opcode));
3017   I.add(VDataIn);
3018 
3019   if (Opcode == AMDGPU::BUFFER_ATOMIC_ADD_F32_BOTHEN ||
3020       Opcode == AMDGPU::BUFFER_ATOMIC_PK_ADD_F16_BOTHEN) {
3021     Register IdxReg = MRI->createVirtualRegister(TRI.getVGPR64Class());
3022     BuildMI(*MBB, &*I, DL, TII.get(AMDGPU::REG_SEQUENCE), IdxReg)
3023       .addReg(VIndex.getReg())
3024       .addImm(AMDGPU::sub0)
3025       .addReg(VOffset.getReg())
3026       .addImm(AMDGPU::sub1);
3027 
3028     I.addReg(IdxReg);
3029   } else if (HasVIndex) {
3030     I.add(VIndex);
3031   } else if (HasVOffset) {
3032     I.add(VOffset);
3033   }
3034 
3035   I.add(MI.getOperand(2)); // rsrc
3036   I.add(SOffset);
3037   I.addImm(Offset);
3038   I.addImm(MI.getOperand(7).getImm()); // cpol
3039   I.cloneMemRefs(MI);
3040 
3041   MI.eraseFromParent();
3042 
3043   return true;
3044 }
3045 
selectGlobalAtomicFadd(MachineInstr & MI,MachineOperand & AddrOp,MachineOperand & DataOp) const3046 bool AMDGPUInstructionSelector::selectGlobalAtomicFadd(
3047   MachineInstr &MI, MachineOperand &AddrOp, MachineOperand &DataOp) const {
3048 
3049   if (STI.hasGFX90AInsts()) {
3050     // gfx90a adds return versions of the global atomic fadd instructions so no
3051     // special handling is required.
3052     return selectImpl(MI, *CoverageInfo);
3053   }
3054 
3055   MachineBasicBlock *MBB = MI.getParent();
3056   const DebugLoc &DL = MI.getDebugLoc();
3057 
3058   if (!MRI->use_nodbg_empty(MI.getOperand(0).getReg())) {
3059     Function &F = MBB->getParent()->getFunction();
3060     DiagnosticInfoUnsupported
3061       NoFpRet(F, "return versions of fp atomics not supported",
3062               MI.getDebugLoc(), DS_Error);
3063     F.getContext().diagnose(NoFpRet);
3064     return false;
3065   }
3066 
3067   // FIXME: This is only needed because tablegen requires number of dst operands
3068   // in match and replace pattern to be the same. Otherwise patterns can be
3069   // exported from SDag path.
3070   auto Addr = selectFlatOffsetImpl(AddrOp, SIInstrFlags::FlatGlobal);
3071 
3072   Register Data = DataOp.getReg();
3073   const unsigned Opc = MRI->getType(Data).isVector() ?
3074     AMDGPU::GLOBAL_ATOMIC_PK_ADD_F16 : AMDGPU::GLOBAL_ATOMIC_ADD_F32;
3075   auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc))
3076     .addReg(Addr.first)
3077     .addReg(Data)
3078     .addImm(Addr.second)
3079     .addImm(0) // cpol
3080     .cloneMemRefs(MI);
3081 
3082   MI.eraseFromParent();
3083   return constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
3084 }
3085 
selectBVHIntrinsic(MachineInstr & MI) const3086 bool AMDGPUInstructionSelector::selectBVHIntrinsic(MachineInstr &MI) const{
3087   MI.setDesc(TII.get(MI.getOperand(1).getImm()));
3088   MI.RemoveOperand(1);
3089   MI.addImplicitDefUseOperands(*MI.getParent()->getParent());
3090   return true;
3091 }
3092 
select(MachineInstr & I)3093 bool AMDGPUInstructionSelector::select(MachineInstr &I) {
3094   if (I.isPHI())
3095     return selectPHI(I);
3096 
3097   if (!I.isPreISelOpcode()) {
3098     if (I.isCopy())
3099       return selectCOPY(I);
3100     return true;
3101   }
3102 
3103   switch (I.getOpcode()) {
3104   case TargetOpcode::G_AND:
3105   case TargetOpcode::G_OR:
3106   case TargetOpcode::G_XOR:
3107     if (selectImpl(I, *CoverageInfo))
3108       return true;
3109     return selectG_AND_OR_XOR(I);
3110   case TargetOpcode::G_ADD:
3111   case TargetOpcode::G_SUB:
3112     if (selectImpl(I, *CoverageInfo))
3113       return true;
3114     return selectG_ADD_SUB(I);
3115   case TargetOpcode::G_UADDO:
3116   case TargetOpcode::G_USUBO:
3117   case TargetOpcode::G_UADDE:
3118   case TargetOpcode::G_USUBE:
3119     return selectG_UADDO_USUBO_UADDE_USUBE(I);
3120   case TargetOpcode::G_INTTOPTR:
3121   case TargetOpcode::G_BITCAST:
3122   case TargetOpcode::G_PTRTOINT:
3123     return selectCOPY(I);
3124   case TargetOpcode::G_CONSTANT:
3125   case TargetOpcode::G_FCONSTANT:
3126     return selectG_CONSTANT(I);
3127   case TargetOpcode::G_FNEG:
3128     if (selectImpl(I, *CoverageInfo))
3129       return true;
3130     return selectG_FNEG(I);
3131   case TargetOpcode::G_FABS:
3132     if (selectImpl(I, *CoverageInfo))
3133       return true;
3134     return selectG_FABS(I);
3135   case TargetOpcode::G_EXTRACT:
3136     return selectG_EXTRACT(I);
3137   case TargetOpcode::G_MERGE_VALUES:
3138   case TargetOpcode::G_BUILD_VECTOR:
3139   case TargetOpcode::G_CONCAT_VECTORS:
3140     return selectG_MERGE_VALUES(I);
3141   case TargetOpcode::G_UNMERGE_VALUES:
3142     return selectG_UNMERGE_VALUES(I);
3143   case TargetOpcode::G_BUILD_VECTOR_TRUNC:
3144     return selectG_BUILD_VECTOR_TRUNC(I);
3145   case TargetOpcode::G_PTR_ADD:
3146     return selectG_PTR_ADD(I);
3147   case TargetOpcode::G_IMPLICIT_DEF:
3148     return selectG_IMPLICIT_DEF(I);
3149   case TargetOpcode::G_FREEZE:
3150     return selectCOPY(I);
3151   case TargetOpcode::G_INSERT:
3152     return selectG_INSERT(I);
3153   case TargetOpcode::G_INTRINSIC:
3154     return selectG_INTRINSIC(I);
3155   case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
3156     return selectG_INTRINSIC_W_SIDE_EFFECTS(I);
3157   case TargetOpcode::G_ICMP:
3158     if (selectG_ICMP(I))
3159       return true;
3160     return selectImpl(I, *CoverageInfo);
3161   case TargetOpcode::G_LOAD:
3162   case TargetOpcode::G_STORE:
3163   case TargetOpcode::G_ATOMIC_CMPXCHG:
3164   case TargetOpcode::G_ATOMICRMW_XCHG:
3165   case TargetOpcode::G_ATOMICRMW_ADD:
3166   case TargetOpcode::G_ATOMICRMW_SUB:
3167   case TargetOpcode::G_ATOMICRMW_AND:
3168   case TargetOpcode::G_ATOMICRMW_OR:
3169   case TargetOpcode::G_ATOMICRMW_XOR:
3170   case TargetOpcode::G_ATOMICRMW_MIN:
3171   case TargetOpcode::G_ATOMICRMW_MAX:
3172   case TargetOpcode::G_ATOMICRMW_UMIN:
3173   case TargetOpcode::G_ATOMICRMW_UMAX:
3174   case TargetOpcode::G_ATOMICRMW_FADD:
3175   case AMDGPU::G_AMDGPU_ATOMIC_INC:
3176   case AMDGPU::G_AMDGPU_ATOMIC_DEC:
3177   case AMDGPU::G_AMDGPU_ATOMIC_FMIN:
3178   case AMDGPU::G_AMDGPU_ATOMIC_FMAX:
3179     return selectG_LOAD_STORE_ATOMICRMW(I);
3180   case AMDGPU::G_AMDGPU_ATOMIC_CMPXCHG:
3181     return selectG_AMDGPU_ATOMIC_CMPXCHG(I);
3182   case TargetOpcode::G_SELECT:
3183     return selectG_SELECT(I);
3184   case TargetOpcode::G_TRUNC:
3185     return selectG_TRUNC(I);
3186   case TargetOpcode::G_SEXT:
3187   case TargetOpcode::G_ZEXT:
3188   case TargetOpcode::G_ANYEXT:
3189   case TargetOpcode::G_SEXT_INREG:
3190     if (selectImpl(I, *CoverageInfo))
3191       return true;
3192     return selectG_SZA_EXT(I);
3193   case TargetOpcode::G_BRCOND:
3194     return selectG_BRCOND(I);
3195   case TargetOpcode::G_GLOBAL_VALUE:
3196     return selectG_GLOBAL_VALUE(I);
3197   case TargetOpcode::G_PTRMASK:
3198     return selectG_PTRMASK(I);
3199   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
3200     return selectG_EXTRACT_VECTOR_ELT(I);
3201   case TargetOpcode::G_INSERT_VECTOR_ELT:
3202     return selectG_INSERT_VECTOR_ELT(I);
3203   case TargetOpcode::G_SHUFFLE_VECTOR:
3204     return selectG_SHUFFLE_VECTOR(I);
3205   case AMDGPU::G_AMDGPU_INTRIN_IMAGE_LOAD:
3206   case AMDGPU::G_AMDGPU_INTRIN_IMAGE_STORE: {
3207     const AMDGPU::ImageDimIntrinsicInfo *Intr
3208       = AMDGPU::getImageDimIntrinsicInfo(I.getIntrinsicID());
3209     assert(Intr && "not an image intrinsic with image pseudo");
3210     return selectImageIntrinsic(I, Intr);
3211   }
3212   case AMDGPU::G_AMDGPU_INTRIN_BVH_INTERSECT_RAY:
3213     return selectBVHIntrinsic(I);
3214   case AMDGPU::G_AMDGPU_BUFFER_ATOMIC_FADD:
3215     return selectAMDGPU_BUFFER_ATOMIC_FADD(I);
3216   case AMDGPU::G_SBFX:
3217   case AMDGPU::G_UBFX:
3218     return selectG_SBFX_UBFX(I);
3219   default:
3220     return selectImpl(I, *CoverageInfo);
3221   }
3222   return false;
3223 }
3224 
3225 InstructionSelector::ComplexRendererFns
selectVCSRC(MachineOperand & Root) const3226 AMDGPUInstructionSelector::selectVCSRC(MachineOperand &Root) const {
3227   return {{
3228       [=](MachineInstrBuilder &MIB) { MIB.add(Root); }
3229   }};
3230 
3231 }
3232 
3233 std::pair<Register, unsigned>
selectVOP3ModsImpl(MachineOperand & Root,bool AllowAbs) const3234 AMDGPUInstructionSelector::selectVOP3ModsImpl(MachineOperand &Root,
3235                                               bool AllowAbs) const {
3236   Register Src = Root.getReg();
3237   Register OrigSrc = Src;
3238   unsigned Mods = 0;
3239   MachineInstr *MI = getDefIgnoringCopies(Src, *MRI);
3240 
3241   if (MI && MI->getOpcode() == AMDGPU::G_FNEG) {
3242     Src = MI->getOperand(1).getReg();
3243     Mods |= SISrcMods::NEG;
3244     MI = getDefIgnoringCopies(Src, *MRI);
3245   }
3246 
3247   if (AllowAbs && MI && MI->getOpcode() == AMDGPU::G_FABS) {
3248     Src = MI->getOperand(1).getReg();
3249     Mods |= SISrcMods::ABS;
3250   }
3251 
3252   if (Mods != 0 &&
3253       RBI.getRegBank(Src, *MRI, TRI)->getID() != AMDGPU::VGPRRegBankID) {
3254     MachineInstr *UseMI = Root.getParent();
3255 
3256     // If we looked through copies to find source modifiers on an SGPR operand,
3257     // we now have an SGPR register source. To avoid potentially violating the
3258     // constant bus restriction, we need to insert a copy to a VGPR.
3259     Register VGPRSrc = MRI->cloneVirtualRegister(OrigSrc);
3260     BuildMI(*UseMI->getParent(), UseMI, UseMI->getDebugLoc(),
3261             TII.get(AMDGPU::COPY), VGPRSrc)
3262       .addReg(Src);
3263     Src = VGPRSrc;
3264   }
3265 
3266   return std::make_pair(Src, Mods);
3267 }
3268 
3269 ///
3270 /// This will select either an SGPR or VGPR operand and will save us from
3271 /// having to write an extra tablegen pattern.
3272 InstructionSelector::ComplexRendererFns
selectVSRC0(MachineOperand & Root) const3273 AMDGPUInstructionSelector::selectVSRC0(MachineOperand &Root) const {
3274   return {{
3275       [=](MachineInstrBuilder &MIB) { MIB.add(Root); }
3276   }};
3277 }
3278 
3279 InstructionSelector::ComplexRendererFns
selectVOP3Mods0(MachineOperand & Root) const3280 AMDGPUInstructionSelector::selectVOP3Mods0(MachineOperand &Root) const {
3281   Register Src;
3282   unsigned Mods;
3283   std::tie(Src, Mods) = selectVOP3ModsImpl(Root);
3284 
3285   return {{
3286       [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
3287       [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }, // src0_mods
3288       [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },    // clamp
3289       [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }     // omod
3290   }};
3291 }
3292 
3293 InstructionSelector::ComplexRendererFns
selectVOP3BMods0(MachineOperand & Root) const3294 AMDGPUInstructionSelector::selectVOP3BMods0(MachineOperand &Root) const {
3295   Register Src;
3296   unsigned Mods;
3297   std::tie(Src, Mods) = selectVOP3ModsImpl(Root, /* AllowAbs */ false);
3298 
3299   return {{
3300       [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
3301       [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }, // src0_mods
3302       [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },    // clamp
3303       [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }     // omod
3304   }};
3305 }
3306 
3307 InstructionSelector::ComplexRendererFns
selectVOP3OMods(MachineOperand & Root) const3308 AMDGPUInstructionSelector::selectVOP3OMods(MachineOperand &Root) const {
3309   return {{
3310       [=](MachineInstrBuilder &MIB) { MIB.add(Root); },
3311       [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }, // clamp
3312       [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }  // omod
3313   }};
3314 }
3315 
3316 InstructionSelector::ComplexRendererFns
selectVOP3Mods(MachineOperand & Root) const3317 AMDGPUInstructionSelector::selectVOP3Mods(MachineOperand &Root) const {
3318   Register Src;
3319   unsigned Mods;
3320   std::tie(Src, Mods) = selectVOP3ModsImpl(Root);
3321 
3322   return {{
3323       [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
3324       [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }  // src_mods
3325   }};
3326 }
3327 
3328 InstructionSelector::ComplexRendererFns
selectVOP3BMods(MachineOperand & Root) const3329 AMDGPUInstructionSelector::selectVOP3BMods(MachineOperand &Root) const {
3330   Register Src;
3331   unsigned Mods;
3332   std::tie(Src, Mods) = selectVOP3ModsImpl(Root, /* AllowAbs */ false);
3333 
3334   return {{
3335       [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
3336       [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
3337   }};
3338 }
3339 
3340 InstructionSelector::ComplexRendererFns
selectVOP3NoMods(MachineOperand & Root) const3341 AMDGPUInstructionSelector::selectVOP3NoMods(MachineOperand &Root) const {
3342   Register Reg = Root.getReg();
3343   const MachineInstr *Def = getDefIgnoringCopies(Reg, *MRI);
3344   if (Def && (Def->getOpcode() == AMDGPU::G_FNEG ||
3345               Def->getOpcode() == AMDGPU::G_FABS))
3346     return {};
3347   return {{
3348       [=](MachineInstrBuilder &MIB) { MIB.addReg(Reg); },
3349   }};
3350 }
3351 
3352 std::pair<Register, unsigned>
selectVOP3PModsImpl(Register Src,const MachineRegisterInfo & MRI) const3353 AMDGPUInstructionSelector::selectVOP3PModsImpl(
3354   Register Src, const MachineRegisterInfo &MRI) const {
3355   unsigned Mods = 0;
3356   MachineInstr *MI = MRI.getVRegDef(Src);
3357 
3358   if (MI && MI->getOpcode() == AMDGPU::G_FNEG &&
3359       // It's possible to see an f32 fneg here, but unlikely.
3360       // TODO: Treat f32 fneg as only high bit.
3361       MRI.getType(Src) == LLT::fixed_vector(2, 16)) {
3362     Mods ^= (SISrcMods::NEG | SISrcMods::NEG_HI);
3363     Src = MI->getOperand(1).getReg();
3364     MI = MRI.getVRegDef(Src);
3365   }
3366 
3367   // TODO: Match op_sel through g_build_vector_trunc and g_shuffle_vector.
3368 
3369   // Packed instructions do not have abs modifiers.
3370   Mods |= SISrcMods::OP_SEL_1;
3371 
3372   return std::make_pair(Src, Mods);
3373 }
3374 
3375 InstructionSelector::ComplexRendererFns
selectVOP3PMods(MachineOperand & Root) const3376 AMDGPUInstructionSelector::selectVOP3PMods(MachineOperand &Root) const {
3377   MachineRegisterInfo &MRI
3378     = Root.getParent()->getParent()->getParent()->getRegInfo();
3379 
3380   Register Src;
3381   unsigned Mods;
3382   std::tie(Src, Mods) = selectVOP3PModsImpl(Root.getReg(), MRI);
3383 
3384   return {{
3385       [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
3386       [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }  // src_mods
3387   }};
3388 }
3389 
3390 InstructionSelector::ComplexRendererFns
selectVOP3Mods_nnan(MachineOperand & Root) const3391 AMDGPUInstructionSelector::selectVOP3Mods_nnan(MachineOperand &Root) const {
3392   Register Src;
3393   unsigned Mods;
3394   std::tie(Src, Mods) = selectVOP3ModsImpl(Root);
3395   if (!isKnownNeverNaN(Src, *MRI))
3396     return None;
3397 
3398   return {{
3399       [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
3400       [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }  // src_mods
3401   }};
3402 }
3403 
3404 InstructionSelector::ComplexRendererFns
selectVOP3OpSelMods(MachineOperand & Root) const3405 AMDGPUInstructionSelector::selectVOP3OpSelMods(MachineOperand &Root) const {
3406   // FIXME: Handle op_sel
3407   return {{
3408       [=](MachineInstrBuilder &MIB) { MIB.addReg(Root.getReg()); },
3409       [=](MachineInstrBuilder &MIB) { MIB.addImm(0); } // src_mods
3410   }};
3411 }
3412 
3413 InstructionSelector::ComplexRendererFns
selectSmrdImm(MachineOperand & Root) const3414 AMDGPUInstructionSelector::selectSmrdImm(MachineOperand &Root) const {
3415   SmallVector<GEPInfo, 4> AddrInfo;
3416   getAddrModeInfo(*Root.getParent(), *MRI, AddrInfo);
3417 
3418   if (AddrInfo.empty() || AddrInfo[0].SgprParts.size() != 1)
3419     return None;
3420 
3421   const GEPInfo &GEPInfo = AddrInfo[0];
3422   Optional<int64_t> EncodedImm =
3423       AMDGPU::getSMRDEncodedOffset(STI, GEPInfo.Imm, false);
3424   if (!EncodedImm)
3425     return None;
3426 
3427   unsigned PtrReg = GEPInfo.SgprParts[0];
3428   return {{
3429     [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrReg); },
3430     [=](MachineInstrBuilder &MIB) { MIB.addImm(*EncodedImm); }
3431   }};
3432 }
3433 
3434 InstructionSelector::ComplexRendererFns
selectSmrdImm32(MachineOperand & Root) const3435 AMDGPUInstructionSelector::selectSmrdImm32(MachineOperand &Root) const {
3436   SmallVector<GEPInfo, 4> AddrInfo;
3437   getAddrModeInfo(*Root.getParent(), *MRI, AddrInfo);
3438 
3439   if (AddrInfo.empty() || AddrInfo[0].SgprParts.size() != 1)
3440     return None;
3441 
3442   const GEPInfo &GEPInfo = AddrInfo[0];
3443   Register PtrReg = GEPInfo.SgprParts[0];
3444   Optional<int64_t> EncodedImm =
3445       AMDGPU::getSMRDEncodedLiteralOffset32(STI, GEPInfo.Imm);
3446   if (!EncodedImm)
3447     return None;
3448 
3449   return {{
3450     [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrReg); },
3451     [=](MachineInstrBuilder &MIB) { MIB.addImm(*EncodedImm); }
3452   }};
3453 }
3454 
3455 InstructionSelector::ComplexRendererFns
selectSmrdSgpr(MachineOperand & Root) const3456 AMDGPUInstructionSelector::selectSmrdSgpr(MachineOperand &Root) const {
3457   MachineInstr *MI = Root.getParent();
3458   MachineBasicBlock *MBB = MI->getParent();
3459 
3460   SmallVector<GEPInfo, 4> AddrInfo;
3461   getAddrModeInfo(*MI, *MRI, AddrInfo);
3462 
3463   // FIXME: We should shrink the GEP if the offset is known to be <= 32-bits,
3464   // then we can select all ptr + 32-bit offsets not just immediate offsets.
3465   if (AddrInfo.empty() || AddrInfo[0].SgprParts.size() != 1)
3466     return None;
3467 
3468   const GEPInfo &GEPInfo = AddrInfo[0];
3469   // SGPR offset is unsigned.
3470   if (!GEPInfo.Imm || GEPInfo.Imm < 0 || !isUInt<32>(GEPInfo.Imm))
3471     return None;
3472 
3473   // If we make it this far we have a load with an 32-bit immediate offset.
3474   // It is OK to select this using a sgpr offset, because we have already
3475   // failed trying to select this load into one of the _IMM variants since
3476   // the _IMM Patterns are considered before the _SGPR patterns.
3477   Register PtrReg = GEPInfo.SgprParts[0];
3478   Register OffsetReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
3479   BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), OffsetReg)
3480           .addImm(GEPInfo.Imm);
3481   return {{
3482     [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrReg); },
3483     [=](MachineInstrBuilder &MIB) { MIB.addReg(OffsetReg); }
3484   }};
3485 }
3486 
3487 std::pair<Register, int>
selectFlatOffsetImpl(MachineOperand & Root,uint64_t FlatVariant) const3488 AMDGPUInstructionSelector::selectFlatOffsetImpl(MachineOperand &Root,
3489                                                 uint64_t FlatVariant) const {
3490   MachineInstr *MI = Root.getParent();
3491 
3492   auto Default = std::make_pair(Root.getReg(), 0);
3493 
3494   if (!STI.hasFlatInstOffsets())
3495     return Default;
3496 
3497   Register PtrBase;
3498   int64_t ConstOffset;
3499   std::tie(PtrBase, ConstOffset) =
3500       getPtrBaseWithConstantOffset(Root.getReg(), *MRI);
3501   if (ConstOffset == 0)
3502     return Default;
3503 
3504   unsigned AddrSpace = (*MI->memoperands_begin())->getAddrSpace();
3505   if (!TII.isLegalFLATOffset(ConstOffset, AddrSpace, FlatVariant))
3506     return Default;
3507 
3508   return std::make_pair(PtrBase, ConstOffset);
3509 }
3510 
3511 InstructionSelector::ComplexRendererFns
selectFlatOffset(MachineOperand & Root) const3512 AMDGPUInstructionSelector::selectFlatOffset(MachineOperand &Root) const {
3513   auto PtrWithOffset = selectFlatOffsetImpl(Root, SIInstrFlags::FLAT);
3514 
3515   return {{
3516       [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrWithOffset.first); },
3517       [=](MachineInstrBuilder &MIB) { MIB.addImm(PtrWithOffset.second); },
3518     }};
3519 }
3520 
3521 InstructionSelector::ComplexRendererFns
selectGlobalOffset(MachineOperand & Root) const3522 AMDGPUInstructionSelector::selectGlobalOffset(MachineOperand &Root) const {
3523   auto PtrWithOffset = selectFlatOffsetImpl(Root, SIInstrFlags::FlatGlobal);
3524 
3525   return {{
3526       [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrWithOffset.first); },
3527       [=](MachineInstrBuilder &MIB) { MIB.addImm(PtrWithOffset.second); },
3528   }};
3529 }
3530 
3531 InstructionSelector::ComplexRendererFns
selectScratchOffset(MachineOperand & Root) const3532 AMDGPUInstructionSelector::selectScratchOffset(MachineOperand &Root) const {
3533   auto PtrWithOffset = selectFlatOffsetImpl(Root, SIInstrFlags::FlatScratch);
3534 
3535   return {{
3536       [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrWithOffset.first); },
3537       [=](MachineInstrBuilder &MIB) { MIB.addImm(PtrWithOffset.second); },
3538     }};
3539 }
3540 
3541 /// Match a zero extend from a 32-bit value to 64-bits.
matchZeroExtendFromS32(MachineRegisterInfo & MRI,Register Reg)3542 static Register matchZeroExtendFromS32(MachineRegisterInfo &MRI, Register Reg) {
3543   Register ZExtSrc;
3544   if (mi_match(Reg, MRI, m_GZExt(m_Reg(ZExtSrc))))
3545     return MRI.getType(ZExtSrc) == LLT::scalar(32) ? ZExtSrc : Register();
3546 
3547   // Match legalized form %zext = G_MERGE_VALUES (s32 %x), (s32 0)
3548   const MachineInstr *Def = getDefIgnoringCopies(Reg, MRI);
3549   if (Def->getOpcode() != AMDGPU::G_MERGE_VALUES)
3550     return false;
3551 
3552   if (mi_match(Def->getOperand(2).getReg(), MRI, m_ZeroInt())) {
3553     return Def->getOperand(1).getReg();
3554   }
3555 
3556   return Register();
3557 }
3558 
3559 // Match (64-bit SGPR base) + (zext vgpr offset) + sext(imm offset)
3560 InstructionSelector::ComplexRendererFns
selectGlobalSAddr(MachineOperand & Root) const3561 AMDGPUInstructionSelector::selectGlobalSAddr(MachineOperand &Root) const {
3562   Register Addr = Root.getReg();
3563   Register PtrBase;
3564   int64_t ConstOffset;
3565   int64_t ImmOffset = 0;
3566 
3567   // Match the immediate offset first, which canonically is moved as low as
3568   // possible.
3569   std::tie(PtrBase, ConstOffset) = getPtrBaseWithConstantOffset(Addr, *MRI);
3570 
3571   if (ConstOffset != 0) {
3572     if (TII.isLegalFLATOffset(ConstOffset, AMDGPUAS::GLOBAL_ADDRESS,
3573                               SIInstrFlags::FlatGlobal)) {
3574       Addr = PtrBase;
3575       ImmOffset = ConstOffset;
3576     } else {
3577       auto PtrBaseDef = getDefSrcRegIgnoringCopies(PtrBase, *MRI);
3578       if (!PtrBaseDef)
3579         return None;
3580 
3581       if (isSGPR(PtrBaseDef->Reg)) {
3582         if (ConstOffset > 0) {
3583           // Offset is too large.
3584           //
3585           // saddr + large_offset -> saddr +
3586           //                         (voffset = large_offset & ~MaxOffset) +
3587           //                         (large_offset & MaxOffset);
3588           int64_t SplitImmOffset, RemainderOffset;
3589           std::tie(SplitImmOffset, RemainderOffset) = TII.splitFlatOffset(
3590               ConstOffset, AMDGPUAS::GLOBAL_ADDRESS, SIInstrFlags::FlatGlobal);
3591 
3592           if (isUInt<32>(RemainderOffset)) {
3593             MachineInstr *MI = Root.getParent();
3594             MachineBasicBlock *MBB = MI->getParent();
3595             Register HighBits =
3596                 MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3597 
3598             BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::V_MOV_B32_e32),
3599                     HighBits)
3600                 .addImm(RemainderOffset);
3601 
3602             return {{
3603                 [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrBase); }, // saddr
3604                 [=](MachineInstrBuilder &MIB) {
3605                   MIB.addReg(HighBits);
3606                 }, // voffset
3607                 [=](MachineInstrBuilder &MIB) { MIB.addImm(SplitImmOffset); },
3608             }};
3609           }
3610         }
3611 
3612         // We are adding a 64 bit SGPR and a constant. If constant bus limit
3613         // is 1 we would need to perform 1 or 2 extra moves for each half of
3614         // the constant and it is better to do a scalar add and then issue a
3615         // single VALU instruction to materialize zero. Otherwise it is less
3616         // instructions to perform VALU adds with immediates or inline literals.
3617         unsigned NumLiterals =
3618             !TII.isInlineConstant(APInt(32, ConstOffset & 0xffffffff)) +
3619             !TII.isInlineConstant(APInt(32, ConstOffset >> 32));
3620         if (STI.getConstantBusLimit(AMDGPU::V_ADD_U32_e64) > NumLiterals)
3621           return None;
3622       }
3623     }
3624   }
3625 
3626   auto AddrDef = getDefSrcRegIgnoringCopies(Addr, *MRI);
3627   if (!AddrDef)
3628     return None;
3629 
3630   // Match the variable offset.
3631   if (AddrDef->MI->getOpcode() == AMDGPU::G_PTR_ADD) {
3632     // Look through the SGPR->VGPR copy.
3633     Register SAddr =
3634         getSrcRegIgnoringCopies(AddrDef->MI->getOperand(1).getReg(), *MRI);
3635 
3636     if (SAddr && isSGPR(SAddr)) {
3637       Register PtrBaseOffset = AddrDef->MI->getOperand(2).getReg();
3638 
3639       // It's possible voffset is an SGPR here, but the copy to VGPR will be
3640       // inserted later.
3641       if (Register VOffset = matchZeroExtendFromS32(*MRI, PtrBaseOffset)) {
3642         return {{[=](MachineInstrBuilder &MIB) { // saddr
3643                    MIB.addReg(SAddr);
3644                  },
3645                  [=](MachineInstrBuilder &MIB) { // voffset
3646                    MIB.addReg(VOffset);
3647                  },
3648                  [=](MachineInstrBuilder &MIB) { // offset
3649                    MIB.addImm(ImmOffset);
3650                  }}};
3651       }
3652     }
3653   }
3654 
3655   // FIXME: We should probably have folded COPY (G_IMPLICIT_DEF) earlier, and
3656   // drop this.
3657   if (AddrDef->MI->getOpcode() == AMDGPU::G_IMPLICIT_DEF ||
3658       AddrDef->MI->getOpcode() == AMDGPU::G_CONSTANT || !isSGPR(AddrDef->Reg))
3659     return None;
3660 
3661   // It's cheaper to materialize a single 32-bit zero for vaddr than the two
3662   // moves required to copy a 64-bit SGPR to VGPR.
3663   MachineInstr *MI = Root.getParent();
3664   MachineBasicBlock *MBB = MI->getParent();
3665   Register VOffset = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3666 
3667   BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::V_MOV_B32_e32), VOffset)
3668       .addImm(0);
3669 
3670   return {{
3671       [=](MachineInstrBuilder &MIB) { MIB.addReg(AddrDef->Reg); }, // saddr
3672       [=](MachineInstrBuilder &MIB) { MIB.addReg(VOffset); },      // voffset
3673       [=](MachineInstrBuilder &MIB) { MIB.addImm(ImmOffset); }     // offset
3674   }};
3675 }
3676 
3677 InstructionSelector::ComplexRendererFns
selectScratchSAddr(MachineOperand & Root) const3678 AMDGPUInstructionSelector::selectScratchSAddr(MachineOperand &Root) const {
3679   Register Addr = Root.getReg();
3680   Register PtrBase;
3681   int64_t ConstOffset;
3682   int64_t ImmOffset = 0;
3683 
3684   // Match the immediate offset first, which canonically is moved as low as
3685   // possible.
3686   std::tie(PtrBase, ConstOffset) = getPtrBaseWithConstantOffset(Addr, *MRI);
3687 
3688   if (ConstOffset != 0 &&
3689       TII.isLegalFLATOffset(ConstOffset, AMDGPUAS::PRIVATE_ADDRESS,
3690                             SIInstrFlags::FlatScratch)) {
3691     Addr = PtrBase;
3692     ImmOffset = ConstOffset;
3693   }
3694 
3695   auto AddrDef = getDefSrcRegIgnoringCopies(Addr, *MRI);
3696   if (!AddrDef)
3697     return None;
3698 
3699   if (AddrDef->MI->getOpcode() == AMDGPU::G_FRAME_INDEX) {
3700     int FI = AddrDef->MI->getOperand(1).getIndex();
3701     return {{
3702         [=](MachineInstrBuilder &MIB) { MIB.addFrameIndex(FI); }, // saddr
3703         [=](MachineInstrBuilder &MIB) { MIB.addImm(ImmOffset); } // offset
3704     }};
3705   }
3706 
3707   Register SAddr = AddrDef->Reg;
3708 
3709   if (AddrDef->MI->getOpcode() == AMDGPU::G_PTR_ADD) {
3710     Register LHS = AddrDef->MI->getOperand(1).getReg();
3711     Register RHS = AddrDef->MI->getOperand(2).getReg();
3712     auto LHSDef = getDefSrcRegIgnoringCopies(LHS, *MRI);
3713     auto RHSDef = getDefSrcRegIgnoringCopies(RHS, *MRI);
3714 
3715     if (LHSDef && RHSDef &&
3716         LHSDef->MI->getOpcode() == AMDGPU::G_FRAME_INDEX &&
3717         isSGPR(RHSDef->Reg)) {
3718       int FI = LHSDef->MI->getOperand(1).getIndex();
3719       MachineInstr &I = *Root.getParent();
3720       MachineBasicBlock *BB = I.getParent();
3721       const DebugLoc &DL = I.getDebugLoc();
3722       SAddr = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
3723 
3724       BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_ADD_I32), SAddr)
3725           .addFrameIndex(FI)
3726           .addReg(RHSDef->Reg);
3727     }
3728   }
3729 
3730   if (!isSGPR(SAddr))
3731     return None;
3732 
3733   return {{
3734       [=](MachineInstrBuilder &MIB) { MIB.addReg(SAddr); }, // saddr
3735       [=](MachineInstrBuilder &MIB) { MIB.addImm(ImmOffset); } // offset
3736   }};
3737 }
3738 
3739 InstructionSelector::ComplexRendererFns
selectMUBUFScratchOffen(MachineOperand & Root) const3740 AMDGPUInstructionSelector::selectMUBUFScratchOffen(MachineOperand &Root) const {
3741   MachineInstr *MI = Root.getParent();
3742   MachineBasicBlock *MBB = MI->getParent();
3743   MachineFunction *MF = MBB->getParent();
3744   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3745 
3746   int64_t Offset = 0;
3747   if (mi_match(Root.getReg(), *MRI, m_ICst(Offset)) &&
3748       Offset != TM.getNullPointerValue(AMDGPUAS::PRIVATE_ADDRESS)) {
3749     Register HighBits = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3750 
3751     // TODO: Should this be inside the render function? The iterator seems to
3752     // move.
3753     BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::V_MOV_B32_e32),
3754             HighBits)
3755       .addImm(Offset & ~4095);
3756 
3757     return {{[=](MachineInstrBuilder &MIB) { // rsrc
3758                MIB.addReg(Info->getScratchRSrcReg());
3759              },
3760              [=](MachineInstrBuilder &MIB) { // vaddr
3761                MIB.addReg(HighBits);
3762              },
3763              [=](MachineInstrBuilder &MIB) { // soffset
3764                // Use constant zero for soffset and rely on eliminateFrameIndex
3765                // to choose the appropriate frame register if need be.
3766                MIB.addImm(0);
3767              },
3768              [=](MachineInstrBuilder &MIB) { // offset
3769                MIB.addImm(Offset & 4095);
3770              }}};
3771   }
3772 
3773   assert(Offset == 0 || Offset == -1);
3774 
3775   // Try to fold a frame index directly into the MUBUF vaddr field, and any
3776   // offsets.
3777   Optional<int> FI;
3778   Register VAddr = Root.getReg();
3779   if (const MachineInstr *RootDef = MRI->getVRegDef(Root.getReg())) {
3780     Register PtrBase;
3781     int64_t ConstOffset;
3782     std::tie(PtrBase, ConstOffset) = getPtrBaseWithConstantOffset(VAddr, *MRI);
3783     if (ConstOffset != 0) {
3784       if (SIInstrInfo::isLegalMUBUFImmOffset(ConstOffset) &&
3785           (!STI.privateMemoryResourceIsRangeChecked() ||
3786            KnownBits->signBitIsZero(PtrBase))) {
3787         const MachineInstr *PtrBaseDef = MRI->getVRegDef(PtrBase);
3788         if (PtrBaseDef->getOpcode() == AMDGPU::G_FRAME_INDEX)
3789           FI = PtrBaseDef->getOperand(1).getIndex();
3790         else
3791           VAddr = PtrBase;
3792         Offset = ConstOffset;
3793       }
3794     } else if (RootDef->getOpcode() == AMDGPU::G_FRAME_INDEX) {
3795       FI = RootDef->getOperand(1).getIndex();
3796     }
3797   }
3798 
3799   return {{[=](MachineInstrBuilder &MIB) { // rsrc
3800              MIB.addReg(Info->getScratchRSrcReg());
3801            },
3802            [=](MachineInstrBuilder &MIB) { // vaddr
3803              if (FI.hasValue())
3804                MIB.addFrameIndex(FI.getValue());
3805              else
3806                MIB.addReg(VAddr);
3807            },
3808            [=](MachineInstrBuilder &MIB) { // soffset
3809              // Use constant zero for soffset and rely on eliminateFrameIndex
3810              // to choose the appropriate frame register if need be.
3811              MIB.addImm(0);
3812            },
3813            [=](MachineInstrBuilder &MIB) { // offset
3814              MIB.addImm(Offset);
3815            }}};
3816 }
3817 
isDSOffsetLegal(Register Base,int64_t Offset) const3818 bool AMDGPUInstructionSelector::isDSOffsetLegal(Register Base,
3819                                                 int64_t Offset) const {
3820   if (!isUInt<16>(Offset))
3821     return false;
3822 
3823   if (STI.hasUsableDSOffset() || STI.unsafeDSOffsetFoldingEnabled())
3824     return true;
3825 
3826   // On Southern Islands instruction with a negative base value and an offset
3827   // don't seem to work.
3828   return KnownBits->signBitIsZero(Base);
3829 }
3830 
isDSOffset2Legal(Register Base,int64_t Offset0,int64_t Offset1,unsigned Size) const3831 bool AMDGPUInstructionSelector::isDSOffset2Legal(Register Base, int64_t Offset0,
3832                                                  int64_t Offset1,
3833                                                  unsigned Size) const {
3834   if (Offset0 % Size != 0 || Offset1 % Size != 0)
3835     return false;
3836   if (!isUInt<8>(Offset0 / Size) || !isUInt<8>(Offset1 / Size))
3837     return false;
3838 
3839   if (STI.hasUsableDSOffset() || STI.unsafeDSOffsetFoldingEnabled())
3840     return true;
3841 
3842   // On Southern Islands instruction with a negative base value and an offset
3843   // don't seem to work.
3844   return KnownBits->signBitIsZero(Base);
3845 }
3846 
3847 InstructionSelector::ComplexRendererFns
selectMUBUFScratchOffset(MachineOperand & Root) const3848 AMDGPUInstructionSelector::selectMUBUFScratchOffset(
3849     MachineOperand &Root) const {
3850   MachineInstr *MI = Root.getParent();
3851   MachineBasicBlock *MBB = MI->getParent();
3852 
3853   int64_t Offset = 0;
3854   if (!mi_match(Root.getReg(), *MRI, m_ICst(Offset)) ||
3855       !SIInstrInfo::isLegalMUBUFImmOffset(Offset))
3856     return {};
3857 
3858   const MachineFunction *MF = MBB->getParent();
3859   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3860 
3861   return {{
3862       [=](MachineInstrBuilder &MIB) { // rsrc
3863         MIB.addReg(Info->getScratchRSrcReg());
3864       },
3865       [=](MachineInstrBuilder &MIB) { // soffset
3866         MIB.addImm(0);
3867       },
3868       [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); } // offset
3869   }};
3870 }
3871 
3872 std::pair<Register, unsigned>
selectDS1Addr1OffsetImpl(MachineOperand & Root) const3873 AMDGPUInstructionSelector::selectDS1Addr1OffsetImpl(MachineOperand &Root) const {
3874   const MachineInstr *RootDef = MRI->getVRegDef(Root.getReg());
3875   if (!RootDef)
3876     return std::make_pair(Root.getReg(), 0);
3877 
3878   int64_t ConstAddr = 0;
3879 
3880   Register PtrBase;
3881   int64_t Offset;
3882   std::tie(PtrBase, Offset) =
3883     getPtrBaseWithConstantOffset(Root.getReg(), *MRI);
3884 
3885   if (Offset) {
3886     if (isDSOffsetLegal(PtrBase, Offset)) {
3887       // (add n0, c0)
3888       return std::make_pair(PtrBase, Offset);
3889     }
3890   } else if (RootDef->getOpcode() == AMDGPU::G_SUB) {
3891     // TODO
3892 
3893 
3894   } else if (mi_match(Root.getReg(), *MRI, m_ICst(ConstAddr))) {
3895     // TODO
3896 
3897   }
3898 
3899   return std::make_pair(Root.getReg(), 0);
3900 }
3901 
3902 InstructionSelector::ComplexRendererFns
selectDS1Addr1Offset(MachineOperand & Root) const3903 AMDGPUInstructionSelector::selectDS1Addr1Offset(MachineOperand &Root) const {
3904   Register Reg;
3905   unsigned Offset;
3906   std::tie(Reg, Offset) = selectDS1Addr1OffsetImpl(Root);
3907   return {{
3908       [=](MachineInstrBuilder &MIB) { MIB.addReg(Reg); },
3909       [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); }
3910     }};
3911 }
3912 
3913 InstructionSelector::ComplexRendererFns
selectDS64Bit4ByteAligned(MachineOperand & Root) const3914 AMDGPUInstructionSelector::selectDS64Bit4ByteAligned(MachineOperand &Root) const {
3915   return selectDSReadWrite2(Root, 4);
3916 }
3917 
3918 InstructionSelector::ComplexRendererFns
selectDS128Bit8ByteAligned(MachineOperand & Root) const3919 AMDGPUInstructionSelector::selectDS128Bit8ByteAligned(MachineOperand &Root) const {
3920   return selectDSReadWrite2(Root, 8);
3921 }
3922 
3923 InstructionSelector::ComplexRendererFns
selectDSReadWrite2(MachineOperand & Root,unsigned Size) const3924 AMDGPUInstructionSelector::selectDSReadWrite2(MachineOperand &Root,
3925                                               unsigned Size) const {
3926   Register Reg;
3927   unsigned Offset;
3928   std::tie(Reg, Offset) = selectDSReadWrite2Impl(Root, Size);
3929   return {{
3930       [=](MachineInstrBuilder &MIB) { MIB.addReg(Reg); },
3931       [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); },
3932       [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset+1); }
3933     }};
3934 }
3935 
3936 std::pair<Register, unsigned>
selectDSReadWrite2Impl(MachineOperand & Root,unsigned Size) const3937 AMDGPUInstructionSelector::selectDSReadWrite2Impl(MachineOperand &Root,
3938                                                   unsigned Size) const {
3939   const MachineInstr *RootDef = MRI->getVRegDef(Root.getReg());
3940   if (!RootDef)
3941     return std::make_pair(Root.getReg(), 0);
3942 
3943   int64_t ConstAddr = 0;
3944 
3945   Register PtrBase;
3946   int64_t Offset;
3947   std::tie(PtrBase, Offset) =
3948     getPtrBaseWithConstantOffset(Root.getReg(), *MRI);
3949 
3950   if (Offset) {
3951     int64_t OffsetValue0 = Offset;
3952     int64_t OffsetValue1 = Offset + Size;
3953     if (isDSOffset2Legal(PtrBase, OffsetValue0, OffsetValue1, Size)) {
3954       // (add n0, c0)
3955       return std::make_pair(PtrBase, OffsetValue0 / Size);
3956     }
3957   } else if (RootDef->getOpcode() == AMDGPU::G_SUB) {
3958     // TODO
3959 
3960   } else if (mi_match(Root.getReg(), *MRI, m_ICst(ConstAddr))) {
3961     // TODO
3962 
3963   }
3964 
3965   return std::make_pair(Root.getReg(), 0);
3966 }
3967 
3968 /// If \p Root is a G_PTR_ADD with a G_CONSTANT on the right hand side, return
3969 /// the base value with the constant offset. There may be intervening copies
3970 /// between \p Root and the identified constant. Returns \p Root, 0 if this does
3971 /// not match the pattern.
3972 std::pair<Register, int64_t>
getPtrBaseWithConstantOffset(Register Root,const MachineRegisterInfo & MRI) const3973 AMDGPUInstructionSelector::getPtrBaseWithConstantOffset(
3974   Register Root, const MachineRegisterInfo &MRI) const {
3975   MachineInstr *RootI = getDefIgnoringCopies(Root, MRI);
3976   if (RootI->getOpcode() != TargetOpcode::G_PTR_ADD)
3977     return {Root, 0};
3978 
3979   MachineOperand &RHS = RootI->getOperand(2);
3980   Optional<ValueAndVReg> MaybeOffset
3981     = getConstantVRegValWithLookThrough(RHS.getReg(), MRI, true);
3982   if (!MaybeOffset)
3983     return {Root, 0};
3984   return {RootI->getOperand(1).getReg(), MaybeOffset->Value.getSExtValue()};
3985 }
3986 
addZeroImm(MachineInstrBuilder & MIB)3987 static void addZeroImm(MachineInstrBuilder &MIB) {
3988   MIB.addImm(0);
3989 }
3990 
3991 /// Return a resource descriptor for use with an arbitrary 64-bit pointer. If \p
3992 /// BasePtr is not valid, a null base pointer will be used.
buildRSRC(MachineIRBuilder & B,MachineRegisterInfo & MRI,uint32_t FormatLo,uint32_t FormatHi,Register BasePtr)3993 static Register buildRSRC(MachineIRBuilder &B, MachineRegisterInfo &MRI,
3994                           uint32_t FormatLo, uint32_t FormatHi,
3995                           Register BasePtr) {
3996   Register RSrc2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3997   Register RSrc3 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3998   Register RSrcHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3999   Register RSrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
4000 
4001   B.buildInstr(AMDGPU::S_MOV_B32)
4002     .addDef(RSrc2)
4003     .addImm(FormatLo);
4004   B.buildInstr(AMDGPU::S_MOV_B32)
4005     .addDef(RSrc3)
4006     .addImm(FormatHi);
4007 
4008   // Build the half of the subregister with the constants before building the
4009   // full 128-bit register. If we are building multiple resource descriptors,
4010   // this will allow CSEing of the 2-component register.
4011   B.buildInstr(AMDGPU::REG_SEQUENCE)
4012     .addDef(RSrcHi)
4013     .addReg(RSrc2)
4014     .addImm(AMDGPU::sub0)
4015     .addReg(RSrc3)
4016     .addImm(AMDGPU::sub1);
4017 
4018   Register RSrcLo = BasePtr;
4019   if (!BasePtr) {
4020     RSrcLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
4021     B.buildInstr(AMDGPU::S_MOV_B64)
4022       .addDef(RSrcLo)
4023       .addImm(0);
4024   }
4025 
4026   B.buildInstr(AMDGPU::REG_SEQUENCE)
4027     .addDef(RSrc)
4028     .addReg(RSrcLo)
4029     .addImm(AMDGPU::sub0_sub1)
4030     .addReg(RSrcHi)
4031     .addImm(AMDGPU::sub2_sub3);
4032 
4033   return RSrc;
4034 }
4035 
buildAddr64RSrc(MachineIRBuilder & B,MachineRegisterInfo & MRI,const SIInstrInfo & TII,Register BasePtr)4036 static Register buildAddr64RSrc(MachineIRBuilder &B, MachineRegisterInfo &MRI,
4037                                 const SIInstrInfo &TII, Register BasePtr) {
4038   uint64_t DefaultFormat = TII.getDefaultRsrcDataFormat();
4039 
4040   // FIXME: Why are half the "default" bits ignored based on the addressing
4041   // mode?
4042   return buildRSRC(B, MRI, 0, Hi_32(DefaultFormat), BasePtr);
4043 }
4044 
buildOffsetSrc(MachineIRBuilder & B,MachineRegisterInfo & MRI,const SIInstrInfo & TII,Register BasePtr)4045 static Register buildOffsetSrc(MachineIRBuilder &B, MachineRegisterInfo &MRI,
4046                                const SIInstrInfo &TII, Register BasePtr) {
4047   uint64_t DefaultFormat = TII.getDefaultRsrcDataFormat();
4048 
4049   // FIXME: Why are half the "default" bits ignored based on the addressing
4050   // mode?
4051   return buildRSRC(B, MRI, -1, Hi_32(DefaultFormat), BasePtr);
4052 }
4053 
4054 AMDGPUInstructionSelector::MUBUFAddressData
parseMUBUFAddress(Register Src) const4055 AMDGPUInstructionSelector::parseMUBUFAddress(Register Src) const {
4056   MUBUFAddressData Data;
4057   Data.N0 = Src;
4058 
4059   Register PtrBase;
4060   int64_t Offset;
4061 
4062   std::tie(PtrBase, Offset) = getPtrBaseWithConstantOffset(Src, *MRI);
4063   if (isUInt<32>(Offset)) {
4064     Data.N0 = PtrBase;
4065     Data.Offset = Offset;
4066   }
4067 
4068   if (MachineInstr *InputAdd
4069       = getOpcodeDef(TargetOpcode::G_PTR_ADD, Data.N0, *MRI)) {
4070     Data.N2 = InputAdd->getOperand(1).getReg();
4071     Data.N3 = InputAdd->getOperand(2).getReg();
4072 
4073     // FIXME: Need to fix extra SGPR->VGPRcopies inserted
4074     // FIXME: Don't know this was defined by operand 0
4075     //
4076     // TODO: Remove this when we have copy folding optimizations after
4077     // RegBankSelect.
4078     Data.N2 = getDefIgnoringCopies(Data.N2, *MRI)->getOperand(0).getReg();
4079     Data.N3 = getDefIgnoringCopies(Data.N3, *MRI)->getOperand(0).getReg();
4080   }
4081 
4082   return Data;
4083 }
4084 
4085 /// Return if the addr64 mubuf mode should be used for the given address.
shouldUseAddr64(MUBUFAddressData Addr) const4086 bool AMDGPUInstructionSelector::shouldUseAddr64(MUBUFAddressData Addr) const {
4087   // (ptr_add N2, N3) -> addr64, or
4088   // (ptr_add (ptr_add N2, N3), C1) -> addr64
4089   if (Addr.N2)
4090     return true;
4091 
4092   const RegisterBank *N0Bank = RBI.getRegBank(Addr.N0, *MRI, TRI);
4093   return N0Bank->getID() == AMDGPU::VGPRRegBankID;
4094 }
4095 
4096 /// Split an immediate offset \p ImmOffset depending on whether it fits in the
4097 /// immediate field. Modifies \p ImmOffset and sets \p SOffset to the variable
4098 /// component.
splitIllegalMUBUFOffset(MachineIRBuilder & B,Register & SOffset,int64_t & ImmOffset) const4099 void AMDGPUInstructionSelector::splitIllegalMUBUFOffset(
4100   MachineIRBuilder &B, Register &SOffset, int64_t &ImmOffset) const {
4101   if (SIInstrInfo::isLegalMUBUFImmOffset(ImmOffset))
4102     return;
4103 
4104   // Illegal offset, store it in soffset.
4105   SOffset = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
4106   B.buildInstr(AMDGPU::S_MOV_B32)
4107     .addDef(SOffset)
4108     .addImm(ImmOffset);
4109   ImmOffset = 0;
4110 }
4111 
selectMUBUFAddr64Impl(MachineOperand & Root,Register & VAddr,Register & RSrcReg,Register & SOffset,int64_t & Offset) const4112 bool AMDGPUInstructionSelector::selectMUBUFAddr64Impl(
4113   MachineOperand &Root, Register &VAddr, Register &RSrcReg,
4114   Register &SOffset, int64_t &Offset) const {
4115   // FIXME: Predicates should stop this from reaching here.
4116   // addr64 bit was removed for volcanic islands.
4117   if (!STI.hasAddr64() || STI.useFlatForGlobal())
4118     return false;
4119 
4120   MUBUFAddressData AddrData = parseMUBUFAddress(Root.getReg());
4121   if (!shouldUseAddr64(AddrData))
4122     return false;
4123 
4124   Register N0 = AddrData.N0;
4125   Register N2 = AddrData.N2;
4126   Register N3 = AddrData.N3;
4127   Offset = AddrData.Offset;
4128 
4129   // Base pointer for the SRD.
4130   Register SRDPtr;
4131 
4132   if (N2) {
4133     if (RBI.getRegBank(N2, *MRI, TRI)->getID() == AMDGPU::VGPRRegBankID) {
4134       assert(N3);
4135       if (RBI.getRegBank(N3, *MRI, TRI)->getID() == AMDGPU::VGPRRegBankID) {
4136         // Both N2 and N3 are divergent. Use N0 (the result of the add) as the
4137         // addr64, and construct the default resource from a 0 address.
4138         VAddr = N0;
4139       } else {
4140         SRDPtr = N3;
4141         VAddr = N2;
4142       }
4143     } else {
4144       // N2 is not divergent.
4145       SRDPtr = N2;
4146       VAddr = N3;
4147     }
4148   } else if (RBI.getRegBank(N0, *MRI, TRI)->getID() == AMDGPU::VGPRRegBankID) {
4149     // Use the default null pointer in the resource
4150     VAddr = N0;
4151   } else {
4152     // N0 -> offset, or
4153     // (N0 + C1) -> offset
4154     SRDPtr = N0;
4155   }
4156 
4157   MachineIRBuilder B(*Root.getParent());
4158   RSrcReg = buildAddr64RSrc(B, *MRI, TII, SRDPtr);
4159   splitIllegalMUBUFOffset(B, SOffset, Offset);
4160   return true;
4161 }
4162 
selectMUBUFOffsetImpl(MachineOperand & Root,Register & RSrcReg,Register & SOffset,int64_t & Offset) const4163 bool AMDGPUInstructionSelector::selectMUBUFOffsetImpl(
4164   MachineOperand &Root, Register &RSrcReg, Register &SOffset,
4165   int64_t &Offset) const {
4166 
4167   // FIXME: Pattern should not reach here.
4168   if (STI.useFlatForGlobal())
4169     return false;
4170 
4171   MUBUFAddressData AddrData = parseMUBUFAddress(Root.getReg());
4172   if (shouldUseAddr64(AddrData))
4173     return false;
4174 
4175   // N0 -> offset, or
4176   // (N0 + C1) -> offset
4177   Register SRDPtr = AddrData.N0;
4178   Offset = AddrData.Offset;
4179 
4180   // TODO: Look through extensions for 32-bit soffset.
4181   MachineIRBuilder B(*Root.getParent());
4182 
4183   RSrcReg = buildOffsetSrc(B, *MRI, TII, SRDPtr);
4184   splitIllegalMUBUFOffset(B, SOffset, Offset);
4185   return true;
4186 }
4187 
4188 InstructionSelector::ComplexRendererFns
selectMUBUFAddr64(MachineOperand & Root) const4189 AMDGPUInstructionSelector::selectMUBUFAddr64(MachineOperand &Root) const {
4190   Register VAddr;
4191   Register RSrcReg;
4192   Register SOffset;
4193   int64_t Offset = 0;
4194 
4195   if (!selectMUBUFAddr64Impl(Root, VAddr, RSrcReg, SOffset, Offset))
4196     return {};
4197 
4198   // FIXME: Use defaulted operands for trailing 0s and remove from the complex
4199   // pattern.
4200   return {{
4201       [=](MachineInstrBuilder &MIB) {  // rsrc
4202         MIB.addReg(RSrcReg);
4203       },
4204       [=](MachineInstrBuilder &MIB) { // vaddr
4205         MIB.addReg(VAddr);
4206       },
4207       [=](MachineInstrBuilder &MIB) { // soffset
4208         if (SOffset)
4209           MIB.addReg(SOffset);
4210         else
4211           MIB.addImm(0);
4212       },
4213       [=](MachineInstrBuilder &MIB) { // offset
4214         MIB.addImm(Offset);
4215       },
4216       addZeroImm, //  cpol
4217       addZeroImm, //  tfe
4218       addZeroImm  //  swz
4219     }};
4220 }
4221 
4222 InstructionSelector::ComplexRendererFns
selectMUBUFOffset(MachineOperand & Root) const4223 AMDGPUInstructionSelector::selectMUBUFOffset(MachineOperand &Root) const {
4224   Register RSrcReg;
4225   Register SOffset;
4226   int64_t Offset = 0;
4227 
4228   if (!selectMUBUFOffsetImpl(Root, RSrcReg, SOffset, Offset))
4229     return {};
4230 
4231   return {{
4232       [=](MachineInstrBuilder &MIB) {  // rsrc
4233         MIB.addReg(RSrcReg);
4234       },
4235       [=](MachineInstrBuilder &MIB) { // soffset
4236         if (SOffset)
4237           MIB.addReg(SOffset);
4238         else
4239           MIB.addImm(0);
4240       },
4241       [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); }, // offset
4242       addZeroImm, //  cpol
4243       addZeroImm, //  tfe
4244       addZeroImm, //  swz
4245     }};
4246 }
4247 
4248 InstructionSelector::ComplexRendererFns
selectMUBUFAddr64Atomic(MachineOperand & Root) const4249 AMDGPUInstructionSelector::selectMUBUFAddr64Atomic(MachineOperand &Root) const {
4250   Register VAddr;
4251   Register RSrcReg;
4252   Register SOffset;
4253   int64_t Offset = 0;
4254 
4255   if (!selectMUBUFAddr64Impl(Root, VAddr, RSrcReg, SOffset, Offset))
4256     return {};
4257 
4258   // FIXME: Use defaulted operands for trailing 0s and remove from the complex
4259   // pattern.
4260   return {{
4261       [=](MachineInstrBuilder &MIB) {  // rsrc
4262         MIB.addReg(RSrcReg);
4263       },
4264       [=](MachineInstrBuilder &MIB) { // vaddr
4265         MIB.addReg(VAddr);
4266       },
4267       [=](MachineInstrBuilder &MIB) { // soffset
4268         if (SOffset)
4269           MIB.addReg(SOffset);
4270         else
4271           MIB.addImm(0);
4272       },
4273       [=](MachineInstrBuilder &MIB) { // offset
4274         MIB.addImm(Offset);
4275       },
4276       [=](MachineInstrBuilder &MIB) {
4277         MIB.addImm(AMDGPU::CPol::GLC); // cpol
4278       }
4279     }};
4280 }
4281 
4282 InstructionSelector::ComplexRendererFns
selectMUBUFOffsetAtomic(MachineOperand & Root) const4283 AMDGPUInstructionSelector::selectMUBUFOffsetAtomic(MachineOperand &Root) const {
4284   Register RSrcReg;
4285   Register SOffset;
4286   int64_t Offset = 0;
4287 
4288   if (!selectMUBUFOffsetImpl(Root, RSrcReg, SOffset, Offset))
4289     return {};
4290 
4291   return {{
4292       [=](MachineInstrBuilder &MIB) {  // rsrc
4293         MIB.addReg(RSrcReg);
4294       },
4295       [=](MachineInstrBuilder &MIB) { // soffset
4296         if (SOffset)
4297           MIB.addReg(SOffset);
4298         else
4299           MIB.addImm(0);
4300       },
4301       [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); }, // offset
4302       [=](MachineInstrBuilder &MIB) { MIB.addImm(AMDGPU::CPol::GLC); } // cpol
4303     }};
4304 }
4305 
4306 /// Get an immediate that must be 32-bits, and treated as zero extended.
getConstantZext32Val(Register Reg,const MachineRegisterInfo & MRI)4307 static Optional<uint64_t> getConstantZext32Val(Register Reg,
4308                                                const MachineRegisterInfo &MRI) {
4309   // getConstantVRegVal sexts any values, so see if that matters.
4310   Optional<int64_t> OffsetVal = getConstantVRegSExtVal(Reg, MRI);
4311   if (!OffsetVal || !isInt<32>(*OffsetVal))
4312     return None;
4313   return Lo_32(*OffsetVal);
4314 }
4315 
4316 InstructionSelector::ComplexRendererFns
selectSMRDBufferImm(MachineOperand & Root) const4317 AMDGPUInstructionSelector::selectSMRDBufferImm(MachineOperand &Root) const {
4318   Optional<uint64_t> OffsetVal = getConstantZext32Val(Root.getReg(), *MRI);
4319   if (!OffsetVal)
4320     return {};
4321 
4322   Optional<int64_t> EncodedImm =
4323       AMDGPU::getSMRDEncodedOffset(STI, *OffsetVal, true);
4324   if (!EncodedImm)
4325     return {};
4326 
4327   return {{ [=](MachineInstrBuilder &MIB) { MIB.addImm(*EncodedImm); }  }};
4328 }
4329 
4330 InstructionSelector::ComplexRendererFns
selectSMRDBufferImm32(MachineOperand & Root) const4331 AMDGPUInstructionSelector::selectSMRDBufferImm32(MachineOperand &Root) const {
4332   assert(STI.getGeneration() == AMDGPUSubtarget::SEA_ISLANDS);
4333 
4334   Optional<uint64_t> OffsetVal = getConstantZext32Val(Root.getReg(), *MRI);
4335   if (!OffsetVal)
4336     return {};
4337 
4338   Optional<int64_t> EncodedImm
4339     = AMDGPU::getSMRDEncodedLiteralOffset32(STI, *OffsetVal);
4340   if (!EncodedImm)
4341     return {};
4342 
4343   return {{ [=](MachineInstrBuilder &MIB) { MIB.addImm(*EncodedImm); }  }};
4344 }
4345 
renderTruncImm32(MachineInstrBuilder & MIB,const MachineInstr & MI,int OpIdx) const4346 void AMDGPUInstructionSelector::renderTruncImm32(MachineInstrBuilder &MIB,
4347                                                  const MachineInstr &MI,
4348                                                  int OpIdx) const {
4349   assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
4350          "Expected G_CONSTANT");
4351   MIB.addImm(MI.getOperand(1).getCImm()->getSExtValue());
4352 }
4353 
renderNegateImm(MachineInstrBuilder & MIB,const MachineInstr & MI,int OpIdx) const4354 void AMDGPUInstructionSelector::renderNegateImm(MachineInstrBuilder &MIB,
4355                                                 const MachineInstr &MI,
4356                                                 int OpIdx) const {
4357   assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
4358          "Expected G_CONSTANT");
4359   MIB.addImm(-MI.getOperand(1).getCImm()->getSExtValue());
4360 }
4361 
renderBitcastImm(MachineInstrBuilder & MIB,const MachineInstr & MI,int OpIdx) const4362 void AMDGPUInstructionSelector::renderBitcastImm(MachineInstrBuilder &MIB,
4363                                                  const MachineInstr &MI,
4364                                                  int OpIdx) const {
4365   assert(OpIdx == -1);
4366 
4367   const MachineOperand &Op = MI.getOperand(1);
4368   if (MI.getOpcode() == TargetOpcode::G_FCONSTANT)
4369     MIB.addImm(Op.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue());
4370   else {
4371     assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && "Expected G_CONSTANT");
4372     MIB.addImm(Op.getCImm()->getSExtValue());
4373   }
4374 }
4375 
renderPopcntImm(MachineInstrBuilder & MIB,const MachineInstr & MI,int OpIdx) const4376 void AMDGPUInstructionSelector::renderPopcntImm(MachineInstrBuilder &MIB,
4377                                                 const MachineInstr &MI,
4378                                                 int OpIdx) const {
4379   assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
4380          "Expected G_CONSTANT");
4381   MIB.addImm(MI.getOperand(1).getCImm()->getValue().countPopulation());
4382 }
4383 
4384 /// This only really exists to satisfy DAG type checking machinery, so is a
4385 /// no-op here.
renderTruncTImm(MachineInstrBuilder & MIB,const MachineInstr & MI,int OpIdx) const4386 void AMDGPUInstructionSelector::renderTruncTImm(MachineInstrBuilder &MIB,
4387                                                 const MachineInstr &MI,
4388                                                 int OpIdx) const {
4389   MIB.addImm(MI.getOperand(OpIdx).getImm());
4390 }
4391 
renderExtractCPol(MachineInstrBuilder & MIB,const MachineInstr & MI,int OpIdx) const4392 void AMDGPUInstructionSelector::renderExtractCPol(MachineInstrBuilder &MIB,
4393                                                   const MachineInstr &MI,
4394                                                   int OpIdx) const {
4395   assert(OpIdx >= 0 && "expected to match an immediate operand");
4396   MIB.addImm(MI.getOperand(OpIdx).getImm() & AMDGPU::CPol::ALL);
4397 }
4398 
renderExtractSWZ(MachineInstrBuilder & MIB,const MachineInstr & MI,int OpIdx) const4399 void AMDGPUInstructionSelector::renderExtractSWZ(MachineInstrBuilder &MIB,
4400                                                  const MachineInstr &MI,
4401                                                  int OpIdx) const {
4402   assert(OpIdx >= 0 && "expected to match an immediate operand");
4403   MIB.addImm((MI.getOperand(OpIdx).getImm() >> 3) & 1);
4404 }
4405 
renderSetGLC(MachineInstrBuilder & MIB,const MachineInstr & MI,int OpIdx) const4406 void AMDGPUInstructionSelector::renderSetGLC(MachineInstrBuilder &MIB,
4407                                              const MachineInstr &MI,
4408                                              int OpIdx) const {
4409   assert(OpIdx >= 0 && "expected to match an immediate operand");
4410   MIB.addImm(MI.getOperand(OpIdx).getImm() | AMDGPU::CPol::GLC);
4411 }
4412 
renderFrameIndex(MachineInstrBuilder & MIB,const MachineInstr & MI,int OpIdx) const4413 void AMDGPUInstructionSelector::renderFrameIndex(MachineInstrBuilder &MIB,
4414                                                  const MachineInstr &MI,
4415                                                  int OpIdx) const {
4416   MIB.addFrameIndex((MI.getOperand(1).getIndex()));
4417 }
4418 
isInlineImmediate16(int64_t Imm) const4419 bool AMDGPUInstructionSelector::isInlineImmediate16(int64_t Imm) const {
4420   return AMDGPU::isInlinableLiteral16(Imm, STI.hasInv2PiInlineImm());
4421 }
4422 
isInlineImmediate32(int64_t Imm) const4423 bool AMDGPUInstructionSelector::isInlineImmediate32(int64_t Imm) const {
4424   return AMDGPU::isInlinableLiteral32(Imm, STI.hasInv2PiInlineImm());
4425 }
4426 
isInlineImmediate64(int64_t Imm) const4427 bool AMDGPUInstructionSelector::isInlineImmediate64(int64_t Imm) const {
4428   return AMDGPU::isInlinableLiteral64(Imm, STI.hasInv2PiInlineImm());
4429 }
4430 
isInlineImmediate(const APFloat & Imm) const4431 bool AMDGPUInstructionSelector::isInlineImmediate(const APFloat &Imm) const {
4432   return TII.isInlineConstant(Imm);
4433 }
4434