xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===-- AMDGPUISelDAGToDAG.cpp - A dag to dag inst selector for AMDGPU ----===//
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 //
9 /// \file
10 /// Defines an instruction selector for the AMDGPU target.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AMDGPUISelDAGToDAG.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "AMDGPUSubtarget.h"
18 #include "AMDGPUTargetMachine.h"
19 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
20 #include "MCTargetDesc/R600MCTargetDesc.h"
21 #include "R600RegisterInfo.h"
22 #include "SIISelLowering.h"
23 #include "SIMachineFunctionInfo.h"
24 #include "llvm/Analysis/UniformityAnalysis.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/SelectionDAGNodes.h"
30 #include "llvm/IR/IntrinsicsAMDGPU.h"
31 #include "llvm/InitializePasses.h"
32 #include "llvm/Support/ErrorHandling.h"
33 
34 #ifdef EXPENSIVE_CHECKS
35 #include "llvm/Analysis/LoopInfo.h"
36 #include "llvm/IR/Dominators.h"
37 #endif
38 
39 #define DEBUG_TYPE "amdgpu-isel"
40 
41 using namespace llvm;
42 
43 //===----------------------------------------------------------------------===//
44 // Instruction Selector Implementation
45 //===----------------------------------------------------------------------===//
46 
47 namespace {
48 static SDValue stripBitcast(SDValue Val) {
49   return Val.getOpcode() == ISD::BITCAST ? Val.getOperand(0) : Val;
50 }
51 
52 // Figure out if this is really an extract of the high 16-bits of a dword.
53 static bool isExtractHiElt(SDValue In, SDValue &Out) {
54   In = stripBitcast(In);
55 
56   if (In.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
57     if (ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(In.getOperand(1))) {
58       if (!Idx->isOne())
59         return false;
60       Out = In.getOperand(0);
61       return true;
62     }
63   }
64 
65   if (In.getOpcode() != ISD::TRUNCATE)
66     return false;
67 
68   SDValue Srl = In.getOperand(0);
69   if (Srl.getOpcode() == ISD::SRL) {
70     if (ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
71       if (ShiftAmt->getZExtValue() == 16) {
72         Out = stripBitcast(Srl.getOperand(0));
73         return true;
74       }
75     }
76   }
77 
78   return false;
79 }
80 
81 // Look through operations that obscure just looking at the low 16-bits of the
82 // same register.
83 static SDValue stripExtractLoElt(SDValue In) {
84   if (In.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
85     SDValue Idx = In.getOperand(1);
86     if (isNullConstant(Idx) && In.getValueSizeInBits() <= 32)
87       return In.getOperand(0);
88   }
89 
90   if (In.getOpcode() == ISD::TRUNCATE) {
91     SDValue Src = In.getOperand(0);
92     if (Src.getValueType().getSizeInBits() == 32)
93       return stripBitcast(Src);
94   }
95 
96   return In;
97 }
98 
99 } // end anonymous namespace
100 
101 INITIALIZE_PASS_BEGIN(AMDGPUDAGToDAGISel, "amdgpu-isel",
102                       "AMDGPU DAG->DAG Pattern Instruction Selection", false, false)
103 INITIALIZE_PASS_DEPENDENCY(AMDGPUArgumentUsageInfo)
104 INITIALIZE_PASS_DEPENDENCY(AMDGPUPerfHintAnalysis)
105 INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
106 #ifdef EXPENSIVE_CHECKS
107 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
108 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
109 #endif
110 INITIALIZE_PASS_END(AMDGPUDAGToDAGISel, "amdgpu-isel",
111                     "AMDGPU DAG->DAG Pattern Instruction Selection", false, false)
112 
113 /// This pass converts a legalized DAG into a AMDGPU-specific
114 // DAG, ready for instruction scheduling.
115 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine &TM,
116                                         CodeGenOptLevel OptLevel) {
117   return new AMDGPUDAGToDAGISel(TM, OptLevel);
118 }
119 
120 AMDGPUDAGToDAGISel::AMDGPUDAGToDAGISel(TargetMachine &TM,
121                                        CodeGenOptLevel OptLevel)
122     : SelectionDAGISel(ID, TM, OptLevel) {
123   EnableLateStructurizeCFG = AMDGPUTargetMachine::EnableLateStructurizeCFG;
124 }
125 
126 bool AMDGPUDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
127 #ifdef EXPENSIVE_CHECKS
128   DominatorTree & DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
129   LoopInfo * LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
130   for (auto &L : LI->getLoopsInPreorder()) {
131     assert(L->isLCSSAForm(DT));
132   }
133 #endif
134   Subtarget = &MF.getSubtarget<GCNSubtarget>();
135   Mode = SIModeRegisterDefaults(MF.getFunction(), *Subtarget);
136   return SelectionDAGISel::runOnMachineFunction(MF);
137 }
138 
139 bool AMDGPUDAGToDAGISel::fp16SrcZerosHighBits(unsigned Opc) const {
140   // XXX - only need to list legal operations.
141   switch (Opc) {
142   case ISD::FADD:
143   case ISD::FSUB:
144   case ISD::FMUL:
145   case ISD::FDIV:
146   case ISD::FREM:
147   case ISD::FCANONICALIZE:
148   case ISD::UINT_TO_FP:
149   case ISD::SINT_TO_FP:
150   case ISD::FABS:
151     // Fabs is lowered to a bit operation, but it's an and which will clear the
152     // high bits anyway.
153   case ISD::FSQRT:
154   case ISD::FSIN:
155   case ISD::FCOS:
156   case ISD::FPOWI:
157   case ISD::FPOW:
158   case ISD::FLOG:
159   case ISD::FLOG2:
160   case ISD::FLOG10:
161   case ISD::FEXP:
162   case ISD::FEXP2:
163   case ISD::FCEIL:
164   case ISD::FTRUNC:
165   case ISD::FRINT:
166   case ISD::FNEARBYINT:
167   case ISD::FROUNDEVEN:
168   case ISD::FROUND:
169   case ISD::FFLOOR:
170   case ISD::FMINNUM:
171   case ISD::FMAXNUM:
172   case ISD::FLDEXP:
173   case AMDGPUISD::FRACT:
174   case AMDGPUISD::CLAMP:
175   case AMDGPUISD::COS_HW:
176   case AMDGPUISD::SIN_HW:
177   case AMDGPUISD::FMIN3:
178   case AMDGPUISD::FMAX3:
179   case AMDGPUISD::FMED3:
180   case AMDGPUISD::FMAD_FTZ:
181   case AMDGPUISD::RCP:
182   case AMDGPUISD::RSQ:
183   case AMDGPUISD::RCP_IFLAG:
184     // On gfx10, all 16-bit instructions preserve the high bits.
185     return Subtarget->getGeneration() <= AMDGPUSubtarget::GFX9;
186   case ISD::FP_ROUND:
187     // We may select fptrunc (fma/mad) to mad_mixlo, which does not zero the
188     // high bits on gfx9.
189     // TODO: If we had the source node we could see if the source was fma/mad
190     return Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS;
191   case ISD::FMA:
192   case ISD::FMAD:
193   case AMDGPUISD::DIV_FIXUP:
194     return Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS;
195   default:
196     // fcopysign, select and others may be lowered to 32-bit bit operations
197     // which don't zero the high bits.
198     return false;
199   }
200 }
201 
202 void AMDGPUDAGToDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
203   AU.addRequired<AMDGPUArgumentUsageInfo>();
204   AU.addRequired<UniformityInfoWrapperPass>();
205 #ifdef EXPENSIVE_CHECKS
206   AU.addRequired<DominatorTreeWrapperPass>();
207   AU.addRequired<LoopInfoWrapperPass>();
208 #endif
209   SelectionDAGISel::getAnalysisUsage(AU);
210 }
211 
212 bool AMDGPUDAGToDAGISel::matchLoadD16FromBuildVector(SDNode *N) const {
213   assert(Subtarget->d16PreservesUnusedBits());
214   MVT VT = N->getValueType(0).getSimpleVT();
215   if (VT != MVT::v2i16 && VT != MVT::v2f16)
216     return false;
217 
218   SDValue Lo = N->getOperand(0);
219   SDValue Hi = N->getOperand(1);
220 
221   LoadSDNode *LdHi = dyn_cast<LoadSDNode>(stripBitcast(Hi));
222 
223   // build_vector lo, (load ptr) -> load_d16_hi ptr, lo
224   // build_vector lo, (zextload ptr from i8) -> load_d16_hi_u8 ptr, lo
225   // build_vector lo, (sextload ptr from i8) -> load_d16_hi_i8 ptr, lo
226 
227   // Need to check for possible indirect dependencies on the other half of the
228   // vector to avoid introducing a cycle.
229   if (LdHi && Hi.hasOneUse() && !LdHi->isPredecessorOf(Lo.getNode())) {
230     SDVTList VTList = CurDAG->getVTList(VT, MVT::Other);
231 
232     SDValue TiedIn = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Lo);
233     SDValue Ops[] = {
234       LdHi->getChain(), LdHi->getBasePtr(), TiedIn
235     };
236 
237     unsigned LoadOp = AMDGPUISD::LOAD_D16_HI;
238     if (LdHi->getMemoryVT() == MVT::i8) {
239       LoadOp = LdHi->getExtensionType() == ISD::SEXTLOAD ?
240         AMDGPUISD::LOAD_D16_HI_I8 : AMDGPUISD::LOAD_D16_HI_U8;
241     } else {
242       assert(LdHi->getMemoryVT() == MVT::i16);
243     }
244 
245     SDValue NewLoadHi =
246       CurDAG->getMemIntrinsicNode(LoadOp, SDLoc(LdHi), VTList,
247                                   Ops, LdHi->getMemoryVT(),
248                                   LdHi->getMemOperand());
249 
250     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), NewLoadHi);
251     CurDAG->ReplaceAllUsesOfValueWith(SDValue(LdHi, 1), NewLoadHi.getValue(1));
252     return true;
253   }
254 
255   // build_vector (load ptr), hi -> load_d16_lo ptr, hi
256   // build_vector (zextload ptr from i8), hi -> load_d16_lo_u8 ptr, hi
257   // build_vector (sextload ptr from i8), hi -> load_d16_lo_i8 ptr, hi
258   LoadSDNode *LdLo = dyn_cast<LoadSDNode>(stripBitcast(Lo));
259   if (LdLo && Lo.hasOneUse()) {
260     SDValue TiedIn = getHi16Elt(Hi);
261     if (!TiedIn || LdLo->isPredecessorOf(TiedIn.getNode()))
262       return false;
263 
264     SDVTList VTList = CurDAG->getVTList(VT, MVT::Other);
265     unsigned LoadOp = AMDGPUISD::LOAD_D16_LO;
266     if (LdLo->getMemoryVT() == MVT::i8) {
267       LoadOp = LdLo->getExtensionType() == ISD::SEXTLOAD ?
268         AMDGPUISD::LOAD_D16_LO_I8 : AMDGPUISD::LOAD_D16_LO_U8;
269     } else {
270       assert(LdLo->getMemoryVT() == MVT::i16);
271     }
272 
273     TiedIn = CurDAG->getNode(ISD::BITCAST, SDLoc(N), VT, TiedIn);
274 
275     SDValue Ops[] = {
276       LdLo->getChain(), LdLo->getBasePtr(), TiedIn
277     };
278 
279     SDValue NewLoadLo =
280       CurDAG->getMemIntrinsicNode(LoadOp, SDLoc(LdLo), VTList,
281                                   Ops, LdLo->getMemoryVT(),
282                                   LdLo->getMemOperand());
283 
284     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), NewLoadLo);
285     CurDAG->ReplaceAllUsesOfValueWith(SDValue(LdLo, 1), NewLoadLo.getValue(1));
286     return true;
287   }
288 
289   return false;
290 }
291 
292 void AMDGPUDAGToDAGISel::PreprocessISelDAG() {
293   if (!Subtarget->d16PreservesUnusedBits())
294     return;
295 
296   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
297 
298   bool MadeChange = false;
299   while (Position != CurDAG->allnodes_begin()) {
300     SDNode *N = &*--Position;
301     if (N->use_empty())
302       continue;
303 
304     switch (N->getOpcode()) {
305     case ISD::BUILD_VECTOR:
306       // TODO: Match load d16 from shl (extload:i16), 16
307       MadeChange |= matchLoadD16FromBuildVector(N);
308       break;
309     default:
310       break;
311     }
312   }
313 
314   if (MadeChange) {
315     CurDAG->RemoveDeadNodes();
316     LLVM_DEBUG(dbgs() << "After PreProcess:\n";
317                CurDAG->dump(););
318   }
319 }
320 
321 bool AMDGPUDAGToDAGISel::isInlineImmediate(const SDNode *N) const {
322   if (N->isUndef())
323     return true;
324 
325   const SIInstrInfo *TII = Subtarget->getInstrInfo();
326   if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N))
327     return TII->isInlineConstant(C->getAPIntValue());
328 
329   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N))
330     return TII->isInlineConstant(C->getValueAPF().bitcastToAPInt());
331 
332   return false;
333 }
334 
335 /// Determine the register class for \p OpNo
336 /// \returns The register class of the virtual register that will be used for
337 /// the given operand number \OpNo or NULL if the register class cannot be
338 /// determined.
339 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
340                                                           unsigned OpNo) const {
341   if (!N->isMachineOpcode()) {
342     if (N->getOpcode() == ISD::CopyToReg) {
343       Register Reg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
344       if (Reg.isVirtual()) {
345         MachineRegisterInfo &MRI = CurDAG->getMachineFunction().getRegInfo();
346         return MRI.getRegClass(Reg);
347       }
348 
349       const SIRegisterInfo *TRI
350         = static_cast<const GCNSubtarget *>(Subtarget)->getRegisterInfo();
351       return TRI->getPhysRegBaseClass(Reg);
352     }
353 
354     return nullptr;
355   }
356 
357   switch (N->getMachineOpcode()) {
358   default: {
359     const MCInstrDesc &Desc =
360         Subtarget->getInstrInfo()->get(N->getMachineOpcode());
361     unsigned OpIdx = Desc.getNumDefs() + OpNo;
362     if (OpIdx >= Desc.getNumOperands())
363       return nullptr;
364     int RegClass = Desc.operands()[OpIdx].RegClass;
365     if (RegClass == -1)
366       return nullptr;
367 
368     return Subtarget->getRegisterInfo()->getRegClass(RegClass);
369   }
370   case AMDGPU::REG_SEQUENCE: {
371     unsigned RCID = N->getConstantOperandVal(0);
372     const TargetRegisterClass *SuperRC =
373         Subtarget->getRegisterInfo()->getRegClass(RCID);
374 
375     SDValue SubRegOp = N->getOperand(OpNo + 1);
376     unsigned SubRegIdx = SubRegOp->getAsZExtVal();
377     return Subtarget->getRegisterInfo()->getSubClassWithSubReg(SuperRC,
378                                                               SubRegIdx);
379   }
380   }
381 }
382 
383 SDNode *AMDGPUDAGToDAGISel::glueCopyToOp(SDNode *N, SDValue NewChain,
384                                          SDValue Glue) const {
385   SmallVector <SDValue, 8> Ops;
386   Ops.push_back(NewChain); // Replace the chain.
387   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
388     Ops.push_back(N->getOperand(i));
389 
390   Ops.push_back(Glue);
391   return CurDAG->MorphNodeTo(N, N->getOpcode(), N->getVTList(), Ops);
392 }
393 
394 SDNode *AMDGPUDAGToDAGISel::glueCopyToM0(SDNode *N, SDValue Val) const {
395   const SITargetLowering& Lowering =
396     *static_cast<const SITargetLowering*>(getTargetLowering());
397 
398   assert(N->getOperand(0).getValueType() == MVT::Other && "Expected chain");
399 
400   SDValue M0 = Lowering.copyToM0(*CurDAG, N->getOperand(0), SDLoc(N), Val);
401   return glueCopyToOp(N, M0, M0.getValue(1));
402 }
403 
404 SDNode *AMDGPUDAGToDAGISel::glueCopyToM0LDSInit(SDNode *N) const {
405   unsigned AS = cast<MemSDNode>(N)->getAddressSpace();
406   if (AS == AMDGPUAS::LOCAL_ADDRESS) {
407     if (Subtarget->ldsRequiresM0Init())
408       return glueCopyToM0(N, CurDAG->getTargetConstant(-1, SDLoc(N), MVT::i32));
409   } else if (AS == AMDGPUAS::REGION_ADDRESS) {
410     MachineFunction &MF = CurDAG->getMachineFunction();
411     unsigned Value = MF.getInfo<SIMachineFunctionInfo>()->getGDSSize();
412     return
413         glueCopyToM0(N, CurDAG->getTargetConstant(Value, SDLoc(N), MVT::i32));
414   }
415   return N;
416 }
417 
418 MachineSDNode *AMDGPUDAGToDAGISel::buildSMovImm64(SDLoc &DL, uint64_t Imm,
419                                                   EVT VT) const {
420   SDNode *Lo = CurDAG->getMachineNode(
421       AMDGPU::S_MOV_B32, DL, MVT::i32,
422       CurDAG->getTargetConstant(Imm & 0xFFFFFFFF, DL, MVT::i32));
423   SDNode *Hi =
424       CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
425                              CurDAG->getTargetConstant(Imm >> 32, DL, MVT::i32));
426   const SDValue Ops[] = {
427       CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
428       SDValue(Lo, 0), CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
429       SDValue(Hi, 0), CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32)};
430 
431   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL, VT, Ops);
432 }
433 
434 void AMDGPUDAGToDAGISel::SelectBuildVector(SDNode *N, unsigned RegClassID) {
435   EVT VT = N->getValueType(0);
436   unsigned NumVectorElts = VT.getVectorNumElements();
437   EVT EltVT = VT.getVectorElementType();
438   SDLoc DL(N);
439   SDValue RegClass = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
440 
441   if (NumVectorElts == 1) {
442     CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, EltVT, N->getOperand(0),
443                          RegClass);
444     return;
445   }
446 
447   assert(NumVectorElts <= 32 && "Vectors with more than 32 elements not "
448                                   "supported yet");
449   // 32 = Max Num Vector Elements
450   // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
451   // 1 = Vector Register Class
452   SmallVector<SDValue, 32 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
453 
454   bool IsGCN = CurDAG->getSubtarget().getTargetTriple().getArch() ==
455                Triple::amdgcn;
456   RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
457   bool IsRegSeq = true;
458   unsigned NOps = N->getNumOperands();
459   for (unsigned i = 0; i < NOps; i++) {
460     // XXX: Why is this here?
461     if (isa<RegisterSDNode>(N->getOperand(i))) {
462       IsRegSeq = false;
463       break;
464     }
465     unsigned Sub = IsGCN ? SIRegisterInfo::getSubRegFromChannel(i)
466                          : R600RegisterInfo::getSubRegFromChannel(i);
467     RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
468     RegSeqArgs[1 + (2 * i) + 1] = CurDAG->getTargetConstant(Sub, DL, MVT::i32);
469   }
470   if (NOps != NumVectorElts) {
471     // Fill in the missing undef elements if this was a scalar_to_vector.
472     assert(N->getOpcode() == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
473     MachineSDNode *ImpDef = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
474                                                    DL, EltVT);
475     for (unsigned i = NOps; i < NumVectorElts; ++i) {
476       unsigned Sub = IsGCN ? SIRegisterInfo::getSubRegFromChannel(i)
477                            : R600RegisterInfo::getSubRegFromChannel(i);
478       RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
479       RegSeqArgs[1 + (2 * i) + 1] =
480           CurDAG->getTargetConstant(Sub, DL, MVT::i32);
481     }
482   }
483 
484   if (!IsRegSeq)
485     SelectCode(N);
486   CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(), RegSeqArgs);
487 }
488 
489 void AMDGPUDAGToDAGISel::Select(SDNode *N) {
490   unsigned int Opc = N->getOpcode();
491   if (N->isMachineOpcode()) {
492     N->setNodeId(-1);
493     return;   // Already selected.
494   }
495 
496   // isa<MemSDNode> almost works but is slightly too permissive for some DS
497   // intrinsics.
498   if (Opc == ISD::LOAD || Opc == ISD::STORE || isa<AtomicSDNode>(N) ||
499       Opc == AMDGPUISD::ATOMIC_LOAD_FMIN ||
500       Opc == AMDGPUISD::ATOMIC_LOAD_FMAX) {
501     N = glueCopyToM0LDSInit(N);
502     SelectCode(N);
503     return;
504   }
505 
506   switch (Opc) {
507   default:
508     break;
509   // We are selecting i64 ADD here instead of custom lower it during
510   // DAG legalization, so we can fold some i64 ADDs used for address
511   // calculation into the LOAD and STORE instructions.
512   case ISD::ADDC:
513   case ISD::ADDE:
514   case ISD::SUBC:
515   case ISD::SUBE: {
516     if (N->getValueType(0) != MVT::i64)
517       break;
518 
519     SelectADD_SUB_I64(N);
520     return;
521   }
522   case ISD::UADDO_CARRY:
523   case ISD::USUBO_CARRY:
524     if (N->getValueType(0) != MVT::i32)
525       break;
526 
527     SelectAddcSubb(N);
528     return;
529   case ISD::UADDO:
530   case ISD::USUBO: {
531     SelectUADDO_USUBO(N);
532     return;
533   }
534   case AMDGPUISD::FMUL_W_CHAIN: {
535     SelectFMUL_W_CHAIN(N);
536     return;
537   }
538   case AMDGPUISD::FMA_W_CHAIN: {
539     SelectFMA_W_CHAIN(N);
540     return;
541   }
542 
543   case ISD::SCALAR_TO_VECTOR:
544   case ISD::BUILD_VECTOR: {
545     EVT VT = N->getValueType(0);
546     unsigned NumVectorElts = VT.getVectorNumElements();
547     if (VT.getScalarSizeInBits() == 16) {
548       if (Opc == ISD::BUILD_VECTOR && NumVectorElts == 2) {
549         if (SDNode *Packed = packConstantV2I16(N, *CurDAG)) {
550           ReplaceNode(N, Packed);
551           return;
552         }
553       }
554 
555       break;
556     }
557 
558     assert(VT.getVectorElementType().bitsEq(MVT::i32));
559     unsigned RegClassID =
560         SIRegisterInfo::getSGPRClassForBitWidth(NumVectorElts * 32)->getID();
561     SelectBuildVector(N, RegClassID);
562     return;
563   }
564   case ISD::BUILD_PAIR: {
565     SDValue RC, SubReg0, SubReg1;
566     SDLoc DL(N);
567     if (N->getValueType(0) == MVT::i128) {
568       RC = CurDAG->getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32);
569       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32);
570       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32);
571     } else if (N->getValueType(0) == MVT::i64) {
572       RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32);
573       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
574       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
575     } else {
576       llvm_unreachable("Unhandled value type for BUILD_PAIR");
577     }
578     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
579                             N->getOperand(1), SubReg1 };
580     ReplaceNode(N, CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL,
581                                           N->getValueType(0), Ops));
582     return;
583   }
584 
585   case ISD::Constant:
586   case ISD::ConstantFP: {
587     if (N->getValueType(0).getSizeInBits() != 64 || isInlineImmediate(N))
588       break;
589 
590     uint64_t Imm;
591     if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(N)) {
592       Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
593       if (AMDGPU::isValid32BitLiteral(Imm, true))
594         break;
595     } else {
596       ConstantSDNode *C = cast<ConstantSDNode>(N);
597       Imm = C->getZExtValue();
598       if (AMDGPU::isValid32BitLiteral(Imm, false))
599         break;
600     }
601 
602     SDLoc DL(N);
603     ReplaceNode(N, buildSMovImm64(DL, Imm, N->getValueType(0)));
604     return;
605   }
606   case AMDGPUISD::BFE_I32:
607   case AMDGPUISD::BFE_U32: {
608     // There is a scalar version available, but unlike the vector version which
609     // has a separate operand for the offset and width, the scalar version packs
610     // the width and offset into a single operand. Try to move to the scalar
611     // version if the offsets are constant, so that we can try to keep extended
612     // loads of kernel arguments in SGPRs.
613 
614     // TODO: Technically we could try to pattern match scalar bitshifts of
615     // dynamic values, but it's probably not useful.
616     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
617     if (!Offset)
618       break;
619 
620     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
621     if (!Width)
622       break;
623 
624     bool Signed = Opc == AMDGPUISD::BFE_I32;
625 
626     uint32_t OffsetVal = Offset->getZExtValue();
627     uint32_t WidthVal = Width->getZExtValue();
628 
629     ReplaceNode(N, getBFE32(Signed, SDLoc(N), N->getOperand(0), OffsetVal,
630                             WidthVal));
631     return;
632   }
633   case AMDGPUISD::DIV_SCALE: {
634     SelectDIV_SCALE(N);
635     return;
636   }
637   case AMDGPUISD::MAD_I64_I32:
638   case AMDGPUISD::MAD_U64_U32: {
639     SelectMAD_64_32(N);
640     return;
641   }
642   case ISD::SMUL_LOHI:
643   case ISD::UMUL_LOHI:
644     return SelectMUL_LOHI(N);
645   case ISD::CopyToReg: {
646     const SITargetLowering& Lowering =
647       *static_cast<const SITargetLowering*>(getTargetLowering());
648     N = Lowering.legalizeTargetIndependentNode(N, *CurDAG);
649     break;
650   }
651   case ISD::AND:
652   case ISD::SRL:
653   case ISD::SRA:
654   case ISD::SIGN_EXTEND_INREG:
655     if (N->getValueType(0) != MVT::i32)
656       break;
657 
658     SelectS_BFE(N);
659     return;
660   case ISD::BRCOND:
661     SelectBRCOND(N);
662     return;
663   case ISD::FP_EXTEND:
664     SelectFP_EXTEND(N);
665     return;
666   case AMDGPUISD::CVT_PKRTZ_F16_F32:
667   case AMDGPUISD::CVT_PKNORM_I16_F32:
668   case AMDGPUISD::CVT_PKNORM_U16_F32:
669   case AMDGPUISD::CVT_PK_U16_U32:
670   case AMDGPUISD::CVT_PK_I16_I32: {
671     // Hack around using a legal type if f16 is illegal.
672     if (N->getValueType(0) == MVT::i32) {
673       MVT NewVT = Opc == AMDGPUISD::CVT_PKRTZ_F16_F32 ? MVT::v2f16 : MVT::v2i16;
674       N = CurDAG->MorphNodeTo(N, N->getOpcode(), CurDAG->getVTList(NewVT),
675                               { N->getOperand(0), N->getOperand(1) });
676       SelectCode(N);
677       return;
678     }
679 
680     break;
681   }
682   case ISD::INTRINSIC_W_CHAIN: {
683     SelectINTRINSIC_W_CHAIN(N);
684     return;
685   }
686   case ISD::INTRINSIC_WO_CHAIN: {
687     SelectINTRINSIC_WO_CHAIN(N);
688     return;
689   }
690   case ISD::INTRINSIC_VOID: {
691     SelectINTRINSIC_VOID(N);
692     return;
693   }
694   case AMDGPUISD::WAVE_ADDRESS: {
695     SelectWAVE_ADDRESS(N);
696     return;
697   }
698   case ISD::STACKRESTORE: {
699     SelectSTACKRESTORE(N);
700     return;
701   }
702   }
703 
704   SelectCode(N);
705 }
706 
707 bool AMDGPUDAGToDAGISel::isUniformBr(const SDNode *N) const {
708   const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
709   const Instruction *Term = BB->getTerminator();
710   return Term->getMetadata("amdgpu.uniform") ||
711          Term->getMetadata("structurizecfg.uniform");
712 }
713 
714 bool AMDGPUDAGToDAGISel::isUnneededShiftMask(const SDNode *N,
715                                              unsigned ShAmtBits) const {
716   assert(N->getOpcode() == ISD::AND);
717 
718   const APInt &RHS = N->getConstantOperandAPInt(1);
719   if (RHS.countr_one() >= ShAmtBits)
720     return true;
721 
722   const APInt &LHSKnownZeros = CurDAG->computeKnownBits(N->getOperand(0)).Zero;
723   return (LHSKnownZeros | RHS).countr_one() >= ShAmtBits;
724 }
725 
726 static bool getBaseWithOffsetUsingSplitOR(SelectionDAG &DAG, SDValue Addr,
727                                           SDValue &N0, SDValue &N1) {
728   if (Addr.getValueType() == MVT::i64 && Addr.getOpcode() == ISD::BITCAST &&
729       Addr.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
730     // As we split 64-bit `or` earlier, it's complicated pattern to match, i.e.
731     // (i64 (bitcast (v2i32 (build_vector
732     //                        (or (extract_vector_elt V, 0), OFFSET),
733     //                        (extract_vector_elt V, 1)))))
734     SDValue Lo = Addr.getOperand(0).getOperand(0);
735     if (Lo.getOpcode() == ISD::OR && DAG.isBaseWithConstantOffset(Lo)) {
736       SDValue BaseLo = Lo.getOperand(0);
737       SDValue BaseHi = Addr.getOperand(0).getOperand(1);
738       // Check that split base (Lo and Hi) are extracted from the same one.
739       if (BaseLo.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
740           BaseHi.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
741           BaseLo.getOperand(0) == BaseHi.getOperand(0) &&
742           // Lo is statically extracted from index 0.
743           isa<ConstantSDNode>(BaseLo.getOperand(1)) &&
744           BaseLo.getConstantOperandVal(1) == 0 &&
745           // Hi is statically extracted from index 0.
746           isa<ConstantSDNode>(BaseHi.getOperand(1)) &&
747           BaseHi.getConstantOperandVal(1) == 1) {
748         N0 = BaseLo.getOperand(0).getOperand(0);
749         N1 = Lo.getOperand(1);
750         return true;
751       }
752     }
753   }
754   return false;
755 }
756 
757 bool AMDGPUDAGToDAGISel::isBaseWithConstantOffset64(SDValue Addr, SDValue &LHS,
758                                                     SDValue &RHS) const {
759   if (CurDAG->isBaseWithConstantOffset(Addr)) {
760     LHS = Addr.getOperand(0);
761     RHS = Addr.getOperand(1);
762     return true;
763   }
764 
765   if (getBaseWithOffsetUsingSplitOR(*CurDAG, Addr, LHS, RHS)) {
766     assert(LHS && RHS && isa<ConstantSDNode>(RHS));
767     return true;
768   }
769 
770   return false;
771 }
772 
773 StringRef AMDGPUDAGToDAGISel::getPassName() const {
774   return "AMDGPU DAG->DAG Pattern Instruction Selection";
775 }
776 
777 //===----------------------------------------------------------------------===//
778 // Complex Patterns
779 //===----------------------------------------------------------------------===//
780 
781 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
782                                             SDValue &Offset) {
783   return false;
784 }
785 
786 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
787                                             SDValue &Offset) {
788   ConstantSDNode *C;
789   SDLoc DL(Addr);
790 
791   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
792     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
793     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
794   } else if ((Addr.getOpcode() == AMDGPUISD::DWORDADDR) &&
795              (C = dyn_cast<ConstantSDNode>(Addr.getOperand(0)))) {
796     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
797     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
798   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
799             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
800     Base = Addr.getOperand(0);
801     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
802   } else {
803     Base = Addr;
804     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
805   }
806 
807   return true;
808 }
809 
810 SDValue AMDGPUDAGToDAGISel::getMaterializedScalarImm32(int64_t Val,
811                                                        const SDLoc &DL) const {
812   SDNode *Mov = CurDAG->getMachineNode(
813     AMDGPU::S_MOV_B32, DL, MVT::i32,
814     CurDAG->getTargetConstant(Val, DL, MVT::i32));
815   return SDValue(Mov, 0);
816 }
817 
818 // FIXME: Should only handle uaddo_carry/usubo_carry
819 void AMDGPUDAGToDAGISel::SelectADD_SUB_I64(SDNode *N) {
820   SDLoc DL(N);
821   SDValue LHS = N->getOperand(0);
822   SDValue RHS = N->getOperand(1);
823 
824   unsigned Opcode = N->getOpcode();
825   bool ConsumeCarry = (Opcode == ISD::ADDE || Opcode == ISD::SUBE);
826   bool ProduceCarry =
827       ConsumeCarry || Opcode == ISD::ADDC || Opcode == ISD::SUBC;
828   bool IsAdd = Opcode == ISD::ADD || Opcode == ISD::ADDC || Opcode == ISD::ADDE;
829 
830   SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
831   SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
832 
833   SDNode *Lo0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
834                                        DL, MVT::i32, LHS, Sub0);
835   SDNode *Hi0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
836                                        DL, MVT::i32, LHS, Sub1);
837 
838   SDNode *Lo1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
839                                        DL, MVT::i32, RHS, Sub0);
840   SDNode *Hi1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
841                                        DL, MVT::i32, RHS, Sub1);
842 
843   SDVTList VTList = CurDAG->getVTList(MVT::i32, MVT::Glue);
844 
845   static const unsigned OpcMap[2][2][2] = {
846       {{AMDGPU::S_SUB_U32, AMDGPU::S_ADD_U32},
847        {AMDGPU::V_SUB_CO_U32_e32, AMDGPU::V_ADD_CO_U32_e32}},
848       {{AMDGPU::S_SUBB_U32, AMDGPU::S_ADDC_U32},
849        {AMDGPU::V_SUBB_U32_e32, AMDGPU::V_ADDC_U32_e32}}};
850 
851   unsigned Opc = OpcMap[0][N->isDivergent()][IsAdd];
852   unsigned CarryOpc = OpcMap[1][N->isDivergent()][IsAdd];
853 
854   SDNode *AddLo;
855   if (!ConsumeCarry) {
856     SDValue Args[] = { SDValue(Lo0, 0), SDValue(Lo1, 0) };
857     AddLo = CurDAG->getMachineNode(Opc, DL, VTList, Args);
858   } else {
859     SDValue Args[] = { SDValue(Lo0, 0), SDValue(Lo1, 0), N->getOperand(2) };
860     AddLo = CurDAG->getMachineNode(CarryOpc, DL, VTList, Args);
861   }
862   SDValue AddHiArgs[] = {
863     SDValue(Hi0, 0),
864     SDValue(Hi1, 0),
865     SDValue(AddLo, 1)
866   };
867   SDNode *AddHi = CurDAG->getMachineNode(CarryOpc, DL, VTList, AddHiArgs);
868 
869   SDValue RegSequenceArgs[] = {
870     CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
871     SDValue(AddLo,0),
872     Sub0,
873     SDValue(AddHi,0),
874     Sub1,
875   };
876   SDNode *RegSequence = CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, DL,
877                                                MVT::i64, RegSequenceArgs);
878 
879   if (ProduceCarry) {
880     // Replace the carry-use
881     ReplaceUses(SDValue(N, 1), SDValue(AddHi, 1));
882   }
883 
884   // Replace the remaining uses.
885   ReplaceNode(N, RegSequence);
886 }
887 
888 void AMDGPUDAGToDAGISel::SelectAddcSubb(SDNode *N) {
889   SDLoc DL(N);
890   SDValue LHS = N->getOperand(0);
891   SDValue RHS = N->getOperand(1);
892   SDValue CI = N->getOperand(2);
893 
894   if (N->isDivergent()) {
895     unsigned Opc = N->getOpcode() == ISD::UADDO_CARRY ? AMDGPU::V_ADDC_U32_e64
896                                                       : AMDGPU::V_SUBB_U32_e64;
897     CurDAG->SelectNodeTo(
898         N, Opc, N->getVTList(),
899         {LHS, RHS, CI,
900          CurDAG->getTargetConstant(0, {}, MVT::i1) /*clamp bit*/});
901   } else {
902     unsigned Opc = N->getOpcode() == ISD::UADDO_CARRY ? AMDGPU::S_ADD_CO_PSEUDO
903                                                       : AMDGPU::S_SUB_CO_PSEUDO;
904     CurDAG->SelectNodeTo(N, Opc, N->getVTList(), {LHS, RHS, CI});
905   }
906 }
907 
908 void AMDGPUDAGToDAGISel::SelectUADDO_USUBO(SDNode *N) {
909   // The name of the opcodes are misleading. v_add_i32/v_sub_i32 have unsigned
910   // carry out despite the _i32 name. These were renamed in VI to _U32.
911   // FIXME: We should probably rename the opcodes here.
912   bool IsAdd = N->getOpcode() == ISD::UADDO;
913   bool IsVALU = N->isDivergent();
914 
915   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;
916        ++UI)
917     if (UI.getUse().getResNo() == 1) {
918       if ((IsAdd && (UI->getOpcode() != ISD::UADDO_CARRY)) ||
919           (!IsAdd && (UI->getOpcode() != ISD::USUBO_CARRY))) {
920         IsVALU = true;
921         break;
922       }
923     }
924 
925   if (IsVALU) {
926     unsigned Opc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
927 
928     CurDAG->SelectNodeTo(
929         N, Opc, N->getVTList(),
930         {N->getOperand(0), N->getOperand(1),
931          CurDAG->getTargetConstant(0, {}, MVT::i1) /*clamp bit*/});
932   } else {
933     unsigned Opc = N->getOpcode() == ISD::UADDO ? AMDGPU::S_UADDO_PSEUDO
934                                                 : AMDGPU::S_USUBO_PSEUDO;
935 
936     CurDAG->SelectNodeTo(N, Opc, N->getVTList(),
937                          {N->getOperand(0), N->getOperand(1)});
938   }
939 }
940 
941 void AMDGPUDAGToDAGISel::SelectFMA_W_CHAIN(SDNode *N) {
942   SDLoc SL(N);
943   //  src0_modifiers, src0,  src1_modifiers, src1, src2_modifiers, src2, clamp, omod
944   SDValue Ops[10];
945 
946   SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[6], Ops[7]);
947   SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
948   SelectVOP3Mods(N->getOperand(3), Ops[5], Ops[4]);
949   Ops[8] = N->getOperand(0);
950   Ops[9] = N->getOperand(4);
951 
952   // If there are no source modifiers, prefer fmac over fma because it can use
953   // the smaller VOP2 encoding.
954   bool UseFMAC = Subtarget->hasDLInsts() &&
955                  cast<ConstantSDNode>(Ops[0])->isZero() &&
956                  cast<ConstantSDNode>(Ops[2])->isZero() &&
957                  cast<ConstantSDNode>(Ops[4])->isZero();
958   unsigned Opcode = UseFMAC ? AMDGPU::V_FMAC_F32_e64 : AMDGPU::V_FMA_F32_e64;
959   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), Ops);
960 }
961 
962 void AMDGPUDAGToDAGISel::SelectFMUL_W_CHAIN(SDNode *N) {
963   SDLoc SL(N);
964   //    src0_modifiers, src0,  src1_modifiers, src1, clamp, omod
965   SDValue Ops[8];
966 
967   SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[4], Ops[5]);
968   SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
969   Ops[6] = N->getOperand(0);
970   Ops[7] = N->getOperand(3);
971 
972   CurDAG->SelectNodeTo(N, AMDGPU::V_MUL_F32_e64, N->getVTList(), Ops);
973 }
974 
975 // We need to handle this here because tablegen doesn't support matching
976 // instructions with multiple outputs.
977 void AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
978   SDLoc SL(N);
979   EVT VT = N->getValueType(0);
980 
981   assert(VT == MVT::f32 || VT == MVT::f64);
982 
983   unsigned Opc
984     = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64_e64 : AMDGPU::V_DIV_SCALE_F32_e64;
985 
986   // src0_modifiers, src0, src1_modifiers, src1, src2_modifiers, src2, clamp,
987   // omod
988   SDValue Ops[8];
989   SelectVOP3BMods0(N->getOperand(0), Ops[1], Ops[0], Ops[6], Ops[7]);
990   SelectVOP3BMods(N->getOperand(1), Ops[3], Ops[2]);
991   SelectVOP3BMods(N->getOperand(2), Ops[5], Ops[4]);
992   CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
993 }
994 
995 // We need to handle this here because tablegen doesn't support matching
996 // instructions with multiple outputs.
997 void AMDGPUDAGToDAGISel::SelectMAD_64_32(SDNode *N) {
998   SDLoc SL(N);
999   bool Signed = N->getOpcode() == AMDGPUISD::MAD_I64_I32;
1000   unsigned Opc;
1001   if (Subtarget->hasMADIntraFwdBug())
1002     Opc = Signed ? AMDGPU::V_MAD_I64_I32_gfx11_e64
1003                  : AMDGPU::V_MAD_U64_U32_gfx11_e64;
1004   else
1005     Opc = Signed ? AMDGPU::V_MAD_I64_I32_e64 : AMDGPU::V_MAD_U64_U32_e64;
1006 
1007   SDValue Clamp = CurDAG->getTargetConstant(0, SL, MVT::i1);
1008   SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
1009                     Clamp };
1010   CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
1011 }
1012 
1013 // We need to handle this here because tablegen doesn't support matching
1014 // instructions with multiple outputs.
1015 void AMDGPUDAGToDAGISel::SelectMUL_LOHI(SDNode *N) {
1016   SDLoc SL(N);
1017   bool Signed = N->getOpcode() == ISD::SMUL_LOHI;
1018   unsigned Opc;
1019   if (Subtarget->hasMADIntraFwdBug())
1020     Opc = Signed ? AMDGPU::V_MAD_I64_I32_gfx11_e64
1021                  : AMDGPU::V_MAD_U64_U32_gfx11_e64;
1022   else
1023     Opc = Signed ? AMDGPU::V_MAD_I64_I32_e64 : AMDGPU::V_MAD_U64_U32_e64;
1024 
1025   SDValue Zero = CurDAG->getTargetConstant(0, SL, MVT::i64);
1026   SDValue Clamp = CurDAG->getTargetConstant(0, SL, MVT::i1);
1027   SDValue Ops[] = {N->getOperand(0), N->getOperand(1), Zero, Clamp};
1028   SDNode *Mad = CurDAG->getMachineNode(Opc, SL, N->getVTList(), Ops);
1029   if (!SDValue(N, 0).use_empty()) {
1030     SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, SL, MVT::i32);
1031     SDNode *Lo = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, SL,
1032                                         MVT::i32, SDValue(Mad, 0), Sub0);
1033     ReplaceUses(SDValue(N, 0), SDValue(Lo, 0));
1034   }
1035   if (!SDValue(N, 1).use_empty()) {
1036     SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, SL, MVT::i32);
1037     SDNode *Hi = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, SL,
1038                                         MVT::i32, SDValue(Mad, 0), Sub1);
1039     ReplaceUses(SDValue(N, 1), SDValue(Hi, 0));
1040   }
1041   CurDAG->RemoveDeadNode(N);
1042 }
1043 
1044 bool AMDGPUDAGToDAGISel::isDSOffsetLegal(SDValue Base, unsigned Offset) const {
1045   if (!isUInt<16>(Offset))
1046     return false;
1047 
1048   if (!Base || Subtarget->hasUsableDSOffset() ||
1049       Subtarget->unsafeDSOffsetFoldingEnabled())
1050     return true;
1051 
1052   // On Southern Islands instruction with a negative base value and an offset
1053   // don't seem to work.
1054   return CurDAG->SignBitIsZero(Base);
1055 }
1056 
1057 bool AMDGPUDAGToDAGISel::SelectDS1Addr1Offset(SDValue Addr, SDValue &Base,
1058                                               SDValue &Offset) const {
1059   SDLoc DL(Addr);
1060   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1061     SDValue N0 = Addr.getOperand(0);
1062     SDValue N1 = Addr.getOperand(1);
1063     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1064     if (isDSOffsetLegal(N0, C1->getSExtValue())) {
1065       // (add n0, c0)
1066       Base = N0;
1067       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1068       return true;
1069     }
1070   } else if (Addr.getOpcode() == ISD::SUB) {
1071     // sub C, x -> add (sub 0, x), C
1072     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
1073       int64_t ByteOffset = C->getSExtValue();
1074       if (isDSOffsetLegal(SDValue(), ByteOffset)) {
1075         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1076 
1077         // XXX - This is kind of hacky. Create a dummy sub node so we can check
1078         // the known bits in isDSOffsetLegal. We need to emit the selected node
1079         // here, so this is thrown away.
1080         SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
1081                                       Zero, Addr.getOperand(1));
1082 
1083         if (isDSOffsetLegal(Sub, ByteOffset)) {
1084           SmallVector<SDValue, 3> Opnds;
1085           Opnds.push_back(Zero);
1086           Opnds.push_back(Addr.getOperand(1));
1087 
1088           // FIXME: Select to VOP3 version for with-carry.
1089           unsigned SubOp = AMDGPU::V_SUB_CO_U32_e32;
1090           if (Subtarget->hasAddNoCarry()) {
1091             SubOp = AMDGPU::V_SUB_U32_e64;
1092             Opnds.push_back(
1093                 CurDAG->getTargetConstant(0, {}, MVT::i1)); // clamp bit
1094           }
1095 
1096           MachineSDNode *MachineSub =
1097               CurDAG->getMachineNode(SubOp, DL, MVT::i32, Opnds);
1098 
1099           Base = SDValue(MachineSub, 0);
1100           Offset = CurDAG->getTargetConstant(ByteOffset, DL, MVT::i16);
1101           return true;
1102         }
1103       }
1104     }
1105   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1106     // If we have a constant address, prefer to put the constant into the
1107     // offset. This can save moves to load the constant address since multiple
1108     // operations can share the zero base address register, and enables merging
1109     // into read2 / write2 instructions.
1110 
1111     SDLoc DL(Addr);
1112 
1113     if (isDSOffsetLegal(SDValue(), CAddr->getZExtValue())) {
1114       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1115       MachineSDNode *MovZero = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
1116                                  DL, MVT::i32, Zero);
1117       Base = SDValue(MovZero, 0);
1118       Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i16);
1119       return true;
1120     }
1121   }
1122 
1123   // default case
1124   Base = Addr;
1125   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i16);
1126   return true;
1127 }
1128 
1129 bool AMDGPUDAGToDAGISel::isDSOffset2Legal(SDValue Base, unsigned Offset0,
1130                                           unsigned Offset1,
1131                                           unsigned Size) const {
1132   if (Offset0 % Size != 0 || Offset1 % Size != 0)
1133     return false;
1134   if (!isUInt<8>(Offset0 / Size) || !isUInt<8>(Offset1 / Size))
1135     return false;
1136 
1137   if (!Base || Subtarget->hasUsableDSOffset() ||
1138       Subtarget->unsafeDSOffsetFoldingEnabled())
1139     return true;
1140 
1141   // On Southern Islands instruction with a negative base value and an offset
1142   // don't seem to work.
1143   return CurDAG->SignBitIsZero(Base);
1144 }
1145 
1146 // Return whether the operation has NoUnsignedWrap property.
1147 static bool isNoUnsignedWrap(SDValue Addr) {
1148   return (Addr.getOpcode() == ISD::ADD &&
1149           Addr->getFlags().hasNoUnsignedWrap()) ||
1150          Addr->getOpcode() == ISD::OR;
1151 }
1152 
1153 // Check that the base address of flat scratch load/store in the form of `base +
1154 // offset` is legal to be put in SGPR/VGPR (i.e. unsigned per hardware
1155 // requirement). We always treat the first operand as the base address here.
1156 bool AMDGPUDAGToDAGISel::isFlatScratchBaseLegal(SDValue Addr) const {
1157   if (isNoUnsignedWrap(Addr))
1158     return true;
1159 
1160   // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
1161   // values.
1162   if (AMDGPU::isGFX12Plus(*Subtarget))
1163     return true;
1164 
1165   auto LHS = Addr.getOperand(0);
1166   auto RHS = Addr.getOperand(1);
1167 
1168   // If the immediate offset is negative and within certain range, the base
1169   // address cannot also be negative. If the base is also negative, the sum
1170   // would be either negative or much larger than the valid range of scratch
1171   // memory a thread can access.
1172   ConstantSDNode *ImmOp = nullptr;
1173   if (Addr.getOpcode() == ISD::ADD && (ImmOp = dyn_cast<ConstantSDNode>(RHS))) {
1174     if (ImmOp->getSExtValue() < 0 && ImmOp->getSExtValue() > -0x40000000)
1175       return true;
1176   }
1177 
1178   return CurDAG->SignBitIsZero(LHS);
1179 }
1180 
1181 // Check address value in SGPR/VGPR are legal for flat scratch in the form
1182 // of: SGPR + VGPR.
1183 bool AMDGPUDAGToDAGISel::isFlatScratchBaseLegalSV(SDValue Addr) const {
1184   if (isNoUnsignedWrap(Addr))
1185     return true;
1186 
1187   auto LHS = Addr.getOperand(0);
1188   auto RHS = Addr.getOperand(1);
1189   return CurDAG->SignBitIsZero(RHS) && CurDAG->SignBitIsZero(LHS);
1190 }
1191 
1192 // Check address value in SGPR/VGPR are legal for flat scratch in the form
1193 // of: SGPR + VGPR + Imm.
1194 bool AMDGPUDAGToDAGISel::isFlatScratchBaseLegalSVImm(SDValue Addr) const {
1195   auto Base = Addr.getOperand(0);
1196   auto *RHSImm = cast<ConstantSDNode>(Addr.getOperand(1));
1197   // If the immediate offset is negative and within certain range, the base
1198   // address cannot also be negative. If the base is also negative, the sum
1199   // would be either negative or much larger than the valid range of scratch
1200   // memory a thread can access.
1201   if (isNoUnsignedWrap(Base) &&
1202       (isNoUnsignedWrap(Addr) ||
1203        (RHSImm->getSExtValue() < 0 && RHSImm->getSExtValue() > -0x40000000)))
1204     return true;
1205 
1206   auto LHS = Base.getOperand(0);
1207   auto RHS = Base.getOperand(1);
1208   return CurDAG->SignBitIsZero(RHS) && CurDAG->SignBitIsZero(LHS);
1209 }
1210 
1211 // TODO: If offset is too big, put low 16-bit into offset.
1212 bool AMDGPUDAGToDAGISel::SelectDS64Bit4ByteAligned(SDValue Addr, SDValue &Base,
1213                                                    SDValue &Offset0,
1214                                                    SDValue &Offset1) const {
1215   return SelectDSReadWrite2(Addr, Base, Offset0, Offset1, 4);
1216 }
1217 
1218 bool AMDGPUDAGToDAGISel::SelectDS128Bit8ByteAligned(SDValue Addr, SDValue &Base,
1219                                                     SDValue &Offset0,
1220                                                     SDValue &Offset1) const {
1221   return SelectDSReadWrite2(Addr, Base, Offset0, Offset1, 8);
1222 }
1223 
1224 bool AMDGPUDAGToDAGISel::SelectDSReadWrite2(SDValue Addr, SDValue &Base,
1225                                             SDValue &Offset0, SDValue &Offset1,
1226                                             unsigned Size) const {
1227   SDLoc DL(Addr);
1228 
1229   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1230     SDValue N0 = Addr.getOperand(0);
1231     SDValue N1 = Addr.getOperand(1);
1232     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1233     unsigned OffsetValue0 = C1->getZExtValue();
1234     unsigned OffsetValue1 = OffsetValue0 + Size;
1235 
1236     // (add n0, c0)
1237     if (isDSOffset2Legal(N0, OffsetValue0, OffsetValue1, Size)) {
1238       Base = N0;
1239       Offset0 = CurDAG->getTargetConstant(OffsetValue0 / Size, DL, MVT::i8);
1240       Offset1 = CurDAG->getTargetConstant(OffsetValue1 / Size, DL, MVT::i8);
1241       return true;
1242     }
1243   } else if (Addr.getOpcode() == ISD::SUB) {
1244     // sub C, x -> add (sub 0, x), C
1245     if (const ConstantSDNode *C =
1246             dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
1247       unsigned OffsetValue0 = C->getZExtValue();
1248       unsigned OffsetValue1 = OffsetValue0 + Size;
1249 
1250       if (isDSOffset2Legal(SDValue(), OffsetValue0, OffsetValue1, Size)) {
1251         SDLoc DL(Addr);
1252         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1253 
1254         // XXX - This is kind of hacky. Create a dummy sub node so we can check
1255         // the known bits in isDSOffsetLegal. We need to emit the selected node
1256         // here, so this is thrown away.
1257         SDValue Sub =
1258             CurDAG->getNode(ISD::SUB, DL, MVT::i32, Zero, Addr.getOperand(1));
1259 
1260         if (isDSOffset2Legal(Sub, OffsetValue0, OffsetValue1, Size)) {
1261           SmallVector<SDValue, 3> Opnds;
1262           Opnds.push_back(Zero);
1263           Opnds.push_back(Addr.getOperand(1));
1264           unsigned SubOp = AMDGPU::V_SUB_CO_U32_e32;
1265           if (Subtarget->hasAddNoCarry()) {
1266             SubOp = AMDGPU::V_SUB_U32_e64;
1267             Opnds.push_back(
1268                 CurDAG->getTargetConstant(0, {}, MVT::i1)); // clamp bit
1269           }
1270 
1271           MachineSDNode *MachineSub = CurDAG->getMachineNode(
1272               SubOp, DL, MVT::getIntegerVT(Size * 8), Opnds);
1273 
1274           Base = SDValue(MachineSub, 0);
1275           Offset0 = CurDAG->getTargetConstant(OffsetValue0 / Size, DL, MVT::i8);
1276           Offset1 = CurDAG->getTargetConstant(OffsetValue1 / Size, DL, MVT::i8);
1277           return true;
1278         }
1279       }
1280     }
1281   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1282     unsigned OffsetValue0 = CAddr->getZExtValue();
1283     unsigned OffsetValue1 = OffsetValue0 + Size;
1284 
1285     if (isDSOffset2Legal(SDValue(), OffsetValue0, OffsetValue1, Size)) {
1286       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1287       MachineSDNode *MovZero =
1288           CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32, Zero);
1289       Base = SDValue(MovZero, 0);
1290       Offset0 = CurDAG->getTargetConstant(OffsetValue0 / Size, DL, MVT::i8);
1291       Offset1 = CurDAG->getTargetConstant(OffsetValue1 / Size, DL, MVT::i8);
1292       return true;
1293     }
1294   }
1295 
1296   // default case
1297 
1298   Base = Addr;
1299   Offset0 = CurDAG->getTargetConstant(0, DL, MVT::i8);
1300   Offset1 = CurDAG->getTargetConstant(1, DL, MVT::i8);
1301   return true;
1302 }
1303 
1304 bool AMDGPUDAGToDAGISel::SelectMUBUF(SDValue Addr, SDValue &Ptr, SDValue &VAddr,
1305                                      SDValue &SOffset, SDValue &Offset,
1306                                      SDValue &Offen, SDValue &Idxen,
1307                                      SDValue &Addr64) const {
1308   // Subtarget prefers to use flat instruction
1309   // FIXME: This should be a pattern predicate and not reach here
1310   if (Subtarget->useFlatForGlobal())
1311     return false;
1312 
1313   SDLoc DL(Addr);
1314 
1315   Idxen = CurDAG->getTargetConstant(0, DL, MVT::i1);
1316   Offen = CurDAG->getTargetConstant(0, DL, MVT::i1);
1317   Addr64 = CurDAG->getTargetConstant(0, DL, MVT::i1);
1318   SOffset = Subtarget->hasRestrictedSOffset()
1319                 ? CurDAG->getRegister(AMDGPU::SGPR_NULL, MVT::i32)
1320                 : CurDAG->getTargetConstant(0, DL, MVT::i32);
1321 
1322   ConstantSDNode *C1 = nullptr;
1323   SDValue N0 = Addr;
1324   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1325     C1 = cast<ConstantSDNode>(Addr.getOperand(1));
1326     if (isUInt<32>(C1->getZExtValue()))
1327       N0 = Addr.getOperand(0);
1328     else
1329       C1 = nullptr;
1330   }
1331 
1332   if (N0.getOpcode() == ISD::ADD) {
1333     // (add N2, N3) -> addr64, or
1334     // (add (add N2, N3), C1) -> addr64
1335     SDValue N2 = N0.getOperand(0);
1336     SDValue N3 = N0.getOperand(1);
1337     Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1338 
1339     if (N2->isDivergent()) {
1340       if (N3->isDivergent()) {
1341         // Both N2 and N3 are divergent. Use N0 (the result of the add) as the
1342         // addr64, and construct the resource from a 0 address.
1343         Ptr = SDValue(buildSMovImm64(DL, 0, MVT::v2i32), 0);
1344         VAddr = N0;
1345       } else {
1346         // N2 is divergent, N3 is not.
1347         Ptr = N3;
1348         VAddr = N2;
1349       }
1350     } else {
1351       // N2 is not divergent.
1352       Ptr = N2;
1353       VAddr = N3;
1354     }
1355     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1356   } else if (N0->isDivergent()) {
1357     // N0 is divergent. Use it as the addr64, and construct the resource from a
1358     // 0 address.
1359     Ptr = SDValue(buildSMovImm64(DL, 0, MVT::v2i32), 0);
1360     VAddr = N0;
1361     Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1362   } else {
1363     // N0 -> offset, or
1364     // (N0 + C1) -> offset
1365     VAddr = CurDAG->getTargetConstant(0, DL, MVT::i32);
1366     Ptr = N0;
1367   }
1368 
1369   if (!C1) {
1370     // No offset.
1371     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1372     return true;
1373   }
1374 
1375   const SIInstrInfo *TII = Subtarget->getInstrInfo();
1376   if (TII->isLegalMUBUFImmOffset(C1->getZExtValue())) {
1377     // Legal offset for instruction.
1378     Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32);
1379     return true;
1380   }
1381 
1382   // Illegal offset, store it in soffset.
1383   Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1384   SOffset =
1385       SDValue(CurDAG->getMachineNode(
1386                   AMDGPU::S_MOV_B32, DL, MVT::i32,
1387                   CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32)),
1388               0);
1389   return true;
1390 }
1391 
1392 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1393                                            SDValue &VAddr, SDValue &SOffset,
1394                                            SDValue &Offset) const {
1395   SDValue Ptr, Offen, Idxen, Addr64;
1396 
1397   // addr64 bit was removed for volcanic islands.
1398   // FIXME: This should be a pattern predicate and not reach here
1399   if (!Subtarget->hasAddr64())
1400     return false;
1401 
1402   if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64))
1403     return false;
1404 
1405   ConstantSDNode *C = cast<ConstantSDNode>(Addr64);
1406   if (C->getSExtValue()) {
1407     SDLoc DL(Addr);
1408 
1409     const SITargetLowering& Lowering =
1410       *static_cast<const SITargetLowering*>(getTargetLowering());
1411 
1412     SRsrc = SDValue(Lowering.wrapAddr64Rsrc(*CurDAG, DL, Ptr), 0);
1413     return true;
1414   }
1415 
1416   return false;
1417 }
1418 
1419 std::pair<SDValue, SDValue> AMDGPUDAGToDAGISel::foldFrameIndex(SDValue N) const {
1420   SDLoc DL(N);
1421 
1422   auto *FI = dyn_cast<FrameIndexSDNode>(N);
1423   SDValue TFI =
1424       FI ? CurDAG->getTargetFrameIndex(FI->getIndex(), FI->getValueType(0)) : N;
1425 
1426   // We rebase the base address into an absolute stack address and hence
1427   // use constant 0 for soffset. This value must be retained until
1428   // frame elimination and eliminateFrameIndex will choose the appropriate
1429   // frame register if need be.
1430   return std::pair(TFI, CurDAG->getTargetConstant(0, DL, MVT::i32));
1431 }
1432 
1433 bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffen(SDNode *Parent,
1434                                                  SDValue Addr, SDValue &Rsrc,
1435                                                  SDValue &VAddr, SDValue &SOffset,
1436                                                  SDValue &ImmOffset) const {
1437 
1438   SDLoc DL(Addr);
1439   MachineFunction &MF = CurDAG->getMachineFunction();
1440   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1441 
1442   Rsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1443 
1444   if (ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1445     int64_t Imm = CAddr->getSExtValue();
1446     const int64_t NullPtr =
1447         AMDGPUTargetMachine::getNullPointerValue(AMDGPUAS::PRIVATE_ADDRESS);
1448     // Don't fold null pointer.
1449     if (Imm != NullPtr) {
1450       const uint32_t MaxOffset = SIInstrInfo::getMaxMUBUFImmOffset(*Subtarget);
1451       SDValue HighBits =
1452           CurDAG->getTargetConstant(Imm & ~MaxOffset, DL, MVT::i32);
1453       MachineSDNode *MovHighBits = CurDAG->getMachineNode(
1454         AMDGPU::V_MOV_B32_e32, DL, MVT::i32, HighBits);
1455       VAddr = SDValue(MovHighBits, 0);
1456 
1457       SOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1458       ImmOffset = CurDAG->getTargetConstant(Imm & MaxOffset, DL, MVT::i32);
1459       return true;
1460     }
1461   }
1462 
1463   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1464     // (add n0, c1)
1465 
1466     SDValue N0 = Addr.getOperand(0);
1467     SDValue N1 = Addr.getOperand(1);
1468 
1469     // Offsets in vaddr must be positive if range checking is enabled.
1470     //
1471     // The total computation of vaddr + soffset + offset must not overflow.  If
1472     // vaddr is negative, even if offset is 0 the sgpr offset add will end up
1473     // overflowing.
1474     //
1475     // Prior to gfx9, MUBUF instructions with the vaddr offset enabled would
1476     // always perform a range check. If a negative vaddr base index was used,
1477     // this would fail the range check. The overall address computation would
1478     // compute a valid address, but this doesn't happen due to the range
1479     // check. For out-of-bounds MUBUF loads, a 0 is returned.
1480     //
1481     // Therefore it should be safe to fold any VGPR offset on gfx9 into the
1482     // MUBUF vaddr, but not on older subtargets which can only do this if the
1483     // sign bit is known 0.
1484     const SIInstrInfo *TII = Subtarget->getInstrInfo();
1485     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1486     if (TII->isLegalMUBUFImmOffset(C1->getZExtValue()) &&
1487         (!Subtarget->privateMemoryResourceIsRangeChecked() ||
1488          CurDAG->SignBitIsZero(N0))) {
1489       std::tie(VAddr, SOffset) = foldFrameIndex(N0);
1490       ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32);
1491       return true;
1492     }
1493   }
1494 
1495   // (node)
1496   std::tie(VAddr, SOffset) = foldFrameIndex(Addr);
1497   ImmOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1498   return true;
1499 }
1500 
1501 static bool IsCopyFromSGPR(const SIRegisterInfo &TRI, SDValue Val) {
1502   if (Val.getOpcode() != ISD::CopyFromReg)
1503     return false;
1504   auto Reg = cast<RegisterSDNode>(Val.getOperand(1))->getReg();
1505   if (!Reg.isPhysical())
1506     return false;
1507   auto RC = TRI.getPhysRegBaseClass(Reg);
1508   return RC && TRI.isSGPRClass(RC);
1509 }
1510 
1511 bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffset(SDNode *Parent,
1512                                                   SDValue Addr,
1513                                                   SDValue &SRsrc,
1514                                                   SDValue &SOffset,
1515                                                   SDValue &Offset) const {
1516   const SIRegisterInfo *TRI =
1517       static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
1518   const SIInstrInfo *TII = Subtarget->getInstrInfo();
1519   MachineFunction &MF = CurDAG->getMachineFunction();
1520   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1521   SDLoc DL(Addr);
1522 
1523   // CopyFromReg <sgpr>
1524   if (IsCopyFromSGPR(*TRI, Addr)) {
1525     SRsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1526     SOffset = Addr;
1527     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1528     return true;
1529   }
1530 
1531   ConstantSDNode *CAddr;
1532   if (Addr.getOpcode() == ISD::ADD) {
1533     // Add (CopyFromReg <sgpr>) <constant>
1534     CAddr = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
1535     if (!CAddr || !TII->isLegalMUBUFImmOffset(CAddr->getZExtValue()))
1536       return false;
1537     if (!IsCopyFromSGPR(*TRI, Addr.getOperand(0)))
1538       return false;
1539 
1540     SOffset = Addr.getOperand(0);
1541   } else if ((CAddr = dyn_cast<ConstantSDNode>(Addr)) &&
1542              TII->isLegalMUBUFImmOffset(CAddr->getZExtValue())) {
1543     // <constant>
1544     SOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1545   } else {
1546     return false;
1547   }
1548 
1549   SRsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1550 
1551   Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i32);
1552   return true;
1553 }
1554 
1555 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1556                                            SDValue &SOffset, SDValue &Offset
1557                                            ) const {
1558   SDValue Ptr, VAddr, Offen, Idxen, Addr64;
1559   const SIInstrInfo *TII = Subtarget->getInstrInfo();
1560 
1561   if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64))
1562     return false;
1563 
1564   if (!cast<ConstantSDNode>(Offen)->getSExtValue() &&
1565       !cast<ConstantSDNode>(Idxen)->getSExtValue() &&
1566       !cast<ConstantSDNode>(Addr64)->getSExtValue()) {
1567     uint64_t Rsrc = TII->getDefaultRsrcDataFormat() |
1568                     APInt::getAllOnes(32).getZExtValue(); // Size
1569     SDLoc DL(Addr);
1570 
1571     const SITargetLowering& Lowering =
1572       *static_cast<const SITargetLowering*>(getTargetLowering());
1573 
1574     SRsrc = SDValue(Lowering.buildRSRC(*CurDAG, DL, Ptr, 0, Rsrc), 0);
1575     return true;
1576   }
1577   return false;
1578 }
1579 
1580 bool AMDGPUDAGToDAGISel::SelectBUFSOffset(SDValue ByteOffsetNode,
1581                                           SDValue &SOffset) const {
1582   if (Subtarget->hasRestrictedSOffset()) {
1583     if (auto SOffsetConst = dyn_cast<ConstantSDNode>(ByteOffsetNode)) {
1584       if (SOffsetConst->isZero()) {
1585         SOffset = CurDAG->getRegister(AMDGPU::SGPR_NULL, MVT::i32);
1586         return true;
1587       }
1588     }
1589   }
1590 
1591   SOffset = ByteOffsetNode;
1592   return true;
1593 }
1594 
1595 // Find a load or store from corresponding pattern root.
1596 // Roots may be build_vector, bitconvert or their combinations.
1597 static MemSDNode* findMemSDNode(SDNode *N) {
1598   N = AMDGPUTargetLowering::stripBitcast(SDValue(N,0)).getNode();
1599   if (MemSDNode *MN = dyn_cast<MemSDNode>(N))
1600     return MN;
1601   assert(isa<BuildVectorSDNode>(N));
1602   for (SDValue V : N->op_values())
1603     if (MemSDNode *MN =
1604           dyn_cast<MemSDNode>(AMDGPUTargetLowering::stripBitcast(V)))
1605       return MN;
1606   llvm_unreachable("cannot find MemSDNode in the pattern!");
1607 }
1608 
1609 bool AMDGPUDAGToDAGISel::SelectFlatOffsetImpl(SDNode *N, SDValue Addr,
1610                                               SDValue &VAddr, SDValue &Offset,
1611                                               uint64_t FlatVariant) const {
1612   int64_t OffsetVal = 0;
1613 
1614   unsigned AS = findMemSDNode(N)->getAddressSpace();
1615 
1616   bool CanHaveFlatSegmentOffsetBug =
1617       Subtarget->hasFlatSegmentOffsetBug() &&
1618       FlatVariant == SIInstrFlags::FLAT &&
1619       (AS == AMDGPUAS::FLAT_ADDRESS || AS == AMDGPUAS::GLOBAL_ADDRESS);
1620 
1621   if (Subtarget->hasFlatInstOffsets() && !CanHaveFlatSegmentOffsetBug) {
1622     SDValue N0, N1;
1623     if (isBaseWithConstantOffset64(Addr, N0, N1) &&
1624         (FlatVariant != SIInstrFlags::FlatScratch ||
1625          isFlatScratchBaseLegal(Addr))) {
1626       int64_t COffsetVal = cast<ConstantSDNode>(N1)->getSExtValue();
1627 
1628       const SIInstrInfo *TII = Subtarget->getInstrInfo();
1629       if (TII->isLegalFLATOffset(COffsetVal, AS, FlatVariant)) {
1630         Addr = N0;
1631         OffsetVal = COffsetVal;
1632       } else {
1633         // If the offset doesn't fit, put the low bits into the offset field and
1634         // add the rest.
1635         //
1636         // For a FLAT instruction the hardware decides whether to access
1637         // global/scratch/shared memory based on the high bits of vaddr,
1638         // ignoring the offset field, so we have to ensure that when we add
1639         // remainder to vaddr it still points into the same underlying object.
1640         // The easiest way to do that is to make sure that we split the offset
1641         // into two pieces that are both >= 0 or both <= 0.
1642 
1643         SDLoc DL(N);
1644         uint64_t RemainderOffset;
1645 
1646         std::tie(OffsetVal, RemainderOffset) =
1647             TII->splitFlatOffset(COffsetVal, AS, FlatVariant);
1648 
1649         SDValue AddOffsetLo =
1650             getMaterializedScalarImm32(Lo_32(RemainderOffset), DL);
1651         SDValue Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
1652 
1653         if (Addr.getValueType().getSizeInBits() == 32) {
1654           SmallVector<SDValue, 3> Opnds;
1655           Opnds.push_back(N0);
1656           Opnds.push_back(AddOffsetLo);
1657           unsigned AddOp = AMDGPU::V_ADD_CO_U32_e32;
1658           if (Subtarget->hasAddNoCarry()) {
1659             AddOp = AMDGPU::V_ADD_U32_e64;
1660             Opnds.push_back(Clamp);
1661           }
1662           Addr = SDValue(CurDAG->getMachineNode(AddOp, DL, MVT::i32, Opnds), 0);
1663         } else {
1664           // TODO: Should this try to use a scalar add pseudo if the base address
1665           // is uniform and saddr is usable?
1666           SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
1667           SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
1668 
1669           SDNode *N0Lo = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
1670                                                 DL, MVT::i32, N0, Sub0);
1671           SDNode *N0Hi = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
1672                                                 DL, MVT::i32, N0, Sub1);
1673 
1674           SDValue AddOffsetHi =
1675               getMaterializedScalarImm32(Hi_32(RemainderOffset), DL);
1676 
1677           SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i1);
1678 
1679           SDNode *Add =
1680               CurDAG->getMachineNode(AMDGPU::V_ADD_CO_U32_e64, DL, VTs,
1681                                      {AddOffsetLo, SDValue(N0Lo, 0), Clamp});
1682 
1683           SDNode *Addc = CurDAG->getMachineNode(
1684               AMDGPU::V_ADDC_U32_e64, DL, VTs,
1685               {AddOffsetHi, SDValue(N0Hi, 0), SDValue(Add, 1), Clamp});
1686 
1687           SDValue RegSequenceArgs[] = {
1688               CurDAG->getTargetConstant(AMDGPU::VReg_64RegClassID, DL, MVT::i32),
1689               SDValue(Add, 0), Sub0, SDValue(Addc, 0), Sub1};
1690 
1691           Addr = SDValue(CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1692                                                 MVT::i64, RegSequenceArgs),
1693                          0);
1694         }
1695       }
1696     }
1697   }
1698 
1699   VAddr = Addr;
1700   Offset = CurDAG->getTargetConstant(OffsetVal, SDLoc(), MVT::i32);
1701   return true;
1702 }
1703 
1704 bool AMDGPUDAGToDAGISel::SelectFlatOffset(SDNode *N, SDValue Addr,
1705                                           SDValue &VAddr,
1706                                           SDValue &Offset) const {
1707   return SelectFlatOffsetImpl(N, Addr, VAddr, Offset, SIInstrFlags::FLAT);
1708 }
1709 
1710 bool AMDGPUDAGToDAGISel::SelectGlobalOffset(SDNode *N, SDValue Addr,
1711                                             SDValue &VAddr,
1712                                             SDValue &Offset) const {
1713   return SelectFlatOffsetImpl(N, Addr, VAddr, Offset, SIInstrFlags::FlatGlobal);
1714 }
1715 
1716 bool AMDGPUDAGToDAGISel::SelectScratchOffset(SDNode *N, SDValue Addr,
1717                                              SDValue &VAddr,
1718                                              SDValue &Offset) const {
1719   return SelectFlatOffsetImpl(N, Addr, VAddr, Offset,
1720                               SIInstrFlags::FlatScratch);
1721 }
1722 
1723 // If this matches zero_extend i32:x, return x
1724 static SDValue matchZExtFromI32(SDValue Op) {
1725   if (Op.getOpcode() != ISD::ZERO_EXTEND)
1726     return SDValue();
1727 
1728   SDValue ExtSrc = Op.getOperand(0);
1729   return (ExtSrc.getValueType() == MVT::i32) ? ExtSrc : SDValue();
1730 }
1731 
1732 // Match (64-bit SGPR base) + (zext vgpr offset) + sext(imm offset)
1733 bool AMDGPUDAGToDAGISel::SelectGlobalSAddr(SDNode *N,
1734                                            SDValue Addr,
1735                                            SDValue &SAddr,
1736                                            SDValue &VOffset,
1737                                            SDValue &Offset) const {
1738   int64_t ImmOffset = 0;
1739 
1740   // Match the immediate offset first, which canonically is moved as low as
1741   // possible.
1742 
1743   SDValue LHS, RHS;
1744   if (isBaseWithConstantOffset64(Addr, LHS, RHS)) {
1745     int64_t COffsetVal = cast<ConstantSDNode>(RHS)->getSExtValue();
1746     const SIInstrInfo *TII = Subtarget->getInstrInfo();
1747 
1748     if (TII->isLegalFLATOffset(COffsetVal, AMDGPUAS::GLOBAL_ADDRESS,
1749                                SIInstrFlags::FlatGlobal)) {
1750       Addr = LHS;
1751       ImmOffset = COffsetVal;
1752     } else if (!LHS->isDivergent()) {
1753       if (COffsetVal > 0) {
1754         SDLoc SL(N);
1755         // saddr + large_offset -> saddr +
1756         //                         (voffset = large_offset & ~MaxOffset) +
1757         //                         (large_offset & MaxOffset);
1758         int64_t SplitImmOffset, RemainderOffset;
1759         std::tie(SplitImmOffset, RemainderOffset) = TII->splitFlatOffset(
1760             COffsetVal, AMDGPUAS::GLOBAL_ADDRESS, SIInstrFlags::FlatGlobal);
1761 
1762         if (isUInt<32>(RemainderOffset)) {
1763           SDNode *VMov = CurDAG->getMachineNode(
1764               AMDGPU::V_MOV_B32_e32, SL, MVT::i32,
1765               CurDAG->getTargetConstant(RemainderOffset, SDLoc(), MVT::i32));
1766           VOffset = SDValue(VMov, 0);
1767           SAddr = LHS;
1768           Offset = CurDAG->getTargetConstant(SplitImmOffset, SDLoc(), MVT::i32);
1769           return true;
1770         }
1771       }
1772 
1773       // We are adding a 64 bit SGPR and a constant. If constant bus limit
1774       // is 1 we would need to perform 1 or 2 extra moves for each half of
1775       // the constant and it is better to do a scalar add and then issue a
1776       // single VALU instruction to materialize zero. Otherwise it is less
1777       // instructions to perform VALU adds with immediates or inline literals.
1778       unsigned NumLiterals =
1779           !TII->isInlineConstant(APInt(32, COffsetVal & 0xffffffff)) +
1780           !TII->isInlineConstant(APInt(32, COffsetVal >> 32));
1781       if (Subtarget->getConstantBusLimit(AMDGPU::V_ADD_U32_e64) > NumLiterals)
1782         return false;
1783     }
1784   }
1785 
1786   // Match the variable offset.
1787   if (Addr.getOpcode() == ISD::ADD) {
1788     LHS = Addr.getOperand(0);
1789     RHS = Addr.getOperand(1);
1790 
1791     if (!LHS->isDivergent()) {
1792       // add (i64 sgpr), (zero_extend (i32 vgpr))
1793       if (SDValue ZextRHS = matchZExtFromI32(RHS)) {
1794         SAddr = LHS;
1795         VOffset = ZextRHS;
1796       }
1797     }
1798 
1799     if (!SAddr && !RHS->isDivergent()) {
1800       // add (zero_extend (i32 vgpr)), (i64 sgpr)
1801       if (SDValue ZextLHS = matchZExtFromI32(LHS)) {
1802         SAddr = RHS;
1803         VOffset = ZextLHS;
1804       }
1805     }
1806 
1807     if (SAddr) {
1808       Offset = CurDAG->getTargetConstant(ImmOffset, SDLoc(), MVT::i32);
1809       return true;
1810     }
1811   }
1812 
1813   if (Addr->isDivergent() || Addr.getOpcode() == ISD::UNDEF ||
1814       isa<ConstantSDNode>(Addr))
1815     return false;
1816 
1817   // It's cheaper to materialize a single 32-bit zero for vaddr than the two
1818   // moves required to copy a 64-bit SGPR to VGPR.
1819   SAddr = Addr;
1820   SDNode *VMov =
1821       CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32, SDLoc(Addr), MVT::i32,
1822                              CurDAG->getTargetConstant(0, SDLoc(), MVT::i32));
1823   VOffset = SDValue(VMov, 0);
1824   Offset = CurDAG->getTargetConstant(ImmOffset, SDLoc(), MVT::i32);
1825   return true;
1826 }
1827 
1828 static SDValue SelectSAddrFI(SelectionDAG *CurDAG, SDValue SAddr) {
1829   if (auto FI = dyn_cast<FrameIndexSDNode>(SAddr)) {
1830     SAddr = CurDAG->getTargetFrameIndex(FI->getIndex(), FI->getValueType(0));
1831   } else if (SAddr.getOpcode() == ISD::ADD &&
1832              isa<FrameIndexSDNode>(SAddr.getOperand(0))) {
1833     // Materialize this into a scalar move for scalar address to avoid
1834     // readfirstlane.
1835     auto FI = cast<FrameIndexSDNode>(SAddr.getOperand(0));
1836     SDValue TFI = CurDAG->getTargetFrameIndex(FI->getIndex(),
1837                                               FI->getValueType(0));
1838     SAddr = SDValue(CurDAG->getMachineNode(AMDGPU::S_ADD_I32, SDLoc(SAddr),
1839                                            MVT::i32, TFI, SAddr.getOperand(1)),
1840                     0);
1841   }
1842 
1843   return SAddr;
1844 }
1845 
1846 // Match (32-bit SGPR base) + sext(imm offset)
1847 bool AMDGPUDAGToDAGISel::SelectScratchSAddr(SDNode *Parent, SDValue Addr,
1848                                             SDValue &SAddr,
1849                                             SDValue &Offset) const {
1850   if (Addr->isDivergent())
1851     return false;
1852 
1853   SDLoc DL(Addr);
1854 
1855   int64_t COffsetVal = 0;
1856 
1857   if (CurDAG->isBaseWithConstantOffset(Addr) && isFlatScratchBaseLegal(Addr)) {
1858     COffsetVal = cast<ConstantSDNode>(Addr.getOperand(1))->getSExtValue();
1859     SAddr = Addr.getOperand(0);
1860   } else {
1861     SAddr = Addr;
1862   }
1863 
1864   SAddr = SelectSAddrFI(CurDAG, SAddr);
1865 
1866   const SIInstrInfo *TII = Subtarget->getInstrInfo();
1867 
1868   if (!TII->isLegalFLATOffset(COffsetVal, AMDGPUAS::PRIVATE_ADDRESS,
1869                               SIInstrFlags::FlatScratch)) {
1870     int64_t SplitImmOffset, RemainderOffset;
1871     std::tie(SplitImmOffset, RemainderOffset) = TII->splitFlatOffset(
1872         COffsetVal, AMDGPUAS::PRIVATE_ADDRESS, SIInstrFlags::FlatScratch);
1873 
1874     COffsetVal = SplitImmOffset;
1875 
1876     SDValue AddOffset =
1877         SAddr.getOpcode() == ISD::TargetFrameIndex
1878             ? getMaterializedScalarImm32(Lo_32(RemainderOffset), DL)
1879             : CurDAG->getTargetConstant(RemainderOffset, DL, MVT::i32);
1880     SAddr = SDValue(CurDAG->getMachineNode(AMDGPU::S_ADD_I32, DL, MVT::i32,
1881                                            SAddr, AddOffset),
1882                     0);
1883   }
1884 
1885   Offset = CurDAG->getTargetConstant(COffsetVal, DL, MVT::i16);
1886 
1887   return true;
1888 }
1889 
1890 // Check whether the flat scratch SVS swizzle bug affects this access.
1891 bool AMDGPUDAGToDAGISel::checkFlatScratchSVSSwizzleBug(
1892     SDValue VAddr, SDValue SAddr, uint64_t ImmOffset) const {
1893   if (!Subtarget->hasFlatScratchSVSSwizzleBug())
1894     return false;
1895 
1896   // The bug affects the swizzling of SVS accesses if there is any carry out
1897   // from the two low order bits (i.e. from bit 1 into bit 2) when adding
1898   // voffset to (soffset + inst_offset).
1899   KnownBits VKnown = CurDAG->computeKnownBits(VAddr);
1900   KnownBits SKnown = KnownBits::computeForAddSub(
1901       true, false, CurDAG->computeKnownBits(SAddr),
1902       KnownBits::makeConstant(APInt(32, ImmOffset)));
1903   uint64_t VMax = VKnown.getMaxValue().getZExtValue();
1904   uint64_t SMax = SKnown.getMaxValue().getZExtValue();
1905   return (VMax & 3) + (SMax & 3) >= 4;
1906 }
1907 
1908 bool AMDGPUDAGToDAGISel::SelectScratchSVAddr(SDNode *N, SDValue Addr,
1909                                              SDValue &VAddr, SDValue &SAddr,
1910                                              SDValue &Offset) const  {
1911   int64_t ImmOffset = 0;
1912 
1913   SDValue LHS, RHS;
1914   SDValue OrigAddr = Addr;
1915   if (isBaseWithConstantOffset64(Addr, LHS, RHS)) {
1916     int64_t COffsetVal = cast<ConstantSDNode>(RHS)->getSExtValue();
1917     const SIInstrInfo *TII = Subtarget->getInstrInfo();
1918 
1919     if (TII->isLegalFLATOffset(COffsetVal, AMDGPUAS::PRIVATE_ADDRESS, true)) {
1920       Addr = LHS;
1921       ImmOffset = COffsetVal;
1922     } else if (!LHS->isDivergent() && COffsetVal > 0) {
1923       SDLoc SL(N);
1924       // saddr + large_offset -> saddr + (vaddr = large_offset & ~MaxOffset) +
1925       //                         (large_offset & MaxOffset);
1926       int64_t SplitImmOffset, RemainderOffset;
1927       std::tie(SplitImmOffset, RemainderOffset)
1928         = TII->splitFlatOffset(COffsetVal, AMDGPUAS::PRIVATE_ADDRESS, true);
1929 
1930       if (isUInt<32>(RemainderOffset)) {
1931         SDNode *VMov = CurDAG->getMachineNode(
1932           AMDGPU::V_MOV_B32_e32, SL, MVT::i32,
1933           CurDAG->getTargetConstant(RemainderOffset, SDLoc(), MVT::i32));
1934         VAddr = SDValue(VMov, 0);
1935         SAddr = LHS;
1936         if (!isFlatScratchBaseLegal(Addr))
1937           return false;
1938         if (checkFlatScratchSVSSwizzleBug(VAddr, SAddr, SplitImmOffset))
1939           return false;
1940         Offset = CurDAG->getTargetConstant(SplitImmOffset, SDLoc(), MVT::i16);
1941         return true;
1942       }
1943     }
1944   }
1945 
1946   if (Addr.getOpcode() != ISD::ADD)
1947     return false;
1948 
1949   LHS = Addr.getOperand(0);
1950   RHS = Addr.getOperand(1);
1951 
1952   if (!LHS->isDivergent() && RHS->isDivergent()) {
1953     SAddr = LHS;
1954     VAddr = RHS;
1955   } else if (!RHS->isDivergent() && LHS->isDivergent()) {
1956     SAddr = RHS;
1957     VAddr = LHS;
1958   } else {
1959     return false;
1960   }
1961 
1962   if (OrigAddr != Addr) {
1963     if (!isFlatScratchBaseLegalSVImm(OrigAddr))
1964       return false;
1965   } else {
1966     if (!isFlatScratchBaseLegalSV(OrigAddr))
1967       return false;
1968   }
1969 
1970   if (checkFlatScratchSVSSwizzleBug(VAddr, SAddr, ImmOffset))
1971     return false;
1972   SAddr = SelectSAddrFI(CurDAG, SAddr);
1973   Offset = CurDAG->getTargetConstant(ImmOffset, SDLoc(), MVT::i16);
1974   return true;
1975 }
1976 
1977 // Match an immediate (if Offset is not null) or an SGPR (if SOffset is
1978 // not null) offset. If Imm32Only is true, match only 32-bit immediate
1979 // offsets available on CI.
1980 bool AMDGPUDAGToDAGISel::SelectSMRDOffset(SDValue ByteOffsetNode,
1981                                           SDValue *SOffset, SDValue *Offset,
1982                                           bool Imm32Only, bool IsBuffer) const {
1983   assert((!SOffset || !Offset) &&
1984          "Cannot match both soffset and offset at the same time!");
1985 
1986   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ByteOffsetNode);
1987   if (!C) {
1988     if (!SOffset)
1989       return false;
1990     if (ByteOffsetNode.getValueType().isScalarInteger() &&
1991         ByteOffsetNode.getValueType().getSizeInBits() == 32) {
1992       *SOffset = ByteOffsetNode;
1993       return true;
1994     }
1995     if (ByteOffsetNode.getOpcode() == ISD::ZERO_EXTEND) {
1996       if (ByteOffsetNode.getOperand(0).getValueType().getSizeInBits() == 32) {
1997         *SOffset = ByteOffsetNode.getOperand(0);
1998         return true;
1999       }
2000     }
2001     return false;
2002   }
2003 
2004   SDLoc SL(ByteOffsetNode);
2005 
2006   // GFX9 and GFX10 have signed byte immediate offsets. The immediate
2007   // offset for S_BUFFER instructions is unsigned.
2008   int64_t ByteOffset = IsBuffer ? C->getZExtValue() : C->getSExtValue();
2009   std::optional<int64_t> EncodedOffset =
2010       AMDGPU::getSMRDEncodedOffset(*Subtarget, ByteOffset, IsBuffer);
2011   if (EncodedOffset && Offset && !Imm32Only) {
2012     *Offset = CurDAG->getTargetConstant(*EncodedOffset, SL, MVT::i32);
2013     return true;
2014   }
2015 
2016   // SGPR and literal offsets are unsigned.
2017   if (ByteOffset < 0)
2018     return false;
2019 
2020   EncodedOffset = AMDGPU::getSMRDEncodedLiteralOffset32(*Subtarget, ByteOffset);
2021   if (EncodedOffset && Offset && Imm32Only) {
2022     *Offset = CurDAG->getTargetConstant(*EncodedOffset, SL, MVT::i32);
2023     return true;
2024   }
2025 
2026   if (!isUInt<32>(ByteOffset) && !isInt<32>(ByteOffset))
2027     return false;
2028 
2029   if (SOffset) {
2030     SDValue C32Bit = CurDAG->getTargetConstant(ByteOffset, SL, MVT::i32);
2031     *SOffset = SDValue(
2032         CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32, C32Bit), 0);
2033     return true;
2034   }
2035 
2036   return false;
2037 }
2038 
2039 SDValue AMDGPUDAGToDAGISel::Expand32BitAddress(SDValue Addr) const {
2040   if (Addr.getValueType() != MVT::i32)
2041     return Addr;
2042 
2043   // Zero-extend a 32-bit address.
2044   SDLoc SL(Addr);
2045 
2046   const MachineFunction &MF = CurDAG->getMachineFunction();
2047   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2048   unsigned AddrHiVal = Info->get32BitAddressHighBits();
2049   SDValue AddrHi = CurDAG->getTargetConstant(AddrHiVal, SL, MVT::i32);
2050 
2051   const SDValue Ops[] = {
2052     CurDAG->getTargetConstant(AMDGPU::SReg_64_XEXECRegClassID, SL, MVT::i32),
2053     Addr,
2054     CurDAG->getTargetConstant(AMDGPU::sub0, SL, MVT::i32),
2055     SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32, AddrHi),
2056             0),
2057     CurDAG->getTargetConstant(AMDGPU::sub1, SL, MVT::i32),
2058   };
2059 
2060   return SDValue(CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, SL, MVT::i64,
2061                                         Ops), 0);
2062 }
2063 
2064 // Match a base and an immediate (if Offset is not null) or an SGPR (if
2065 // SOffset is not null) or an immediate+SGPR offset. If Imm32Only is
2066 // true, match only 32-bit immediate offsets available on CI.
2067 bool AMDGPUDAGToDAGISel::SelectSMRDBaseOffset(SDValue Addr, SDValue &SBase,
2068                                               SDValue *SOffset, SDValue *Offset,
2069                                               bool Imm32Only,
2070                                               bool IsBuffer) const {
2071   if (SOffset && Offset) {
2072     assert(!Imm32Only && !IsBuffer);
2073     SDValue B;
2074     return SelectSMRDBaseOffset(Addr, B, nullptr, Offset) &&
2075            SelectSMRDBaseOffset(B, SBase, SOffset, nullptr);
2076   }
2077 
2078   // A 32-bit (address + offset) should not cause unsigned 32-bit integer
2079   // wraparound, because s_load instructions perform the addition in 64 bits.
2080   if (Addr.getValueType() == MVT::i32 && Addr.getOpcode() == ISD::ADD &&
2081       !Addr->getFlags().hasNoUnsignedWrap())
2082     return false;
2083 
2084   SDValue N0, N1;
2085   // Extract the base and offset if possible.
2086   if (CurDAG->isBaseWithConstantOffset(Addr) || Addr.getOpcode() == ISD::ADD) {
2087     N0 = Addr.getOperand(0);
2088     N1 = Addr.getOperand(1);
2089   } else if (getBaseWithOffsetUsingSplitOR(*CurDAG, Addr, N0, N1)) {
2090     assert(N0 && N1 && isa<ConstantSDNode>(N1));
2091   }
2092   if (!N0 || !N1)
2093     return false;
2094   if (SelectSMRDOffset(N1, SOffset, Offset, Imm32Only, IsBuffer)) {
2095     SBase = N0;
2096     return true;
2097   }
2098   if (SelectSMRDOffset(N0, SOffset, Offset, Imm32Only, IsBuffer)) {
2099     SBase = N1;
2100     return true;
2101   }
2102   return false;
2103 }
2104 
2105 bool AMDGPUDAGToDAGISel::SelectSMRD(SDValue Addr, SDValue &SBase,
2106                                     SDValue *SOffset, SDValue *Offset,
2107                                     bool Imm32Only) const {
2108   if (SelectSMRDBaseOffset(Addr, SBase, SOffset, Offset, Imm32Only)) {
2109     SBase = Expand32BitAddress(SBase);
2110     return true;
2111   }
2112 
2113   if (Addr.getValueType() == MVT::i32 && Offset && !SOffset) {
2114     SBase = Expand32BitAddress(Addr);
2115     *Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
2116     return true;
2117   }
2118 
2119   return false;
2120 }
2121 
2122 bool AMDGPUDAGToDAGISel::SelectSMRDImm(SDValue Addr, SDValue &SBase,
2123                                        SDValue &Offset) const {
2124   return SelectSMRD(Addr, SBase, /* SOffset */ nullptr, &Offset);
2125 }
2126 
2127 bool AMDGPUDAGToDAGISel::SelectSMRDImm32(SDValue Addr, SDValue &SBase,
2128                                          SDValue &Offset) const {
2129   assert(Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS);
2130   return SelectSMRD(Addr, SBase, /* SOffset */ nullptr, &Offset,
2131                     /* Imm32Only */ true);
2132 }
2133 
2134 bool AMDGPUDAGToDAGISel::SelectSMRDSgpr(SDValue Addr, SDValue &SBase,
2135                                         SDValue &SOffset) const {
2136   return SelectSMRD(Addr, SBase, &SOffset, /* Offset */ nullptr);
2137 }
2138 
2139 bool AMDGPUDAGToDAGISel::SelectSMRDSgprImm(SDValue Addr, SDValue &SBase,
2140                                            SDValue &SOffset,
2141                                            SDValue &Offset) const {
2142   return SelectSMRD(Addr, SBase, &SOffset, &Offset);
2143 }
2144 
2145 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm(SDValue N, SDValue &Offset) const {
2146   return SelectSMRDOffset(N, /* SOffset */ nullptr, &Offset,
2147                           /* Imm32Only */ false, /* IsBuffer */ true);
2148 }
2149 
2150 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm32(SDValue N,
2151                                                SDValue &Offset) const {
2152   assert(Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS);
2153   return SelectSMRDOffset(N, /* SOffset */ nullptr, &Offset,
2154                           /* Imm32Only */ true, /* IsBuffer */ true);
2155 }
2156 
2157 bool AMDGPUDAGToDAGISel::SelectSMRDBufferSgprImm(SDValue N, SDValue &SOffset,
2158                                                  SDValue &Offset) const {
2159   // Match the (soffset + offset) pair as a 32-bit register base and
2160   // an immediate offset.
2161   return N.getValueType() == MVT::i32 &&
2162          SelectSMRDBaseOffset(N, /* SBase */ SOffset, /* SOffset*/ nullptr,
2163                               &Offset, /* Imm32Only */ false,
2164                               /* IsBuffer */ true);
2165 }
2166 
2167 bool AMDGPUDAGToDAGISel::SelectMOVRELOffset(SDValue Index,
2168                                             SDValue &Base,
2169                                             SDValue &Offset) const {
2170   SDLoc DL(Index);
2171 
2172   if (CurDAG->isBaseWithConstantOffset(Index)) {
2173     SDValue N0 = Index.getOperand(0);
2174     SDValue N1 = Index.getOperand(1);
2175     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
2176 
2177     // (add n0, c0)
2178     // Don't peel off the offset (c0) if doing so could possibly lead
2179     // the base (n0) to be negative.
2180     // (or n0, |c0|) can never change a sign given isBaseWithConstantOffset.
2181     if (C1->getSExtValue() <= 0 || CurDAG->SignBitIsZero(N0) ||
2182         (Index->getOpcode() == ISD::OR && C1->getSExtValue() >= 0)) {
2183       Base = N0;
2184       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32);
2185       return true;
2186     }
2187   }
2188 
2189   if (isa<ConstantSDNode>(Index))
2190     return false;
2191 
2192   Base = Index;
2193   Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
2194   return true;
2195 }
2196 
2197 SDNode *AMDGPUDAGToDAGISel::getBFE32(bool IsSigned, const SDLoc &DL,
2198                                      SDValue Val, uint32_t Offset,
2199                                      uint32_t Width) {
2200   if (Val->isDivergent()) {
2201     unsigned Opcode = IsSigned ? AMDGPU::V_BFE_I32_e64 : AMDGPU::V_BFE_U32_e64;
2202     SDValue Off = CurDAG->getTargetConstant(Offset, DL, MVT::i32);
2203     SDValue W = CurDAG->getTargetConstant(Width, DL, MVT::i32);
2204 
2205     return CurDAG->getMachineNode(Opcode, DL, MVT::i32, Val, Off, W);
2206   }
2207   unsigned Opcode = IsSigned ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32;
2208   // Transformation function, pack the offset and width of a BFE into
2209   // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
2210   // source, bits [5:0] contain the offset and bits [22:16] the width.
2211   uint32_t PackedVal = Offset | (Width << 16);
2212   SDValue PackedConst = CurDAG->getTargetConstant(PackedVal, DL, MVT::i32);
2213 
2214   return CurDAG->getMachineNode(Opcode, DL, MVT::i32, Val, PackedConst);
2215 }
2216 
2217 void AMDGPUDAGToDAGISel::SelectS_BFEFromShifts(SDNode *N) {
2218   // "(a << b) srl c)" ---> "BFE_U32 a, (c-b), (32-c)
2219   // "(a << b) sra c)" ---> "BFE_I32 a, (c-b), (32-c)
2220   // Predicate: 0 < b <= c < 32
2221 
2222   const SDValue &Shl = N->getOperand(0);
2223   ConstantSDNode *B = dyn_cast<ConstantSDNode>(Shl->getOperand(1));
2224   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2225 
2226   if (B && C) {
2227     uint32_t BVal = B->getZExtValue();
2228     uint32_t CVal = C->getZExtValue();
2229 
2230     if (0 < BVal && BVal <= CVal && CVal < 32) {
2231       bool Signed = N->getOpcode() == ISD::SRA;
2232       ReplaceNode(N, getBFE32(Signed, SDLoc(N), Shl.getOperand(0), CVal - BVal,
2233                   32 - CVal));
2234       return;
2235     }
2236   }
2237   SelectCode(N);
2238 }
2239 
2240 void AMDGPUDAGToDAGISel::SelectS_BFE(SDNode *N) {
2241   switch (N->getOpcode()) {
2242   case ISD::AND:
2243     if (N->getOperand(0).getOpcode() == ISD::SRL) {
2244       // "(a srl b) & mask" ---> "BFE_U32 a, b, popcount(mask)"
2245       // Predicate: isMask(mask)
2246       const SDValue &Srl = N->getOperand(0);
2247       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(Srl.getOperand(1));
2248       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
2249 
2250       if (Shift && Mask) {
2251         uint32_t ShiftVal = Shift->getZExtValue();
2252         uint32_t MaskVal = Mask->getZExtValue();
2253 
2254         if (isMask_32(MaskVal)) {
2255           uint32_t WidthVal = llvm::popcount(MaskVal);
2256           ReplaceNode(N, getBFE32(false, SDLoc(N), Srl.getOperand(0), ShiftVal,
2257                                   WidthVal));
2258           return;
2259         }
2260       }
2261     }
2262     break;
2263   case ISD::SRL:
2264     if (N->getOperand(0).getOpcode() == ISD::AND) {
2265       // "(a & mask) srl b)" ---> "BFE_U32 a, b, popcount(mask >> b)"
2266       // Predicate: isMask(mask >> b)
2267       const SDValue &And = N->getOperand(0);
2268       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(N->getOperand(1));
2269       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(And->getOperand(1));
2270 
2271       if (Shift && Mask) {
2272         uint32_t ShiftVal = Shift->getZExtValue();
2273         uint32_t MaskVal = Mask->getZExtValue() >> ShiftVal;
2274 
2275         if (isMask_32(MaskVal)) {
2276           uint32_t WidthVal = llvm::popcount(MaskVal);
2277           ReplaceNode(N, getBFE32(false, SDLoc(N), And.getOperand(0), ShiftVal,
2278                       WidthVal));
2279           return;
2280         }
2281       }
2282     } else if (N->getOperand(0).getOpcode() == ISD::SHL) {
2283       SelectS_BFEFromShifts(N);
2284       return;
2285     }
2286     break;
2287   case ISD::SRA:
2288     if (N->getOperand(0).getOpcode() == ISD::SHL) {
2289       SelectS_BFEFromShifts(N);
2290       return;
2291     }
2292     break;
2293 
2294   case ISD::SIGN_EXTEND_INREG: {
2295     // sext_inreg (srl x, 16), i8 -> bfe_i32 x, 16, 8
2296     SDValue Src = N->getOperand(0);
2297     if (Src.getOpcode() != ISD::SRL)
2298       break;
2299 
2300     const ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(Src.getOperand(1));
2301     if (!Amt)
2302       break;
2303 
2304     unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
2305     ReplaceNode(N, getBFE32(true, SDLoc(N), Src.getOperand(0),
2306                             Amt->getZExtValue(), Width));
2307     return;
2308   }
2309   }
2310 
2311   SelectCode(N);
2312 }
2313 
2314 bool AMDGPUDAGToDAGISel::isCBranchSCC(const SDNode *N) const {
2315   assert(N->getOpcode() == ISD::BRCOND);
2316   if (!N->hasOneUse())
2317     return false;
2318 
2319   SDValue Cond = N->getOperand(1);
2320   if (Cond.getOpcode() == ISD::CopyToReg)
2321     Cond = Cond.getOperand(2);
2322 
2323   if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse())
2324     return false;
2325 
2326   MVT VT = Cond.getOperand(0).getSimpleValueType();
2327   if (VT == MVT::i32)
2328     return true;
2329 
2330   if (VT == MVT::i64) {
2331     auto ST = static_cast<const GCNSubtarget *>(Subtarget);
2332 
2333     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
2334     return (CC == ISD::SETEQ || CC == ISD::SETNE) && ST->hasScalarCompareEq64();
2335   }
2336 
2337   return false;
2338 }
2339 
2340 static SDValue combineBallotPattern(SDValue VCMP, bool &Negate) {
2341   assert(VCMP->getOpcode() == AMDGPUISD::SETCC);
2342   // Special case for amdgcn.ballot:
2343   // %Cond = i1 (and/or combination of i1 ISD::SETCCs)
2344   // %VCMP = i(WaveSize) AMDGPUISD::SETCC (ext %Cond), 0, setne/seteq
2345   // =>
2346   // Use i1 %Cond value instead of i(WaveSize) %VCMP.
2347   // This is possible because divergent ISD::SETCC is selected as V_CMP and
2348   // Cond becomes a i(WaveSize) full mask value.
2349   // Note that ballot doesn't use SETEQ condition but its easy to support it
2350   // here for completeness, so in this case Negate is set true on return.
2351   auto VCMP_CC = cast<CondCodeSDNode>(VCMP.getOperand(2))->get();
2352   if ((VCMP_CC == ISD::SETEQ || VCMP_CC == ISD::SETNE) &&
2353       isNullConstant(VCMP.getOperand(1))) {
2354 
2355     auto Cond = VCMP.getOperand(0);
2356     if (ISD::isExtOpcode(Cond->getOpcode())) // Skip extension.
2357       Cond = Cond.getOperand(0);
2358 
2359     if (isBoolSGPR(Cond)) {
2360       Negate = VCMP_CC == ISD::SETEQ;
2361       return Cond;
2362     }
2363   }
2364   return SDValue();
2365 }
2366 
2367 void AMDGPUDAGToDAGISel::SelectBRCOND(SDNode *N) {
2368   SDValue Cond = N->getOperand(1);
2369 
2370   if (Cond.isUndef()) {
2371     CurDAG->SelectNodeTo(N, AMDGPU::SI_BR_UNDEF, MVT::Other,
2372                          N->getOperand(2), N->getOperand(0));
2373     return;
2374   }
2375 
2376   const GCNSubtarget *ST = static_cast<const GCNSubtarget *>(Subtarget);
2377   const SIRegisterInfo *TRI = ST->getRegisterInfo();
2378 
2379   bool UseSCCBr = isCBranchSCC(N) && isUniformBr(N);
2380   bool AndExec = !UseSCCBr;
2381   bool Negate = false;
2382 
2383   if (Cond.getOpcode() == ISD::SETCC &&
2384       Cond->getOperand(0)->getOpcode() == AMDGPUISD::SETCC) {
2385     SDValue VCMP = Cond->getOperand(0);
2386     auto CC = cast<CondCodeSDNode>(Cond->getOperand(2))->get();
2387     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2388         isNullConstant(Cond->getOperand(1)) &&
2389         // TODO: make condition below an assert after fixing ballot bitwidth.
2390         VCMP.getValueType().getSizeInBits() == ST->getWavefrontSize()) {
2391       // %VCMP = i(WaveSize) AMDGPUISD::SETCC ...
2392       // %C = i1 ISD::SETCC %VCMP, 0, setne/seteq
2393       // BRCOND i1 %C, %BB
2394       // =>
2395       // %VCMP = i(WaveSize) AMDGPUISD::SETCC ...
2396       // VCC = COPY i(WaveSize) %VCMP
2397       // S_CBRANCH_VCCNZ/VCCZ %BB
2398       Negate = CC == ISD::SETEQ;
2399       bool NegatedBallot = false;
2400       if (auto BallotCond = combineBallotPattern(VCMP, NegatedBallot)) {
2401         Cond = BallotCond;
2402         UseSCCBr = !BallotCond->isDivergent();
2403         Negate = Negate ^ NegatedBallot;
2404       } else {
2405         // TODO: don't use SCC here assuming that AMDGPUISD::SETCC is always
2406         // selected as V_CMP, but this may change for uniform condition.
2407         Cond = VCMP;
2408         UseSCCBr = false;
2409       }
2410     }
2411     // Cond is either V_CMP resulted from AMDGPUISD::SETCC or a combination of
2412     // V_CMPs resulted from ballot or ballot has uniform condition and SCC is
2413     // used.
2414     AndExec = false;
2415   }
2416 
2417   unsigned BrOp =
2418       UseSCCBr ? (Negate ? AMDGPU::S_CBRANCH_SCC0 : AMDGPU::S_CBRANCH_SCC1)
2419                : (Negate ? AMDGPU::S_CBRANCH_VCCZ : AMDGPU::S_CBRANCH_VCCNZ);
2420   Register CondReg = UseSCCBr ? AMDGPU::SCC : TRI->getVCC();
2421   SDLoc SL(N);
2422 
2423   if (AndExec) {
2424     // This is the case that we are selecting to S_CBRANCH_VCCNZ.  We have not
2425     // analyzed what generates the vcc value, so we do not know whether vcc
2426     // bits for disabled lanes are 0.  Thus we need to mask out bits for
2427     // disabled lanes.
2428     //
2429     // For the case that we select S_CBRANCH_SCC1 and it gets
2430     // changed to S_CBRANCH_VCCNZ in SIFixSGPRCopies, SIFixSGPRCopies calls
2431     // SIInstrInfo::moveToVALU which inserts the S_AND).
2432     //
2433     // We could add an analysis of what generates the vcc value here and omit
2434     // the S_AND when is unnecessary. But it would be better to add a separate
2435     // pass after SIFixSGPRCopies to do the unnecessary S_AND removal, so it
2436     // catches both cases.
2437     Cond = SDValue(CurDAG->getMachineNode(ST->isWave32() ? AMDGPU::S_AND_B32
2438                                                          : AMDGPU::S_AND_B64,
2439                      SL, MVT::i1,
2440                      CurDAG->getRegister(ST->isWave32() ? AMDGPU::EXEC_LO
2441                                                         : AMDGPU::EXEC,
2442                                          MVT::i1),
2443                     Cond),
2444                    0);
2445   }
2446 
2447   SDValue VCC = CurDAG->getCopyToReg(N->getOperand(0), SL, CondReg, Cond);
2448   CurDAG->SelectNodeTo(N, BrOp, MVT::Other,
2449                        N->getOperand(2), // Basic Block
2450                        VCC.getValue(0));
2451 }
2452 
2453 void AMDGPUDAGToDAGISel::SelectFP_EXTEND(SDNode *N) {
2454   if (Subtarget->hasSALUFloatInsts() && N->getValueType(0) == MVT::f32 &&
2455       !N->isDivergent()) {
2456     SDValue Src = N->getOperand(0);
2457     if (Src.getValueType() == MVT::f16) {
2458       if (isExtractHiElt(Src, Src)) {
2459         CurDAG->SelectNodeTo(N, AMDGPU::S_CVT_HI_F32_F16, N->getVTList(),
2460                              {Src});
2461         return;
2462       }
2463     }
2464   }
2465 
2466   SelectCode(N);
2467 }
2468 
2469 void AMDGPUDAGToDAGISel::SelectDSAppendConsume(SDNode *N, unsigned IntrID) {
2470   // The address is assumed to be uniform, so if it ends up in a VGPR, it will
2471   // be copied to an SGPR with readfirstlane.
2472   unsigned Opc = IntrID == Intrinsic::amdgcn_ds_append ?
2473     AMDGPU::DS_APPEND : AMDGPU::DS_CONSUME;
2474 
2475   SDValue Chain = N->getOperand(0);
2476   SDValue Ptr = N->getOperand(2);
2477   MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
2478   MachineMemOperand *MMO = M->getMemOperand();
2479   bool IsGDS = M->getAddressSpace() == AMDGPUAS::REGION_ADDRESS;
2480 
2481   SDValue Offset;
2482   if (CurDAG->isBaseWithConstantOffset(Ptr)) {
2483     SDValue PtrBase = Ptr.getOperand(0);
2484     SDValue PtrOffset = Ptr.getOperand(1);
2485 
2486     const APInt &OffsetVal = cast<ConstantSDNode>(PtrOffset)->getAPIntValue();
2487     if (isDSOffsetLegal(PtrBase, OffsetVal.getZExtValue())) {
2488       N = glueCopyToM0(N, PtrBase);
2489       Offset = CurDAG->getTargetConstant(OffsetVal, SDLoc(), MVT::i32);
2490     }
2491   }
2492 
2493   if (!Offset) {
2494     N = glueCopyToM0(N, Ptr);
2495     Offset = CurDAG->getTargetConstant(0, SDLoc(), MVT::i32);
2496   }
2497 
2498   SDValue Ops[] = {
2499     Offset,
2500     CurDAG->getTargetConstant(IsGDS, SDLoc(), MVT::i32),
2501     Chain,
2502     N->getOperand(N->getNumOperands() - 1) // New glue
2503   };
2504 
2505   SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
2506   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
2507 }
2508 
2509 // We need to handle this here because tablegen doesn't support matching
2510 // instructions with multiple outputs.
2511 void AMDGPUDAGToDAGISel::SelectDSBvhStackIntrinsic(SDNode *N) {
2512   unsigned Opc = AMDGPU::DS_BVH_STACK_RTN_B32;
2513   SDValue Ops[] = {N->getOperand(2), N->getOperand(3), N->getOperand(4),
2514                    N->getOperand(5), N->getOperand(0)};
2515 
2516   MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
2517   MachineMemOperand *MMO = M->getMemOperand();
2518   SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
2519   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
2520 }
2521 
2522 static unsigned gwsIntrinToOpcode(unsigned IntrID) {
2523   switch (IntrID) {
2524   case Intrinsic::amdgcn_ds_gws_init:
2525     return AMDGPU::DS_GWS_INIT;
2526   case Intrinsic::amdgcn_ds_gws_barrier:
2527     return AMDGPU::DS_GWS_BARRIER;
2528   case Intrinsic::amdgcn_ds_gws_sema_v:
2529     return AMDGPU::DS_GWS_SEMA_V;
2530   case Intrinsic::amdgcn_ds_gws_sema_br:
2531     return AMDGPU::DS_GWS_SEMA_BR;
2532   case Intrinsic::amdgcn_ds_gws_sema_p:
2533     return AMDGPU::DS_GWS_SEMA_P;
2534   case Intrinsic::amdgcn_ds_gws_sema_release_all:
2535     return AMDGPU::DS_GWS_SEMA_RELEASE_ALL;
2536   default:
2537     llvm_unreachable("not a gws intrinsic");
2538   }
2539 }
2540 
2541 void AMDGPUDAGToDAGISel::SelectDS_GWS(SDNode *N, unsigned IntrID) {
2542   if (!Subtarget->hasGWS() ||
2543       (IntrID == Intrinsic::amdgcn_ds_gws_sema_release_all &&
2544        !Subtarget->hasGWSSemaReleaseAll())) {
2545     // Let this error.
2546     SelectCode(N);
2547     return;
2548   }
2549 
2550   // Chain, intrinsic ID, vsrc, offset
2551   const bool HasVSrc = N->getNumOperands() == 4;
2552   assert(HasVSrc || N->getNumOperands() == 3);
2553 
2554   SDLoc SL(N);
2555   SDValue BaseOffset = N->getOperand(HasVSrc ? 3 : 2);
2556   int ImmOffset = 0;
2557   MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
2558   MachineMemOperand *MMO = M->getMemOperand();
2559 
2560   // Don't worry if the offset ends up in a VGPR. Only one lane will have
2561   // effect, so SIFixSGPRCopies will validly insert readfirstlane.
2562 
2563   // The resource id offset is computed as (<isa opaque base> + M0[21:16] +
2564   // offset field) % 64. Some versions of the programming guide omit the m0
2565   // part, or claim it's from offset 0.
2566   if (ConstantSDNode *ConstOffset = dyn_cast<ConstantSDNode>(BaseOffset)) {
2567     // If we have a constant offset, try to use the 0 in m0 as the base.
2568     // TODO: Look into changing the default m0 initialization value. If the
2569     // default -1 only set the low 16-bits, we could leave it as-is and add 1 to
2570     // the immediate offset.
2571     glueCopyToM0(N, CurDAG->getTargetConstant(0, SL, MVT::i32));
2572     ImmOffset = ConstOffset->getZExtValue();
2573   } else {
2574     if (CurDAG->isBaseWithConstantOffset(BaseOffset)) {
2575       ImmOffset = BaseOffset.getConstantOperandVal(1);
2576       BaseOffset = BaseOffset.getOperand(0);
2577     }
2578 
2579     // Prefer to do the shift in an SGPR since it should be possible to use m0
2580     // as the result directly. If it's already an SGPR, it will be eliminated
2581     // later.
2582     SDNode *SGPROffset
2583       = CurDAG->getMachineNode(AMDGPU::V_READFIRSTLANE_B32, SL, MVT::i32,
2584                                BaseOffset);
2585     // Shift to offset in m0
2586     SDNode *M0Base
2587       = CurDAG->getMachineNode(AMDGPU::S_LSHL_B32, SL, MVT::i32,
2588                                SDValue(SGPROffset, 0),
2589                                CurDAG->getTargetConstant(16, SL, MVT::i32));
2590     glueCopyToM0(N, SDValue(M0Base, 0));
2591   }
2592 
2593   SDValue Chain = N->getOperand(0);
2594   SDValue OffsetField = CurDAG->getTargetConstant(ImmOffset, SL, MVT::i32);
2595 
2596   const unsigned Opc = gwsIntrinToOpcode(IntrID);
2597   SmallVector<SDValue, 5> Ops;
2598   if (HasVSrc)
2599     Ops.push_back(N->getOperand(2));
2600   Ops.push_back(OffsetField);
2601   Ops.push_back(Chain);
2602 
2603   SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
2604   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
2605 }
2606 
2607 void AMDGPUDAGToDAGISel::SelectInterpP1F16(SDNode *N) {
2608   if (Subtarget->getLDSBankCount() != 16) {
2609     // This is a single instruction with a pattern.
2610     SelectCode(N);
2611     return;
2612   }
2613 
2614   SDLoc DL(N);
2615 
2616   // This requires 2 instructions. It is possible to write a pattern to support
2617   // this, but the generated isel emitter doesn't correctly deal with multiple
2618   // output instructions using the same physical register input. The copy to m0
2619   // is incorrectly placed before the second instruction.
2620   //
2621   // TODO: Match source modifiers.
2622   //
2623   // def : Pat <
2624   //   (int_amdgcn_interp_p1_f16
2625   //    (VOP3Mods f32:$src0, i32:$src0_modifiers),
2626   //                             (i32 timm:$attrchan), (i32 timm:$attr),
2627   //                             (i1 timm:$high), M0),
2628   //   (V_INTERP_P1LV_F16 $src0_modifiers, VGPR_32:$src0, timm:$attr,
2629   //       timm:$attrchan, 0,
2630   //       (V_INTERP_MOV_F32 2, timm:$attr, timm:$attrchan), timm:$high)> {
2631   //   let Predicates = [has16BankLDS];
2632   // }
2633 
2634   // 16 bank LDS
2635   SDValue ToM0 = CurDAG->getCopyToReg(CurDAG->getEntryNode(), DL, AMDGPU::M0,
2636                                       N->getOperand(5), SDValue());
2637 
2638   SDVTList VTs = CurDAG->getVTList(MVT::f32, MVT::Other);
2639 
2640   SDNode *InterpMov =
2641     CurDAG->getMachineNode(AMDGPU::V_INTERP_MOV_F32, DL, VTs, {
2642         CurDAG->getTargetConstant(2, DL, MVT::i32), // P0
2643         N->getOperand(3),  // Attr
2644         N->getOperand(2),  // Attrchan
2645         ToM0.getValue(1) // In glue
2646   });
2647 
2648   SDNode *InterpP1LV =
2649     CurDAG->getMachineNode(AMDGPU::V_INTERP_P1LV_F16, DL, MVT::f32, {
2650         CurDAG->getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
2651         N->getOperand(1), // Src0
2652         N->getOperand(3), // Attr
2653         N->getOperand(2), // Attrchan
2654         CurDAG->getTargetConstant(0, DL, MVT::i32), // $src2_modifiers
2655         SDValue(InterpMov, 0), // Src2 - holds two f16 values selected by high
2656         N->getOperand(4), // high
2657         CurDAG->getTargetConstant(0, DL, MVT::i1), // $clamp
2658         CurDAG->getTargetConstant(0, DL, MVT::i32), // $omod
2659         SDValue(InterpMov, 1)
2660   });
2661 
2662   CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), SDValue(InterpP1LV, 0));
2663 }
2664 
2665 void AMDGPUDAGToDAGISel::SelectINTRINSIC_W_CHAIN(SDNode *N) {
2666   unsigned IntrID = N->getConstantOperandVal(1);
2667   switch (IntrID) {
2668   case Intrinsic::amdgcn_ds_append:
2669   case Intrinsic::amdgcn_ds_consume: {
2670     if (N->getValueType(0) != MVT::i32)
2671       break;
2672     SelectDSAppendConsume(N, IntrID);
2673     return;
2674   }
2675   case Intrinsic::amdgcn_ds_bvh_stack_rtn:
2676     SelectDSBvhStackIntrinsic(N);
2677     return;
2678   }
2679 
2680   SelectCode(N);
2681 }
2682 
2683 void AMDGPUDAGToDAGISel::SelectINTRINSIC_WO_CHAIN(SDNode *N) {
2684   unsigned IntrID = N->getConstantOperandVal(0);
2685   unsigned Opcode;
2686   switch (IntrID) {
2687   case Intrinsic::amdgcn_wqm:
2688     Opcode = AMDGPU::WQM;
2689     break;
2690   case Intrinsic::amdgcn_softwqm:
2691     Opcode = AMDGPU::SOFT_WQM;
2692     break;
2693   case Intrinsic::amdgcn_wwm:
2694   case Intrinsic::amdgcn_strict_wwm:
2695     Opcode = AMDGPU::STRICT_WWM;
2696     break;
2697   case Intrinsic::amdgcn_strict_wqm:
2698     Opcode = AMDGPU::STRICT_WQM;
2699     break;
2700   case Intrinsic::amdgcn_interp_p1_f16:
2701     SelectInterpP1F16(N);
2702     return;
2703   case Intrinsic::amdgcn_inverse_ballot:
2704     switch (N->getOperand(1).getValueSizeInBits()) {
2705     case 32:
2706       Opcode = AMDGPU::S_INVERSE_BALLOT_U32;
2707       break;
2708     case 64:
2709       Opcode = AMDGPU::S_INVERSE_BALLOT_U64;
2710       break;
2711     default:
2712       llvm_unreachable("Unsupported size for inverse ballot mask.");
2713     }
2714     break;
2715   default:
2716     SelectCode(N);
2717     return;
2718   }
2719 
2720   SDValue Src = N->getOperand(1);
2721   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), {Src});
2722 }
2723 
2724 void AMDGPUDAGToDAGISel::SelectINTRINSIC_VOID(SDNode *N) {
2725   unsigned IntrID = N->getConstantOperandVal(1);
2726   switch (IntrID) {
2727   case Intrinsic::amdgcn_ds_gws_init:
2728   case Intrinsic::amdgcn_ds_gws_barrier:
2729   case Intrinsic::amdgcn_ds_gws_sema_v:
2730   case Intrinsic::amdgcn_ds_gws_sema_br:
2731   case Intrinsic::amdgcn_ds_gws_sema_p:
2732   case Intrinsic::amdgcn_ds_gws_sema_release_all:
2733     SelectDS_GWS(N, IntrID);
2734     return;
2735   default:
2736     break;
2737   }
2738 
2739   SelectCode(N);
2740 }
2741 
2742 void AMDGPUDAGToDAGISel::SelectWAVE_ADDRESS(SDNode *N) {
2743   SDValue Log2WaveSize =
2744     CurDAG->getTargetConstant(Subtarget->getWavefrontSizeLog2(), SDLoc(N), MVT::i32);
2745   CurDAG->SelectNodeTo(N, AMDGPU::S_LSHR_B32, N->getVTList(),
2746                        {N->getOperand(0), Log2WaveSize});
2747 }
2748 
2749 void AMDGPUDAGToDAGISel::SelectSTACKRESTORE(SDNode *N) {
2750   SDValue SrcVal = N->getOperand(1);
2751   if (SrcVal.getValueType() != MVT::i32) {
2752     SelectCode(N); // Emit default error
2753     return;
2754   }
2755 
2756   SDValue CopyVal;
2757   Register SP = TLI->getStackPointerRegisterToSaveRestore();
2758   SDLoc SL(N);
2759 
2760   if (SrcVal.getOpcode() == AMDGPUISD::WAVE_ADDRESS) {
2761     CopyVal = SrcVal.getOperand(0);
2762   } else {
2763     SDValue Log2WaveSize = CurDAG->getTargetConstant(
2764         Subtarget->getWavefrontSizeLog2(), SL, MVT::i32);
2765 
2766     if (N->isDivergent()) {
2767       SrcVal = SDValue(CurDAG->getMachineNode(AMDGPU::V_READFIRSTLANE_B32, SL,
2768                                               MVT::i32, SrcVal),
2769                        0);
2770     }
2771 
2772     CopyVal = SDValue(CurDAG->getMachineNode(AMDGPU::S_LSHL_B32, SL, MVT::i32,
2773                                              {SrcVal, Log2WaveSize}),
2774                       0);
2775   }
2776 
2777   SDValue CopyToSP = CurDAG->getCopyToReg(N->getOperand(0), SL, SP, CopyVal);
2778   CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyToSP);
2779 }
2780 
2781 bool AMDGPUDAGToDAGISel::SelectVOP3ModsImpl(SDValue In, SDValue &Src,
2782                                             unsigned &Mods,
2783                                             bool IsCanonicalizing,
2784                                             bool AllowAbs) const {
2785   Mods = SISrcMods::NONE;
2786   Src = In;
2787 
2788   if (Src.getOpcode() == ISD::FNEG) {
2789     Mods |= SISrcMods::NEG;
2790     Src = Src.getOperand(0);
2791   } else if (Src.getOpcode() == ISD::FSUB && IsCanonicalizing) {
2792     // Fold fsub [+-]0 into fneg. This may not have folded depending on the
2793     // denormal mode, but we're implicitly canonicalizing in a source operand.
2794     auto *LHS = dyn_cast<ConstantFPSDNode>(Src.getOperand(0));
2795     if (LHS && LHS->isZero()) {
2796       Mods |= SISrcMods::NEG;
2797       Src = Src.getOperand(1);
2798     }
2799   }
2800 
2801   if (AllowAbs && Src.getOpcode() == ISD::FABS) {
2802     Mods |= SISrcMods::ABS;
2803     Src = Src.getOperand(0);
2804   }
2805 
2806   return true;
2807 }
2808 
2809 bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
2810                                         SDValue &SrcMods) const {
2811   unsigned Mods;
2812   if (SelectVOP3ModsImpl(In, Src, Mods, /*IsCanonicalizing=*/true,
2813                          /*AllowAbs=*/true)) {
2814     SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2815     return true;
2816   }
2817 
2818   return false;
2819 }
2820 
2821 bool AMDGPUDAGToDAGISel::SelectVOP3ModsNonCanonicalizing(
2822     SDValue In, SDValue &Src, SDValue &SrcMods) const {
2823   unsigned Mods;
2824   if (SelectVOP3ModsImpl(In, Src, Mods, /*IsCanonicalizing=*/false,
2825                          /*AllowAbs=*/true)) {
2826     SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2827     return true;
2828   }
2829 
2830   return false;
2831 }
2832 
2833 bool AMDGPUDAGToDAGISel::SelectVOP3BMods(SDValue In, SDValue &Src,
2834                                          SDValue &SrcMods) const {
2835   unsigned Mods;
2836   if (SelectVOP3ModsImpl(In, Src, Mods,
2837                          /*IsCanonicalizing=*/true,
2838                          /*AllowAbs=*/false)) {
2839     SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2840     return true;
2841   }
2842 
2843   return false;
2844 }
2845 
2846 bool AMDGPUDAGToDAGISel::SelectVOP3NoMods(SDValue In, SDValue &Src) const {
2847   if (In.getOpcode() == ISD::FABS || In.getOpcode() == ISD::FNEG)
2848     return false;
2849 
2850   Src = In;
2851   return true;
2852 }
2853 
2854 bool AMDGPUDAGToDAGISel::SelectVINTERPModsImpl(SDValue In, SDValue &Src,
2855                                                SDValue &SrcMods,
2856                                                bool OpSel) const {
2857   unsigned Mods;
2858   if (SelectVOP3ModsImpl(In, Src, Mods,
2859                          /*IsCanonicalizing=*/true,
2860                          /*AllowAbs=*/false)) {
2861     if (OpSel)
2862       Mods |= SISrcMods::OP_SEL_0;
2863     SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2864     return true;
2865   }
2866 
2867   return false;
2868 }
2869 
2870 bool AMDGPUDAGToDAGISel::SelectVINTERPMods(SDValue In, SDValue &Src,
2871                                            SDValue &SrcMods) const {
2872   return SelectVINTERPModsImpl(In, Src, SrcMods, /* OpSel */ false);
2873 }
2874 
2875 bool AMDGPUDAGToDAGISel::SelectVINTERPModsHi(SDValue In, SDValue &Src,
2876                                              SDValue &SrcMods) const {
2877   return SelectVINTERPModsImpl(In, Src, SrcMods, /* OpSel */ true);
2878 }
2879 
2880 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
2881                                          SDValue &SrcMods, SDValue &Clamp,
2882                                          SDValue &Omod) const {
2883   SDLoc DL(In);
2884   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
2885   Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
2886 
2887   return SelectVOP3Mods(In, Src, SrcMods);
2888 }
2889 
2890 bool AMDGPUDAGToDAGISel::SelectVOP3BMods0(SDValue In, SDValue &Src,
2891                                           SDValue &SrcMods, SDValue &Clamp,
2892                                           SDValue &Omod) const {
2893   SDLoc DL(In);
2894   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
2895   Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
2896 
2897   return SelectVOP3BMods(In, Src, SrcMods);
2898 }
2899 
2900 bool AMDGPUDAGToDAGISel::SelectVOP3OMods(SDValue In, SDValue &Src,
2901                                          SDValue &Clamp, SDValue &Omod) const {
2902   Src = In;
2903 
2904   SDLoc DL(In);
2905   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
2906   Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
2907 
2908   return true;
2909 }
2910 
2911 bool AMDGPUDAGToDAGISel::SelectVOP3PMods(SDValue In, SDValue &Src,
2912                                          SDValue &SrcMods, bool IsDOT) const {
2913   unsigned Mods = SISrcMods::NONE;
2914   Src = In;
2915 
2916   // TODO: Handle G_FSUB 0 as fneg
2917   if (Src.getOpcode() == ISD::FNEG) {
2918     Mods ^= (SISrcMods::NEG | SISrcMods::NEG_HI);
2919     Src = Src.getOperand(0);
2920   }
2921 
2922   if (Src.getOpcode() == ISD::BUILD_VECTOR && Src.getNumOperands() == 2 &&
2923       (!IsDOT || !Subtarget->hasDOTOpSelHazard())) {
2924     unsigned VecMods = Mods;
2925 
2926     SDValue Lo = stripBitcast(Src.getOperand(0));
2927     SDValue Hi = stripBitcast(Src.getOperand(1));
2928 
2929     if (Lo.getOpcode() == ISD::FNEG) {
2930       Lo = stripBitcast(Lo.getOperand(0));
2931       Mods ^= SISrcMods::NEG;
2932     }
2933 
2934     if (Hi.getOpcode() == ISD::FNEG) {
2935       Hi = stripBitcast(Hi.getOperand(0));
2936       Mods ^= SISrcMods::NEG_HI;
2937     }
2938 
2939     if (isExtractHiElt(Lo, Lo))
2940       Mods |= SISrcMods::OP_SEL_0;
2941 
2942     if (isExtractHiElt(Hi, Hi))
2943       Mods |= SISrcMods::OP_SEL_1;
2944 
2945     unsigned VecSize = Src.getValueSizeInBits();
2946     Lo = stripExtractLoElt(Lo);
2947     Hi = stripExtractLoElt(Hi);
2948 
2949     if (Lo.getValueSizeInBits() > VecSize) {
2950       Lo = CurDAG->getTargetExtractSubreg(
2951         (VecSize > 32) ? AMDGPU::sub0_sub1 : AMDGPU::sub0, SDLoc(In),
2952         MVT::getIntegerVT(VecSize), Lo);
2953     }
2954 
2955     if (Hi.getValueSizeInBits() > VecSize) {
2956       Hi = CurDAG->getTargetExtractSubreg(
2957         (VecSize > 32) ? AMDGPU::sub0_sub1 : AMDGPU::sub0, SDLoc(In),
2958         MVT::getIntegerVT(VecSize), Hi);
2959     }
2960 
2961     assert(Lo.getValueSizeInBits() <= VecSize &&
2962            Hi.getValueSizeInBits() <= VecSize);
2963 
2964     if (Lo == Hi && !isInlineImmediate(Lo.getNode())) {
2965       // Really a scalar input. Just select from the low half of the register to
2966       // avoid packing.
2967 
2968       if (VecSize == 32 || VecSize == Lo.getValueSizeInBits()) {
2969         Src = Lo;
2970       } else {
2971         assert(Lo.getValueSizeInBits() == 32 && VecSize == 64);
2972 
2973         SDLoc SL(In);
2974         SDValue Undef = SDValue(
2975           CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, SL,
2976                                  Lo.getValueType()), 0);
2977         auto RC = Lo->isDivergent() ? AMDGPU::VReg_64RegClassID
2978                                     : AMDGPU::SReg_64RegClassID;
2979         const SDValue Ops[] = {
2980           CurDAG->getTargetConstant(RC, SL, MVT::i32),
2981           Lo, CurDAG->getTargetConstant(AMDGPU::sub0, SL, MVT::i32),
2982           Undef, CurDAG->getTargetConstant(AMDGPU::sub1, SL, MVT::i32) };
2983 
2984         Src = SDValue(CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, SL,
2985                                              Src.getValueType(), Ops), 0);
2986       }
2987       SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2988       return true;
2989     }
2990 
2991     if (VecSize == 64 && Lo == Hi && isa<ConstantFPSDNode>(Lo)) {
2992       uint64_t Lit = cast<ConstantFPSDNode>(Lo)->getValueAPF()
2993                       .bitcastToAPInt().getZExtValue();
2994       if (AMDGPU::isInlinableLiteral32(Lit, Subtarget->hasInv2PiInlineImm())) {
2995         Src = CurDAG->getTargetConstant(Lit, SDLoc(In), MVT::i64);
2996         SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2997         return true;
2998       }
2999     }
3000 
3001     Mods = VecMods;
3002   }
3003 
3004   // Packed instructions do not have abs modifiers.
3005   Mods |= SISrcMods::OP_SEL_1;
3006 
3007   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3008   return true;
3009 }
3010 
3011 bool AMDGPUDAGToDAGISel::SelectVOP3PModsDOT(SDValue In, SDValue &Src,
3012                                             SDValue &SrcMods) const {
3013   return SelectVOP3PMods(In, Src, SrcMods, true);
3014 }
3015 
3016 bool AMDGPUDAGToDAGISel::SelectDotIUVOP3PMods(SDValue In, SDValue &Src) const {
3017   const ConstantSDNode *C = cast<ConstantSDNode>(In);
3018   // Literal i1 value set in intrinsic, represents SrcMods for the next operand.
3019   // 1 promotes packed values to signed, 0 treats them as unsigned.
3020   assert(C->getAPIntValue().getBitWidth() == 1 && "expected i1 value");
3021 
3022   unsigned Mods = SISrcMods::OP_SEL_1;
3023   unsigned SrcSign = C->getZExtValue();
3024   if (SrcSign == 1)
3025     Mods ^= SISrcMods::NEG;
3026 
3027   Src = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3028   return true;
3029 }
3030 
3031 bool AMDGPUDAGToDAGISel::SelectWMMAOpSelVOP3PMods(SDValue In,
3032                                                   SDValue &Src) const {
3033   const ConstantSDNode *C = cast<ConstantSDNode>(In);
3034   assert(C->getAPIntValue().getBitWidth() == 1 && "expected i1 value");
3035 
3036   unsigned Mods = SISrcMods::OP_SEL_1;
3037   unsigned SrcVal = C->getZExtValue();
3038   if (SrcVal == 1)
3039     Mods |= SISrcMods::OP_SEL_0;
3040 
3041   Src = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3042   return true;
3043 }
3044 
3045 bool AMDGPUDAGToDAGISel::SelectVOP3OpSel(SDValue In, SDValue &Src,
3046                                          SDValue &SrcMods) const {
3047   Src = In;
3048   // FIXME: Handle op_sel
3049   SrcMods = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);
3050   return true;
3051 }
3052 
3053 bool AMDGPUDAGToDAGISel::SelectVOP3OpSelMods(SDValue In, SDValue &Src,
3054                                              SDValue &SrcMods) const {
3055   // FIXME: Handle op_sel
3056   return SelectVOP3Mods(In, Src, SrcMods);
3057 }
3058 
3059 // The return value is not whether the match is possible (which it always is),
3060 // but whether or not it a conversion is really used.
3061 bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsImpl(SDValue In, SDValue &Src,
3062                                                    unsigned &Mods) const {
3063   Mods = 0;
3064   SelectVOP3ModsImpl(In, Src, Mods);
3065 
3066   if (Src.getOpcode() == ISD::FP_EXTEND) {
3067     Src = Src.getOperand(0);
3068     assert(Src.getValueType() == MVT::f16);
3069     Src = stripBitcast(Src);
3070 
3071     // Be careful about folding modifiers if we already have an abs. fneg is
3072     // applied last, so we don't want to apply an earlier fneg.
3073     if ((Mods & SISrcMods::ABS) == 0) {
3074       unsigned ModsTmp;
3075       SelectVOP3ModsImpl(Src, Src, ModsTmp);
3076 
3077       if ((ModsTmp & SISrcMods::NEG) != 0)
3078         Mods ^= SISrcMods::NEG;
3079 
3080       if ((ModsTmp & SISrcMods::ABS) != 0)
3081         Mods |= SISrcMods::ABS;
3082     }
3083 
3084     // op_sel/op_sel_hi decide the source type and source.
3085     // If the source's op_sel_hi is set, it indicates to do a conversion from fp16.
3086     // If the sources's op_sel is set, it picks the high half of the source
3087     // register.
3088 
3089     Mods |= SISrcMods::OP_SEL_1;
3090     if (isExtractHiElt(Src, Src)) {
3091       Mods |= SISrcMods::OP_SEL_0;
3092 
3093       // TODO: Should we try to look for neg/abs here?
3094     }
3095 
3096     return true;
3097   }
3098 
3099   return false;
3100 }
3101 
3102 bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsExt(SDValue In, SDValue &Src,
3103                                                   SDValue &SrcMods) const {
3104   unsigned Mods = 0;
3105   if (!SelectVOP3PMadMixModsImpl(In, Src, Mods))
3106     return false;
3107   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3108   return true;
3109 }
3110 
3111 bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixMods(SDValue In, SDValue &Src,
3112                                                SDValue &SrcMods) const {
3113   unsigned Mods = 0;
3114   SelectVOP3PMadMixModsImpl(In, Src, Mods);
3115   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
3116   return true;
3117 }
3118 
3119 SDValue AMDGPUDAGToDAGISel::getHi16Elt(SDValue In) const {
3120   if (In.isUndef())
3121     return CurDAG->getUNDEF(MVT::i32);
3122 
3123   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(In)) {
3124     SDLoc SL(In);
3125     return CurDAG->getConstant(C->getZExtValue() << 16, SL, MVT::i32);
3126   }
3127 
3128   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(In)) {
3129     SDLoc SL(In);
3130     return CurDAG->getConstant(
3131       C->getValueAPF().bitcastToAPInt().getZExtValue() << 16, SL, MVT::i32);
3132   }
3133 
3134   SDValue Src;
3135   if (isExtractHiElt(In, Src))
3136     return Src;
3137 
3138   return SDValue();
3139 }
3140 
3141 bool AMDGPUDAGToDAGISel::isVGPRImm(const SDNode * N) const {
3142   assert(CurDAG->getTarget().getTargetTriple().getArch() == Triple::amdgcn);
3143 
3144   const SIRegisterInfo *SIRI =
3145     static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
3146   const SIInstrInfo * SII =
3147     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
3148 
3149   unsigned Limit = 0;
3150   bool AllUsesAcceptSReg = true;
3151   for (SDNode::use_iterator U = N->use_begin(), E = SDNode::use_end();
3152     Limit < 10 && U != E; ++U, ++Limit) {
3153     const TargetRegisterClass *RC = getOperandRegClass(*U, U.getOperandNo());
3154 
3155     // If the register class is unknown, it could be an unknown
3156     // register class that needs to be an SGPR, e.g. an inline asm
3157     // constraint
3158     if (!RC || SIRI->isSGPRClass(RC))
3159       return false;
3160 
3161     if (RC != &AMDGPU::VS_32RegClass && RC != &AMDGPU::VS_64RegClass) {
3162       AllUsesAcceptSReg = false;
3163       SDNode * User = *U;
3164       if (User->isMachineOpcode()) {
3165         unsigned Opc = User->getMachineOpcode();
3166         const MCInstrDesc &Desc = SII->get(Opc);
3167         if (Desc.isCommutable()) {
3168           unsigned OpIdx = Desc.getNumDefs() + U.getOperandNo();
3169           unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
3170           if (SII->findCommutedOpIndices(Desc, OpIdx, CommuteIdx1)) {
3171             unsigned CommutedOpNo = CommuteIdx1 - Desc.getNumDefs();
3172             const TargetRegisterClass *CommutedRC = getOperandRegClass(*U, CommutedOpNo);
3173             if (CommutedRC == &AMDGPU::VS_32RegClass ||
3174                 CommutedRC == &AMDGPU::VS_64RegClass)
3175               AllUsesAcceptSReg = true;
3176           }
3177         }
3178       }
3179       // If "AllUsesAcceptSReg == false" so far we haven't succeeded
3180       // commuting current user. This means have at least one use
3181       // that strictly require VGPR. Thus, we will not attempt to commute
3182       // other user instructions.
3183       if (!AllUsesAcceptSReg)
3184         break;
3185     }
3186   }
3187   return !AllUsesAcceptSReg && (Limit < 10);
3188 }
3189 
3190 bool AMDGPUDAGToDAGISel::isUniformLoad(const SDNode * N) const {
3191   auto Ld = cast<LoadSDNode>(N);
3192 
3193   if (N->isDivergent() && !AMDGPUInstrInfo::isUniformMMO(Ld->getMemOperand()))
3194     return false;
3195 
3196   return Ld->getAlign() >= Align(4) &&
3197          ((Ld->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
3198            Ld->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ||
3199           (Subtarget->getScalarizeGlobalBehavior() &&
3200            Ld->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
3201            Ld->isSimple() &&
3202            static_cast<const SITargetLowering *>(getTargetLowering())
3203                ->isMemOpHasNoClobberedMemOperand(N)));
3204 }
3205 
3206 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
3207   const AMDGPUTargetLowering& Lowering =
3208     *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
3209   bool IsModified = false;
3210   do {
3211     IsModified = false;
3212 
3213     // Go over all selected nodes and try to fold them a bit more
3214     SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_begin();
3215     while (Position != CurDAG->allnodes_end()) {
3216       SDNode *Node = &*Position++;
3217       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(Node);
3218       if (!MachineNode)
3219         continue;
3220 
3221       SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
3222       if (ResNode != Node) {
3223         if (ResNode)
3224           ReplaceUses(Node, ResNode);
3225         IsModified = true;
3226       }
3227     }
3228     CurDAG->RemoveDeadNodes();
3229   } while (IsModified);
3230 }
3231 
3232 char AMDGPUDAGToDAGISel::ID = 0;
3233