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 "AMDGPU.h"
15 #include "AMDGPUArgumentUsageInfo.h"
16 #include "AMDGPUISelLowering.h" // For AMDGPUISD
17 #include "AMDGPUInstrInfo.h"
18 #include "AMDGPUPerfHintAnalysis.h"
19 #include "AMDGPURegisterInfo.h"
20 #include "AMDGPUSubtarget.h"
21 #include "AMDGPUTargetMachine.h"
22 #include "SIDefines.h"
23 #include "SIISelLowering.h"
24 #include "SIInstrInfo.h"
25 #include "SIMachineFunctionInfo.h"
26 #include "SIRegisterInfo.h"
27 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/CodeGen/FunctionLoweringInfo.h"
34 #include "llvm/CodeGen/ISDOpcodes.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/CodeGen/SelectionDAGISel.h"
39 #include "llvm/CodeGen/SelectionDAGNodes.h"
40 #include "llvm/CodeGen/ValueTypes.h"
41 #include "llvm/IR/BasicBlock.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/MC/MCInstrDesc.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CodeGen.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MachineValueType.h"
48 #include "llvm/Support/MathExtras.h"
49 #include <cassert>
50 #include <cstdint>
51 #include <new>
52 #include <vector>
53 
54 #define DEBUG_TYPE "isel"
55 
56 using namespace llvm;
57 
58 namespace llvm {
59 
60 class R600InstrInfo;
61 
62 } // end namespace llvm
63 
64 //===----------------------------------------------------------------------===//
65 // Instruction Selector Implementation
66 //===----------------------------------------------------------------------===//
67 
68 namespace {
69 
70 /// AMDGPU specific code to select AMDGPU machine instructions for
71 /// SelectionDAG operations.
72 class AMDGPUDAGToDAGISel : public SelectionDAGISel {
73   // Subtarget - Keep a pointer to the AMDGPU Subtarget around so that we can
74   // make the right decision when generating code for different targets.
75   const GCNSubtarget *Subtarget;
76   bool EnableLateStructurizeCFG;
77 
78 public:
79   explicit AMDGPUDAGToDAGISel(TargetMachine *TM = nullptr,
80                               CodeGenOpt::Level OptLevel = CodeGenOpt::Default)
81     : SelectionDAGISel(*TM, OptLevel) {
82     EnableLateStructurizeCFG = AMDGPUTargetMachine::EnableLateStructurizeCFG;
83   }
84   ~AMDGPUDAGToDAGISel() override = default;
85 
86   void getAnalysisUsage(AnalysisUsage &AU) const override {
87     AU.addRequired<AMDGPUArgumentUsageInfo>();
88     AU.addRequired<AMDGPUPerfHintAnalysis>();
89     AU.addRequired<LegacyDivergenceAnalysis>();
90     SelectionDAGISel::getAnalysisUsage(AU);
91   }
92 
93   bool matchLoadD16FromBuildVector(SDNode *N) const;
94 
95   bool runOnMachineFunction(MachineFunction &MF) override;
96   void PreprocessISelDAG() override;
97   void Select(SDNode *N) override;
98   StringRef getPassName() const override;
99   void PostprocessISelDAG() override;
100 
101 protected:
102   void SelectBuildVector(SDNode *N, unsigned RegClassID);
103 
104 private:
105   std::pair<SDValue, SDValue> foldFrameIndex(SDValue N) const;
106   bool isNoNanSrc(SDValue N) const;
107   bool isInlineImmediate(const SDNode *N) const;
108   bool isVGPRImm(const SDNode *N) const;
109   bool isUniformLoad(const SDNode *N) const;
110   bool isUniformBr(const SDNode *N) const;
111 
112   MachineSDNode *buildSMovImm64(SDLoc &DL, uint64_t Val, EVT VT) const;
113 
114   SDNode *glueCopyToM0LDSInit(SDNode *N) const;
115   SDNode *glueCopyToM0(SDNode *N, SDValue Val) const;
116 
117   const TargetRegisterClass *getOperandRegClass(SDNode *N, unsigned OpNo) const;
118   virtual bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
119   virtual bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
120   bool isDSOffsetLegal(SDValue Base, unsigned Offset,
121                        unsigned OffsetBits) const;
122   bool SelectDS1Addr1Offset(SDValue Ptr, SDValue &Base, SDValue &Offset) const;
123   bool SelectDS64Bit4ByteAligned(SDValue Ptr, SDValue &Base, SDValue &Offset0,
124                                  SDValue &Offset1) const;
125   bool SelectMUBUF(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
126                    SDValue &SOffset, SDValue &Offset, SDValue &Offen,
127                    SDValue &Idxen, SDValue &Addr64, SDValue &GLC, SDValue &SLC,
128                    SDValue &TFE, SDValue &DLC) const;
129   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
130                          SDValue &SOffset, SDValue &Offset, SDValue &GLC,
131                          SDValue &SLC, SDValue &TFE, SDValue &DLC) const;
132   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
133                          SDValue &VAddr, SDValue &SOffset, SDValue &Offset,
134                          SDValue &SLC) const;
135   bool SelectMUBUFScratchOffen(SDNode *Parent,
136                                SDValue Addr, SDValue &RSrc, SDValue &VAddr,
137                                SDValue &SOffset, SDValue &ImmOffset) const;
138   bool SelectMUBUFScratchOffset(SDNode *Parent,
139                                 SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
140                                 SDValue &Offset) const;
141 
142   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &SOffset,
143                          SDValue &Offset, SDValue &GLC, SDValue &SLC,
144                          SDValue &TFE, SDValue &DLC) const;
145   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
146                          SDValue &Offset, SDValue &SLC) const;
147   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
148                          SDValue &Offset) const;
149 
150   bool SelectFlatAtomic(SDNode *N, SDValue Addr, SDValue &VAddr,
151                         SDValue &Offset, SDValue &SLC) const;
152   bool SelectFlatAtomicSigned(SDNode *N, SDValue Addr, SDValue &VAddr,
153                               SDValue &Offset, SDValue &SLC) const;
154 
155   template <bool IsSigned>
156   bool SelectFlatOffset(SDNode *N, SDValue Addr, SDValue &VAddr,
157                         SDValue &Offset, SDValue &SLC) const;
158 
159   bool SelectSMRDOffset(SDValue ByteOffsetNode, SDValue &Offset,
160                         bool &Imm) const;
161   SDValue Expand32BitAddress(SDValue Addr) const;
162   bool SelectSMRD(SDValue Addr, SDValue &SBase, SDValue &Offset,
163                   bool &Imm) const;
164   bool SelectSMRDImm(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
165   bool SelectSMRDImm32(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
166   bool SelectSMRDSgpr(SDValue Addr, SDValue &SBase, SDValue &Offset) const;
167   bool SelectSMRDBufferImm(SDValue Addr, SDValue &Offset) const;
168   bool SelectSMRDBufferImm32(SDValue Addr, SDValue &Offset) const;
169   bool SelectMOVRELOffset(SDValue Index, SDValue &Base, SDValue &Offset) const;
170 
171   bool SelectVOP3Mods_NNaN(SDValue In, SDValue &Src, SDValue &SrcMods) const;
172   bool SelectVOP3ModsImpl(SDValue In, SDValue &Src, unsigned &SrcMods) const;
173   bool SelectVOP3Mods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
174   bool SelectVOP3NoMods(SDValue In, SDValue &Src) const;
175   bool SelectVOP3Mods0(SDValue In, SDValue &Src, SDValue &SrcMods,
176                        SDValue &Clamp, SDValue &Omod) const;
177   bool SelectVOP3NoMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
178                          SDValue &Clamp, SDValue &Omod) const;
179 
180   bool SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src, SDValue &SrcMods,
181                                  SDValue &Clamp,
182                                  SDValue &Omod) const;
183 
184   bool SelectVOP3OMods(SDValue In, SDValue &Src,
185                        SDValue &Clamp, SDValue &Omod) const;
186 
187   bool SelectVOP3PMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
188   bool SelectVOP3PMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
189                         SDValue &Clamp) const;
190 
191   bool SelectVOP3OpSel(SDValue In, SDValue &Src, SDValue &SrcMods) const;
192   bool SelectVOP3OpSel0(SDValue In, SDValue &Src, SDValue &SrcMods,
193                         SDValue &Clamp) const;
194 
195   bool SelectVOP3OpSelMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
196   bool SelectVOP3OpSelMods0(SDValue In, SDValue &Src, SDValue &SrcMods,
197                             SDValue &Clamp) const;
198   bool SelectVOP3PMadMixModsImpl(SDValue In, SDValue &Src, unsigned &Mods) const;
199   bool SelectVOP3PMadMixMods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
200 
201   SDValue getHi16Elt(SDValue In) const;
202 
203   void SelectADD_SUB_I64(SDNode *N);
204   void SelectAddcSubb(SDNode *N);
205   void SelectUADDO_USUBO(SDNode *N);
206   void SelectDIV_SCALE(SDNode *N);
207   void SelectDIV_FMAS(SDNode *N);
208   void SelectMAD_64_32(SDNode *N);
209   void SelectFMA_W_CHAIN(SDNode *N);
210   void SelectFMUL_W_CHAIN(SDNode *N);
211 
212   SDNode *getS_BFE(unsigned Opcode, const SDLoc &DL, SDValue Val,
213                    uint32_t Offset, uint32_t Width);
214   void SelectS_BFEFromShifts(SDNode *N);
215   void SelectS_BFE(SDNode *N);
216   bool isCBranchSCC(const SDNode *N) const;
217   void SelectBRCOND(SDNode *N);
218   void SelectFMAD_FMA(SDNode *N);
219   void SelectATOMIC_CMP_SWAP(SDNode *N);
220   void SelectDSAppendConsume(SDNode *N, unsigned IntrID);
221   void SelectDS_GWS(SDNode *N, unsigned IntrID);
222   void SelectINTRINSIC_W_CHAIN(SDNode *N);
223   void SelectINTRINSIC_VOID(SDNode *N);
224 
225 protected:
226   // Include the pieces autogenerated from the target description.
227 #include "AMDGPUGenDAGISel.inc"
228 };
229 
230 class R600DAGToDAGISel : public AMDGPUDAGToDAGISel {
231   const R600Subtarget *Subtarget;
232 
233   bool isConstantLoad(const MemSDNode *N, int cbID) const;
234   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
235   bool SelectGlobalValueVariableOffset(SDValue Addr, SDValue &BaseReg,
236                                        SDValue& Offset);
237 public:
238   explicit R600DAGToDAGISel(TargetMachine *TM, CodeGenOpt::Level OptLevel) :
239       AMDGPUDAGToDAGISel(TM, OptLevel) {}
240 
241   void Select(SDNode *N) override;
242 
243   bool SelectADDRIndirect(SDValue Addr, SDValue &Base,
244                           SDValue &Offset) override;
245   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
246                           SDValue &Offset) override;
247 
248   bool runOnMachineFunction(MachineFunction &MF) override;
249 
250   void PreprocessISelDAG() override {}
251 
252 protected:
253   // Include the pieces autogenerated from the target description.
254 #include "R600GenDAGISel.inc"
255 };
256 
257 static SDValue stripBitcast(SDValue Val) {
258   return Val.getOpcode() == ISD::BITCAST ? Val.getOperand(0) : Val;
259 }
260 
261 // Figure out if this is really an extract of the high 16-bits of a dword.
262 static bool isExtractHiElt(SDValue In, SDValue &Out) {
263   In = stripBitcast(In);
264   if (In.getOpcode() != ISD::TRUNCATE)
265     return false;
266 
267   SDValue Srl = In.getOperand(0);
268   if (Srl.getOpcode() == ISD::SRL) {
269     if (ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
270       if (ShiftAmt->getZExtValue() == 16) {
271         Out = stripBitcast(Srl.getOperand(0));
272         return true;
273       }
274     }
275   }
276 
277   return false;
278 }
279 
280 // Look through operations that obscure just looking at the low 16-bits of the
281 // same register.
282 static SDValue stripExtractLoElt(SDValue In) {
283   if (In.getOpcode() == ISD::TRUNCATE) {
284     SDValue Src = In.getOperand(0);
285     if (Src.getValueType().getSizeInBits() == 32)
286       return stripBitcast(Src);
287   }
288 
289   return In;
290 }
291 
292 }  // end anonymous namespace
293 
294 INITIALIZE_PASS_BEGIN(AMDGPUDAGToDAGISel, "amdgpu-isel",
295                       "AMDGPU DAG->DAG Pattern Instruction Selection", false, false)
296 INITIALIZE_PASS_DEPENDENCY(AMDGPUArgumentUsageInfo)
297 INITIALIZE_PASS_DEPENDENCY(AMDGPUPerfHintAnalysis)
298 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
299 INITIALIZE_PASS_END(AMDGPUDAGToDAGISel, "amdgpu-isel",
300                     "AMDGPU DAG->DAG Pattern Instruction Selection", false, false)
301 
302 /// This pass converts a legalized DAG into a AMDGPU-specific
303 // DAG, ready for instruction scheduling.
304 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine *TM,
305                                         CodeGenOpt::Level OptLevel) {
306   return new AMDGPUDAGToDAGISel(TM, OptLevel);
307 }
308 
309 /// This pass converts a legalized DAG into a R600-specific
310 // DAG, ready for instruction scheduling.
311 FunctionPass *llvm::createR600ISelDag(TargetMachine *TM,
312                                       CodeGenOpt::Level OptLevel) {
313   return new R600DAGToDAGISel(TM, OptLevel);
314 }
315 
316 bool AMDGPUDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
317   Subtarget = &MF.getSubtarget<GCNSubtarget>();
318   return SelectionDAGISel::runOnMachineFunction(MF);
319 }
320 
321 bool AMDGPUDAGToDAGISel::matchLoadD16FromBuildVector(SDNode *N) const {
322   assert(Subtarget->d16PreservesUnusedBits());
323   MVT VT = N->getValueType(0).getSimpleVT();
324   if (VT != MVT::v2i16 && VT != MVT::v2f16)
325     return false;
326 
327   SDValue Lo = N->getOperand(0);
328   SDValue Hi = N->getOperand(1);
329 
330   LoadSDNode *LdHi = dyn_cast<LoadSDNode>(stripBitcast(Hi));
331 
332   // build_vector lo, (load ptr) -> load_d16_hi ptr, lo
333   // build_vector lo, (zextload ptr from i8) -> load_d16_hi_u8 ptr, lo
334   // build_vector lo, (sextload ptr from i8) -> load_d16_hi_i8 ptr, lo
335 
336   // Need to check for possible indirect dependencies on the other half of the
337   // vector to avoid introducing a cycle.
338   if (LdHi && Hi.hasOneUse() && !LdHi->isPredecessorOf(Lo.getNode())) {
339     SDVTList VTList = CurDAG->getVTList(VT, MVT::Other);
340 
341     SDValue TiedIn = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Lo);
342     SDValue Ops[] = {
343       LdHi->getChain(), LdHi->getBasePtr(), TiedIn
344     };
345 
346     unsigned LoadOp = AMDGPUISD::LOAD_D16_HI;
347     if (LdHi->getMemoryVT() == MVT::i8) {
348       LoadOp = LdHi->getExtensionType() == ISD::SEXTLOAD ?
349         AMDGPUISD::LOAD_D16_HI_I8 : AMDGPUISD::LOAD_D16_HI_U8;
350     } else {
351       assert(LdHi->getMemoryVT() == MVT::i16);
352     }
353 
354     SDValue NewLoadHi =
355       CurDAG->getMemIntrinsicNode(LoadOp, SDLoc(LdHi), VTList,
356                                   Ops, LdHi->getMemoryVT(),
357                                   LdHi->getMemOperand());
358 
359     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), NewLoadHi);
360     CurDAG->ReplaceAllUsesOfValueWith(SDValue(LdHi, 1), NewLoadHi.getValue(1));
361     return true;
362   }
363 
364   // build_vector (load ptr), hi -> load_d16_lo ptr, hi
365   // build_vector (zextload ptr from i8), hi -> load_d16_lo_u8 ptr, hi
366   // build_vector (sextload ptr from i8), hi -> load_d16_lo_i8 ptr, hi
367   LoadSDNode *LdLo = dyn_cast<LoadSDNode>(stripBitcast(Lo));
368   if (LdLo && Lo.hasOneUse()) {
369     SDValue TiedIn = getHi16Elt(Hi);
370     if (!TiedIn || LdLo->isPredecessorOf(TiedIn.getNode()))
371       return false;
372 
373     SDVTList VTList = CurDAG->getVTList(VT, MVT::Other);
374     unsigned LoadOp = AMDGPUISD::LOAD_D16_LO;
375     if (LdLo->getMemoryVT() == MVT::i8) {
376       LoadOp = LdLo->getExtensionType() == ISD::SEXTLOAD ?
377         AMDGPUISD::LOAD_D16_LO_I8 : AMDGPUISD::LOAD_D16_LO_U8;
378     } else {
379       assert(LdLo->getMemoryVT() == MVT::i16);
380     }
381 
382     TiedIn = CurDAG->getNode(ISD::BITCAST, SDLoc(N), VT, TiedIn);
383 
384     SDValue Ops[] = {
385       LdLo->getChain(), LdLo->getBasePtr(), TiedIn
386     };
387 
388     SDValue NewLoadLo =
389       CurDAG->getMemIntrinsicNode(LoadOp, SDLoc(LdLo), VTList,
390                                   Ops, LdLo->getMemoryVT(),
391                                   LdLo->getMemOperand());
392 
393     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), NewLoadLo);
394     CurDAG->ReplaceAllUsesOfValueWith(SDValue(LdLo, 1), NewLoadLo.getValue(1));
395     return true;
396   }
397 
398   return false;
399 }
400 
401 void AMDGPUDAGToDAGISel::PreprocessISelDAG() {
402   if (!Subtarget->d16PreservesUnusedBits())
403     return;
404 
405   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
406 
407   bool MadeChange = false;
408   while (Position != CurDAG->allnodes_begin()) {
409     SDNode *N = &*--Position;
410     if (N->use_empty())
411       continue;
412 
413     switch (N->getOpcode()) {
414     case ISD::BUILD_VECTOR:
415       MadeChange |= matchLoadD16FromBuildVector(N);
416       break;
417     default:
418       break;
419     }
420   }
421 
422   if (MadeChange) {
423     CurDAG->RemoveDeadNodes();
424     LLVM_DEBUG(dbgs() << "After PreProcess:\n";
425                CurDAG->dump(););
426   }
427 }
428 
429 bool AMDGPUDAGToDAGISel::isNoNanSrc(SDValue N) const {
430   if (TM.Options.NoNaNsFPMath)
431     return true;
432 
433   // TODO: Move into isKnownNeverNaN
434   if (N->getFlags().isDefined())
435     return N->getFlags().hasNoNaNs();
436 
437   return CurDAG->isKnownNeverNaN(N);
438 }
439 
440 bool AMDGPUDAGToDAGISel::isInlineImmediate(const SDNode *N) const {
441   const SIInstrInfo *TII = Subtarget->getInstrInfo();
442 
443   if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N))
444     return TII->isInlineConstant(C->getAPIntValue());
445 
446   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N))
447     return TII->isInlineConstant(C->getValueAPF().bitcastToAPInt());
448 
449   return false;
450 }
451 
452 /// Determine the register class for \p OpNo
453 /// \returns The register class of the virtual register that will be used for
454 /// the given operand number \OpNo or NULL if the register class cannot be
455 /// determined.
456 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
457                                                           unsigned OpNo) const {
458   if (!N->isMachineOpcode()) {
459     if (N->getOpcode() == ISD::CopyToReg) {
460       unsigned Reg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
461       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
462         MachineRegisterInfo &MRI = CurDAG->getMachineFunction().getRegInfo();
463         return MRI.getRegClass(Reg);
464       }
465 
466       const SIRegisterInfo *TRI
467         = static_cast<const GCNSubtarget *>(Subtarget)->getRegisterInfo();
468       return TRI->getPhysRegClass(Reg);
469     }
470 
471     return nullptr;
472   }
473 
474   switch (N->getMachineOpcode()) {
475   default: {
476     const MCInstrDesc &Desc =
477         Subtarget->getInstrInfo()->get(N->getMachineOpcode());
478     unsigned OpIdx = Desc.getNumDefs() + OpNo;
479     if (OpIdx >= Desc.getNumOperands())
480       return nullptr;
481     int RegClass = Desc.OpInfo[OpIdx].RegClass;
482     if (RegClass == -1)
483       return nullptr;
484 
485     return Subtarget->getRegisterInfo()->getRegClass(RegClass);
486   }
487   case AMDGPU::REG_SEQUENCE: {
488     unsigned RCID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
489     const TargetRegisterClass *SuperRC =
490         Subtarget->getRegisterInfo()->getRegClass(RCID);
491 
492     SDValue SubRegOp = N->getOperand(OpNo + 1);
493     unsigned SubRegIdx = cast<ConstantSDNode>(SubRegOp)->getZExtValue();
494     return Subtarget->getRegisterInfo()->getSubClassWithSubReg(SuperRC,
495                                                               SubRegIdx);
496   }
497   }
498 }
499 
500 SDNode *AMDGPUDAGToDAGISel::glueCopyToM0(SDNode *N, SDValue Val) const {
501   const SITargetLowering& Lowering =
502     *static_cast<const SITargetLowering*>(getTargetLowering());
503 
504   // Write max value to m0 before each load operation
505 
506   assert(N->getOperand(0).getValueType() == MVT::Other && "Expected chain");
507 
508   SDValue M0 = Lowering.copyToM0(*CurDAG, N->getOperand(0), SDLoc(N),
509                                  Val);
510 
511   SDValue Glue = M0.getValue(1);
512 
513   SmallVector <SDValue, 8> Ops;
514   Ops.push_back(M0); // Replace the chain.
515   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
516     Ops.push_back(N->getOperand(i));
517 
518   Ops.push_back(Glue);
519   return CurDAG->MorphNodeTo(N, N->getOpcode(), N->getVTList(), Ops);
520 }
521 
522 SDNode *AMDGPUDAGToDAGISel::glueCopyToM0LDSInit(SDNode *N) const {
523   if (cast<MemSDNode>(N)->getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS ||
524       !Subtarget->ldsRequiresM0Init())
525     return N;
526   return glueCopyToM0(N, CurDAG->getTargetConstant(-1, SDLoc(N), MVT::i32));
527 }
528 
529 MachineSDNode *AMDGPUDAGToDAGISel::buildSMovImm64(SDLoc &DL, uint64_t Imm,
530                                                   EVT VT) const {
531   SDNode *Lo = CurDAG->getMachineNode(
532       AMDGPU::S_MOV_B32, DL, MVT::i32,
533       CurDAG->getConstant(Imm & 0xFFFFFFFF, DL, MVT::i32));
534   SDNode *Hi =
535       CurDAG->getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32,
536                              CurDAG->getConstant(Imm >> 32, DL, MVT::i32));
537   const SDValue Ops[] = {
538       CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
539       SDValue(Lo, 0), CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
540       SDValue(Hi, 0), CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32)};
541 
542   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL, VT, Ops);
543 }
544 
545 static unsigned selectSGPRVectorRegClassID(unsigned NumVectorElts) {
546   switch (NumVectorElts) {
547   case 1:
548     return AMDGPU::SReg_32_XM0RegClassID;
549   case 2:
550     return AMDGPU::SReg_64RegClassID;
551   case 3:
552     return AMDGPU::SGPR_96RegClassID;
553   case 4:
554     return AMDGPU::SReg_128RegClassID;
555   case 5:
556     return AMDGPU::SGPR_160RegClassID;
557   case 8:
558     return AMDGPU::SReg_256RegClassID;
559   case 16:
560     return AMDGPU::SReg_512RegClassID;
561   }
562 
563   llvm_unreachable("invalid vector size");
564 }
565 
566 static bool getConstantValue(SDValue N, uint32_t &Out) {
567   if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N)) {
568     Out = C->getAPIntValue().getZExtValue();
569     return true;
570   }
571 
572   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N)) {
573     Out = C->getValueAPF().bitcastToAPInt().getZExtValue();
574     return true;
575   }
576 
577   return false;
578 }
579 
580 void AMDGPUDAGToDAGISel::SelectBuildVector(SDNode *N, unsigned RegClassID) {
581   EVT VT = N->getValueType(0);
582   unsigned NumVectorElts = VT.getVectorNumElements();
583   EVT EltVT = VT.getVectorElementType();
584   SDLoc DL(N);
585   SDValue RegClass = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
586 
587   if (NumVectorElts == 1) {
588     CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, EltVT, N->getOperand(0),
589                          RegClass);
590     return;
591   }
592 
593   assert(NumVectorElts <= 16 && "Vectors with more than 16 elements not "
594                                   "supported yet");
595   // 16 = Max Num Vector Elements
596   // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
597   // 1 = Vector Register Class
598   SmallVector<SDValue, 16 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
599 
600   RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, DL, MVT::i32);
601   bool IsRegSeq = true;
602   unsigned NOps = N->getNumOperands();
603   for (unsigned i = 0; i < NOps; i++) {
604     // XXX: Why is this here?
605     if (isa<RegisterSDNode>(N->getOperand(i))) {
606       IsRegSeq = false;
607       break;
608     }
609     unsigned Sub = AMDGPURegisterInfo::getSubRegFromChannel(i);
610     RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
611     RegSeqArgs[1 + (2 * i) + 1] = CurDAG->getTargetConstant(Sub, DL, MVT::i32);
612   }
613   if (NOps != NumVectorElts) {
614     // Fill in the missing undef elements if this was a scalar_to_vector.
615     assert(N->getOpcode() == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
616     MachineSDNode *ImpDef = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
617                                                    DL, EltVT);
618     for (unsigned i = NOps; i < NumVectorElts; ++i) {
619       unsigned Sub = AMDGPURegisterInfo::getSubRegFromChannel(i);
620       RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
621       RegSeqArgs[1 + (2 * i) + 1] =
622           CurDAG->getTargetConstant(Sub, DL, MVT::i32);
623     }
624   }
625 
626   if (!IsRegSeq)
627     SelectCode(N);
628   CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(), RegSeqArgs);
629 }
630 
631 void AMDGPUDAGToDAGISel::Select(SDNode *N) {
632   unsigned int Opc = N->getOpcode();
633   if (N->isMachineOpcode()) {
634     N->setNodeId(-1);
635     return;   // Already selected.
636   }
637 
638   if (isa<AtomicSDNode>(N) ||
639       (Opc == AMDGPUISD::ATOMIC_INC || Opc == AMDGPUISD::ATOMIC_DEC ||
640        Opc == ISD::ATOMIC_LOAD_FADD ||
641        Opc == AMDGPUISD::ATOMIC_LOAD_FMIN ||
642        Opc == AMDGPUISD::ATOMIC_LOAD_FMAX))
643     N = glueCopyToM0LDSInit(N);
644 
645   switch (Opc) {
646   default:
647     break;
648   // We are selecting i64 ADD here instead of custom lower it during
649   // DAG legalization, so we can fold some i64 ADDs used for address
650   // calculation into the LOAD and STORE instructions.
651   case ISD::ADDC:
652   case ISD::ADDE:
653   case ISD::SUBC:
654   case ISD::SUBE: {
655     if (N->getValueType(0) != MVT::i64)
656       break;
657 
658     SelectADD_SUB_I64(N);
659     return;
660   }
661   case ISD::ADDCARRY:
662   case ISD::SUBCARRY:
663     if (N->getValueType(0) != MVT::i32)
664       break;
665 
666     SelectAddcSubb(N);
667     return;
668   case ISD::UADDO:
669   case ISD::USUBO: {
670     SelectUADDO_USUBO(N);
671     return;
672   }
673   case AMDGPUISD::FMUL_W_CHAIN: {
674     SelectFMUL_W_CHAIN(N);
675     return;
676   }
677   case AMDGPUISD::FMA_W_CHAIN: {
678     SelectFMA_W_CHAIN(N);
679     return;
680   }
681 
682   case ISD::SCALAR_TO_VECTOR:
683   case ISD::BUILD_VECTOR: {
684     EVT VT = N->getValueType(0);
685     unsigned NumVectorElts = VT.getVectorNumElements();
686     if (VT.getScalarSizeInBits() == 16) {
687       if (Opc == ISD::BUILD_VECTOR && NumVectorElts == 2) {
688         uint32_t LHSVal, RHSVal;
689         if (getConstantValue(N->getOperand(0), LHSVal) &&
690             getConstantValue(N->getOperand(1), RHSVal)) {
691           uint32_t K = LHSVal | (RHSVal << 16);
692           CurDAG->SelectNodeTo(N, AMDGPU::S_MOV_B32, VT,
693                                CurDAG->getTargetConstant(K, SDLoc(N), MVT::i32));
694           return;
695         }
696       }
697 
698       break;
699     }
700 
701     assert(VT.getVectorElementType().bitsEq(MVT::i32));
702     unsigned RegClassID = selectSGPRVectorRegClassID(NumVectorElts);
703     SelectBuildVector(N, RegClassID);
704     return;
705   }
706   case ISD::BUILD_PAIR: {
707     SDValue RC, SubReg0, SubReg1;
708     SDLoc DL(N);
709     if (N->getValueType(0) == MVT::i128) {
710       RC = CurDAG->getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32);
711       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32);
712       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32);
713     } else if (N->getValueType(0) == MVT::i64) {
714       RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32);
715       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
716       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
717     } else {
718       llvm_unreachable("Unhandled value type for BUILD_PAIR");
719     }
720     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
721                             N->getOperand(1), SubReg1 };
722     ReplaceNode(N, CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL,
723                                           N->getValueType(0), Ops));
724     return;
725   }
726 
727   case ISD::Constant:
728   case ISD::ConstantFP: {
729     if (N->getValueType(0).getSizeInBits() != 64 || isInlineImmediate(N))
730       break;
731 
732     uint64_t Imm;
733     if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(N))
734       Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
735     else {
736       ConstantSDNode *C = cast<ConstantSDNode>(N);
737       Imm = C->getZExtValue();
738     }
739 
740     SDLoc DL(N);
741     ReplaceNode(N, buildSMovImm64(DL, Imm, N->getValueType(0)));
742     return;
743   }
744   case ISD::LOAD:
745   case ISD::STORE:
746   case ISD::ATOMIC_LOAD:
747   case ISD::ATOMIC_STORE: {
748     N = glueCopyToM0LDSInit(N);
749     break;
750   }
751 
752   case AMDGPUISD::BFE_I32:
753   case AMDGPUISD::BFE_U32: {
754     // There is a scalar version available, but unlike the vector version which
755     // has a separate operand for the offset and width, the scalar version packs
756     // the width and offset into a single operand. Try to move to the scalar
757     // version if the offsets are constant, so that we can try to keep extended
758     // loads of kernel arguments in SGPRs.
759 
760     // TODO: Technically we could try to pattern match scalar bitshifts of
761     // dynamic values, but it's probably not useful.
762     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
763     if (!Offset)
764       break;
765 
766     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
767     if (!Width)
768       break;
769 
770     bool Signed = Opc == AMDGPUISD::BFE_I32;
771 
772     uint32_t OffsetVal = Offset->getZExtValue();
773     uint32_t WidthVal = Width->getZExtValue();
774 
775     ReplaceNode(N, getS_BFE(Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32,
776                             SDLoc(N), N->getOperand(0), OffsetVal, WidthVal));
777     return;
778   }
779   case AMDGPUISD::DIV_SCALE: {
780     SelectDIV_SCALE(N);
781     return;
782   }
783   case AMDGPUISD::DIV_FMAS: {
784     SelectDIV_FMAS(N);
785     return;
786   }
787   case AMDGPUISD::MAD_I64_I32:
788   case AMDGPUISD::MAD_U64_U32: {
789     SelectMAD_64_32(N);
790     return;
791   }
792   case ISD::CopyToReg: {
793     const SITargetLowering& Lowering =
794       *static_cast<const SITargetLowering*>(getTargetLowering());
795     N = Lowering.legalizeTargetIndependentNode(N, *CurDAG);
796     break;
797   }
798   case ISD::AND:
799   case ISD::SRL:
800   case ISD::SRA:
801   case ISD::SIGN_EXTEND_INREG:
802     if (N->getValueType(0) != MVT::i32)
803       break;
804 
805     SelectS_BFE(N);
806     return;
807   case ISD::BRCOND:
808     SelectBRCOND(N);
809     return;
810   case ISD::FMAD:
811   case ISD::FMA:
812     SelectFMAD_FMA(N);
813     return;
814   case AMDGPUISD::ATOMIC_CMP_SWAP:
815     SelectATOMIC_CMP_SWAP(N);
816     return;
817   case AMDGPUISD::CVT_PKRTZ_F16_F32:
818   case AMDGPUISD::CVT_PKNORM_I16_F32:
819   case AMDGPUISD::CVT_PKNORM_U16_F32:
820   case AMDGPUISD::CVT_PK_U16_U32:
821   case AMDGPUISD::CVT_PK_I16_I32: {
822     // Hack around using a legal type if f16 is illegal.
823     if (N->getValueType(0) == MVT::i32) {
824       MVT NewVT = Opc == AMDGPUISD::CVT_PKRTZ_F16_F32 ? MVT::v2f16 : MVT::v2i16;
825       N = CurDAG->MorphNodeTo(N, N->getOpcode(), CurDAG->getVTList(NewVT),
826                               { N->getOperand(0), N->getOperand(1) });
827       SelectCode(N);
828       return;
829     }
830 
831     break;
832   }
833   case ISD::INTRINSIC_W_CHAIN: {
834     SelectINTRINSIC_W_CHAIN(N);
835     return;
836   }
837   case ISD::INTRINSIC_VOID: {
838     SelectINTRINSIC_VOID(N);
839     return;
840   }
841   }
842 
843   SelectCode(N);
844 }
845 
846 bool AMDGPUDAGToDAGISel::isUniformBr(const SDNode *N) const {
847   const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
848   const Instruction *Term = BB->getTerminator();
849   return Term->getMetadata("amdgpu.uniform") ||
850          Term->getMetadata("structurizecfg.uniform");
851 }
852 
853 StringRef AMDGPUDAGToDAGISel::getPassName() const {
854   return "AMDGPU DAG->DAG Pattern Instruction Selection";
855 }
856 
857 //===----------------------------------------------------------------------===//
858 // Complex Patterns
859 //===----------------------------------------------------------------------===//
860 
861 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
862                                             SDValue &Offset) {
863   return false;
864 }
865 
866 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
867                                             SDValue &Offset) {
868   ConstantSDNode *C;
869   SDLoc DL(Addr);
870 
871   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
872     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
873     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
874   } else if ((Addr.getOpcode() == AMDGPUISD::DWORDADDR) &&
875              (C = dyn_cast<ConstantSDNode>(Addr.getOperand(0)))) {
876     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
877     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
878   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
879             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
880     Base = Addr.getOperand(0);
881     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
882   } else {
883     Base = Addr;
884     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
885   }
886 
887   return true;
888 }
889 
890 // FIXME: Should only handle addcarry/subcarry
891 void AMDGPUDAGToDAGISel::SelectADD_SUB_I64(SDNode *N) {
892   SDLoc DL(N);
893   SDValue LHS = N->getOperand(0);
894   SDValue RHS = N->getOperand(1);
895 
896   unsigned Opcode = N->getOpcode();
897   bool ConsumeCarry = (Opcode == ISD::ADDE || Opcode == ISD::SUBE);
898   bool ProduceCarry =
899       ConsumeCarry || Opcode == ISD::ADDC || Opcode == ISD::SUBC;
900   bool IsAdd = Opcode == ISD::ADD || Opcode == ISD::ADDC || Opcode == ISD::ADDE;
901 
902   SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, DL, MVT::i32);
903   SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, DL, MVT::i32);
904 
905   SDNode *Lo0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
906                                        DL, MVT::i32, LHS, Sub0);
907   SDNode *Hi0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
908                                        DL, MVT::i32, LHS, Sub1);
909 
910   SDNode *Lo1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
911                                        DL, MVT::i32, RHS, Sub0);
912   SDNode *Hi1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
913                                        DL, MVT::i32, RHS, Sub1);
914 
915   SDVTList VTList = CurDAG->getVTList(MVT::i32, MVT::Glue);
916 
917   unsigned Opc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
918   unsigned CarryOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
919 
920   SDNode *AddLo;
921   if (!ConsumeCarry) {
922     SDValue Args[] = { SDValue(Lo0, 0), SDValue(Lo1, 0) };
923     AddLo = CurDAG->getMachineNode(Opc, DL, VTList, Args);
924   } else {
925     SDValue Args[] = { SDValue(Lo0, 0), SDValue(Lo1, 0), N->getOperand(2) };
926     AddLo = CurDAG->getMachineNode(CarryOpc, DL, VTList, Args);
927   }
928   SDValue AddHiArgs[] = {
929     SDValue(Hi0, 0),
930     SDValue(Hi1, 0),
931     SDValue(AddLo, 1)
932   };
933   SDNode *AddHi = CurDAG->getMachineNode(CarryOpc, DL, VTList, AddHiArgs);
934 
935   SDValue RegSequenceArgs[] = {
936     CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, DL, MVT::i32),
937     SDValue(AddLo,0),
938     Sub0,
939     SDValue(AddHi,0),
940     Sub1,
941   };
942   SDNode *RegSequence = CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, DL,
943                                                MVT::i64, RegSequenceArgs);
944 
945   if (ProduceCarry) {
946     // Replace the carry-use
947     ReplaceUses(SDValue(N, 1), SDValue(AddHi, 1));
948   }
949 
950   // Replace the remaining uses.
951   ReplaceNode(N, RegSequence);
952 }
953 
954 void AMDGPUDAGToDAGISel::SelectAddcSubb(SDNode *N) {
955   SDLoc DL(N);
956   SDValue LHS = N->getOperand(0);
957   SDValue RHS = N->getOperand(1);
958   SDValue CI = N->getOperand(2);
959 
960   unsigned Opc = N->getOpcode() == ISD::ADDCARRY ? AMDGPU::V_ADDC_U32_e64
961                                                  : AMDGPU::V_SUBB_U32_e64;
962   CurDAG->SelectNodeTo(
963       N, Opc, N->getVTList(),
964       {LHS, RHS, CI, CurDAG->getTargetConstant(0, {}, MVT::i1) /*clamp bit*/});
965 }
966 
967 void AMDGPUDAGToDAGISel::SelectUADDO_USUBO(SDNode *N) {
968   // The name of the opcodes are misleading. v_add_i32/v_sub_i32 have unsigned
969   // carry out despite the _i32 name. These were renamed in VI to _U32.
970   // FIXME: We should probably rename the opcodes here.
971   unsigned Opc = N->getOpcode() == ISD::UADDO ?
972     AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
973 
974   CurDAG->SelectNodeTo(
975       N, Opc, N->getVTList(),
976       {N->getOperand(0), N->getOperand(1),
977        CurDAG->getTargetConstant(0, {}, MVT::i1) /*clamp bit*/});
978 }
979 
980 void AMDGPUDAGToDAGISel::SelectFMA_W_CHAIN(SDNode *N) {
981   SDLoc SL(N);
982   //  src0_modifiers, src0,  src1_modifiers, src1, src2_modifiers, src2, clamp, omod
983   SDValue Ops[10];
984 
985   SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[6], Ops[7]);
986   SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
987   SelectVOP3Mods(N->getOperand(3), Ops[5], Ops[4]);
988   Ops[8] = N->getOperand(0);
989   Ops[9] = N->getOperand(4);
990 
991   CurDAG->SelectNodeTo(N, AMDGPU::V_FMA_F32, N->getVTList(), Ops);
992 }
993 
994 void AMDGPUDAGToDAGISel::SelectFMUL_W_CHAIN(SDNode *N) {
995   SDLoc SL(N);
996   //    src0_modifiers, src0,  src1_modifiers, src1, clamp, omod
997   SDValue Ops[8];
998 
999   SelectVOP3Mods0(N->getOperand(1), Ops[1], Ops[0], Ops[4], Ops[5]);
1000   SelectVOP3Mods(N->getOperand(2), Ops[3], Ops[2]);
1001   Ops[6] = N->getOperand(0);
1002   Ops[7] = N->getOperand(3);
1003 
1004   CurDAG->SelectNodeTo(N, AMDGPU::V_MUL_F32_e64, N->getVTList(), Ops);
1005 }
1006 
1007 // We need to handle this here because tablegen doesn't support matching
1008 // instructions with multiple outputs.
1009 void AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
1010   SDLoc SL(N);
1011   EVT VT = N->getValueType(0);
1012 
1013   assert(VT == MVT::f32 || VT == MVT::f64);
1014 
1015   unsigned Opc
1016     = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64 : AMDGPU::V_DIV_SCALE_F32;
1017 
1018   SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) };
1019   CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
1020 }
1021 
1022 void AMDGPUDAGToDAGISel::SelectDIV_FMAS(SDNode *N) {
1023   const GCNSubtarget *ST = static_cast<const GCNSubtarget *>(Subtarget);
1024   const SIRegisterInfo *TRI = ST->getRegisterInfo();
1025 
1026   SDLoc SL(N);
1027   EVT VT = N->getValueType(0);
1028 
1029   assert(VT == MVT::f32 || VT == MVT::f64);
1030 
1031   unsigned Opc
1032     = (VT == MVT::f64) ? AMDGPU::V_DIV_FMAS_F64 : AMDGPU::V_DIV_FMAS_F32;
1033 
1034   SDValue CarryIn = N->getOperand(3);
1035   // V_DIV_FMAS implicitly reads VCC.
1036   SDValue VCC = CurDAG->getCopyToReg(CurDAG->getEntryNode(), SL,
1037                                      TRI->getVCC(), CarryIn, SDValue());
1038 
1039   SDValue Ops[10];
1040 
1041   SelectVOP3Mods0(N->getOperand(0), Ops[1], Ops[0], Ops[6], Ops[7]);
1042   SelectVOP3Mods(N->getOperand(1), Ops[3], Ops[2]);
1043   SelectVOP3Mods(N->getOperand(2), Ops[5], Ops[4]);
1044 
1045   Ops[8] = VCC;
1046   Ops[9] = VCC.getValue(1);
1047 
1048   CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
1049 }
1050 
1051 // We need to handle this here because tablegen doesn't support matching
1052 // instructions with multiple outputs.
1053 void AMDGPUDAGToDAGISel::SelectMAD_64_32(SDNode *N) {
1054   SDLoc SL(N);
1055   bool Signed = N->getOpcode() == AMDGPUISD::MAD_I64_I32;
1056   unsigned Opc = Signed ? AMDGPU::V_MAD_I64_I32 : AMDGPU::V_MAD_U64_U32;
1057 
1058   SDValue Clamp = CurDAG->getTargetConstant(0, SL, MVT::i1);
1059   SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
1060                     Clamp };
1061   CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
1062 }
1063 
1064 bool AMDGPUDAGToDAGISel::isDSOffsetLegal(SDValue Base, unsigned Offset,
1065                                          unsigned OffsetBits) const {
1066   if ((OffsetBits == 16 && !isUInt<16>(Offset)) ||
1067       (OffsetBits == 8 && !isUInt<8>(Offset)))
1068     return false;
1069 
1070   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS ||
1071       Subtarget->unsafeDSOffsetFoldingEnabled())
1072     return true;
1073 
1074   // On Southern Islands instruction with a negative base value and an offset
1075   // don't seem to work.
1076   return CurDAG->SignBitIsZero(Base);
1077 }
1078 
1079 bool AMDGPUDAGToDAGISel::SelectDS1Addr1Offset(SDValue Addr, SDValue &Base,
1080                                               SDValue &Offset) const {
1081   SDLoc DL(Addr);
1082   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1083     SDValue N0 = Addr.getOperand(0);
1084     SDValue N1 = Addr.getOperand(1);
1085     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1086     if (isDSOffsetLegal(N0, C1->getSExtValue(), 16)) {
1087       // (add n0, c0)
1088       Base = N0;
1089       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1090       return true;
1091     }
1092   } else if (Addr.getOpcode() == ISD::SUB) {
1093     // sub C, x -> add (sub 0, x), C
1094     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
1095       int64_t ByteOffset = C->getSExtValue();
1096       if (isUInt<16>(ByteOffset)) {
1097         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1098 
1099         // XXX - This is kind of hacky. Create a dummy sub node so we can check
1100         // the known bits in isDSOffsetLegal. We need to emit the selected node
1101         // here, so this is thrown away.
1102         SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
1103                                       Zero, Addr.getOperand(1));
1104 
1105         if (isDSOffsetLegal(Sub, ByteOffset, 16)) {
1106           SmallVector<SDValue, 3> Opnds;
1107           Opnds.push_back(Zero);
1108           Opnds.push_back(Addr.getOperand(1));
1109 
1110           // FIXME: Select to VOP3 version for with-carry.
1111           unsigned SubOp = AMDGPU::V_SUB_I32_e32;
1112           if (Subtarget->hasAddNoCarry()) {
1113             SubOp = AMDGPU::V_SUB_U32_e64;
1114             Opnds.push_back(
1115                 CurDAG->getTargetConstant(0, {}, MVT::i1)); // clamp bit
1116           }
1117 
1118           MachineSDNode *MachineSub =
1119               CurDAG->getMachineNode(SubOp, DL, MVT::i32, Opnds);
1120 
1121           Base = SDValue(MachineSub, 0);
1122           Offset = CurDAG->getTargetConstant(ByteOffset, DL, MVT::i16);
1123           return true;
1124         }
1125       }
1126     }
1127   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1128     // If we have a constant address, prefer to put the constant into the
1129     // offset. This can save moves to load the constant address since multiple
1130     // operations can share the zero base address register, and enables merging
1131     // into read2 / write2 instructions.
1132 
1133     SDLoc DL(Addr);
1134 
1135     if (isUInt<16>(CAddr->getZExtValue())) {
1136       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1137       MachineSDNode *MovZero = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
1138                                  DL, MVT::i32, Zero);
1139       Base = SDValue(MovZero, 0);
1140       Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i16);
1141       return true;
1142     }
1143   }
1144 
1145   // default case
1146   Base = Addr;
1147   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i16);
1148   return true;
1149 }
1150 
1151 // TODO: If offset is too big, put low 16-bit into offset.
1152 bool AMDGPUDAGToDAGISel::SelectDS64Bit4ByteAligned(SDValue Addr, SDValue &Base,
1153                                                    SDValue &Offset0,
1154                                                    SDValue &Offset1) const {
1155   SDLoc DL(Addr);
1156 
1157   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1158     SDValue N0 = Addr.getOperand(0);
1159     SDValue N1 = Addr.getOperand(1);
1160     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1161     unsigned DWordOffset0 = C1->getZExtValue() / 4;
1162     unsigned DWordOffset1 = DWordOffset0 + 1;
1163     // (add n0, c0)
1164     if (isDSOffsetLegal(N0, DWordOffset1, 8)) {
1165       Base = N0;
1166       Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
1167       Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
1168       return true;
1169     }
1170   } else if (Addr.getOpcode() == ISD::SUB) {
1171     // sub C, x -> add (sub 0, x), C
1172     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Addr.getOperand(0))) {
1173       unsigned DWordOffset0 = C->getZExtValue() / 4;
1174       unsigned DWordOffset1 = DWordOffset0 + 1;
1175 
1176       if (isUInt<8>(DWordOffset0)) {
1177         SDLoc DL(Addr);
1178         SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1179 
1180         // XXX - This is kind of hacky. Create a dummy sub node so we can check
1181         // the known bits in isDSOffsetLegal. We need to emit the selected node
1182         // here, so this is thrown away.
1183         SDValue Sub = CurDAG->getNode(ISD::SUB, DL, MVT::i32,
1184                                       Zero, Addr.getOperand(1));
1185 
1186         if (isDSOffsetLegal(Sub, DWordOffset1, 8)) {
1187           SmallVector<SDValue, 3> Opnds;
1188           Opnds.push_back(Zero);
1189           Opnds.push_back(Addr.getOperand(1));
1190           unsigned SubOp = AMDGPU::V_SUB_I32_e32;
1191           if (Subtarget->hasAddNoCarry()) {
1192             SubOp = AMDGPU::V_SUB_U32_e64;
1193             Opnds.push_back(
1194                 CurDAG->getTargetConstant(0, {}, MVT::i1)); // clamp bit
1195           }
1196 
1197           MachineSDNode *MachineSub
1198             = CurDAG->getMachineNode(SubOp, DL, MVT::i32, Opnds);
1199 
1200           Base = SDValue(MachineSub, 0);
1201           Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
1202           Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
1203           return true;
1204         }
1205       }
1206     }
1207   } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1208     unsigned DWordOffset0 = CAddr->getZExtValue() / 4;
1209     unsigned DWordOffset1 = DWordOffset0 + 1;
1210     assert(4 * DWordOffset0 == CAddr->getZExtValue());
1211 
1212     if (isUInt<8>(DWordOffset0) && isUInt<8>(DWordOffset1)) {
1213       SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1214       MachineSDNode *MovZero
1215         = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
1216                                  DL, MVT::i32, Zero);
1217       Base = SDValue(MovZero, 0);
1218       Offset0 = CurDAG->getTargetConstant(DWordOffset0, DL, MVT::i8);
1219       Offset1 = CurDAG->getTargetConstant(DWordOffset1, DL, MVT::i8);
1220       return true;
1221     }
1222   }
1223 
1224   // default case
1225 
1226   Base = Addr;
1227   Offset0 = CurDAG->getTargetConstant(0, DL, MVT::i8);
1228   Offset1 = CurDAG->getTargetConstant(1, DL, MVT::i8);
1229   return true;
1230 }
1231 
1232 bool AMDGPUDAGToDAGISel::SelectMUBUF(SDValue Addr, SDValue &Ptr,
1233                                      SDValue &VAddr, SDValue &SOffset,
1234                                      SDValue &Offset, SDValue &Offen,
1235                                      SDValue &Idxen, SDValue &Addr64,
1236                                      SDValue &GLC, SDValue &SLC,
1237                                      SDValue &TFE, SDValue &DLC) const {
1238   // Subtarget prefers to use flat instruction
1239   if (Subtarget->useFlatForGlobal())
1240     return false;
1241 
1242   SDLoc DL(Addr);
1243 
1244   if (!GLC.getNode())
1245     GLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
1246   if (!SLC.getNode())
1247     SLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
1248   TFE = CurDAG->getTargetConstant(0, DL, MVT::i1);
1249   DLC = CurDAG->getTargetConstant(0, DL, MVT::i1);
1250 
1251   Idxen = CurDAG->getTargetConstant(0, DL, MVT::i1);
1252   Offen = CurDAG->getTargetConstant(0, DL, MVT::i1);
1253   Addr64 = CurDAG->getTargetConstant(0, DL, MVT::i1);
1254   SOffset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1255 
1256   ConstantSDNode *C1 = nullptr;
1257   SDValue N0 = Addr;
1258   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1259     C1 = cast<ConstantSDNode>(Addr.getOperand(1));
1260     if (isUInt<32>(C1->getZExtValue()))
1261       N0 = Addr.getOperand(0);
1262     else
1263       C1 = nullptr;
1264   }
1265 
1266   if (N0.getOpcode() == ISD::ADD) {
1267     // (add N2, N3) -> addr64, or
1268     // (add (add N2, N3), C1) -> addr64
1269     SDValue N2 = N0.getOperand(0);
1270     SDValue N3 = N0.getOperand(1);
1271     Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1272 
1273     if (N2->isDivergent()) {
1274       if (N3->isDivergent()) {
1275         // Both N2 and N3 are divergent. Use N0 (the result of the add) as the
1276         // addr64, and construct the resource from a 0 address.
1277         Ptr = SDValue(buildSMovImm64(DL, 0, MVT::v2i32), 0);
1278         VAddr = N0;
1279       } else {
1280         // N2 is divergent, N3 is not.
1281         Ptr = N3;
1282         VAddr = N2;
1283       }
1284     } else {
1285       // N2 is not divergent.
1286       Ptr = N2;
1287       VAddr = N3;
1288     }
1289     Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1290   } else if (N0->isDivergent()) {
1291     // N0 is divergent. Use it as the addr64, and construct the resource from a
1292     // 0 address.
1293     Ptr = SDValue(buildSMovImm64(DL, 0, MVT::v2i32), 0);
1294     VAddr = N0;
1295     Addr64 = CurDAG->getTargetConstant(1, DL, MVT::i1);
1296   } else {
1297     // N0 -> offset, or
1298     // (N0 + C1) -> offset
1299     VAddr = CurDAG->getTargetConstant(0, DL, MVT::i32);
1300     Ptr = N0;
1301   }
1302 
1303   if (!C1) {
1304     // No offset.
1305     Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1306     return true;
1307   }
1308 
1309   if (SIInstrInfo::isLegalMUBUFImmOffset(C1->getZExtValue())) {
1310     // Legal offset for instruction.
1311     Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1312     return true;
1313   }
1314 
1315   // Illegal offset, store it in soffset.
1316   Offset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1317   SOffset =
1318       SDValue(CurDAG->getMachineNode(
1319                   AMDGPU::S_MOV_B32, DL, MVT::i32,
1320                   CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32)),
1321               0);
1322   return true;
1323 }
1324 
1325 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1326                                            SDValue &VAddr, SDValue &SOffset,
1327                                            SDValue &Offset, SDValue &GLC,
1328                                            SDValue &SLC, SDValue &TFE,
1329                                            SDValue &DLC) const {
1330   SDValue Ptr, Offen, Idxen, Addr64;
1331 
1332   // addr64 bit was removed for volcanic islands.
1333   if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1334     return false;
1335 
1336   if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
1337               GLC, SLC, TFE, DLC))
1338     return false;
1339 
1340   ConstantSDNode *C = cast<ConstantSDNode>(Addr64);
1341   if (C->getSExtValue()) {
1342     SDLoc DL(Addr);
1343 
1344     const SITargetLowering& Lowering =
1345       *static_cast<const SITargetLowering*>(getTargetLowering());
1346 
1347     SRsrc = SDValue(Lowering.wrapAddr64Rsrc(*CurDAG, DL, Ptr), 0);
1348     return true;
1349   }
1350 
1351   return false;
1352 }
1353 
1354 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1355                                            SDValue &VAddr, SDValue &SOffset,
1356                                            SDValue &Offset,
1357                                            SDValue &SLC) const {
1358   SLC = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i1);
1359   SDValue GLC, TFE, DLC;
1360 
1361   return SelectMUBUFAddr64(Addr, SRsrc, VAddr, SOffset, Offset, GLC, SLC, TFE, DLC);
1362 }
1363 
1364 static bool isStackPtrRelative(const MachinePointerInfo &PtrInfo) {
1365   auto PSV = PtrInfo.V.dyn_cast<const PseudoSourceValue *>();
1366   return PSV && PSV->isStack();
1367 }
1368 
1369 std::pair<SDValue, SDValue> AMDGPUDAGToDAGISel::foldFrameIndex(SDValue N) const {
1370   const MachineFunction &MF = CurDAG->getMachineFunction();
1371   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1372 
1373   if (auto FI = dyn_cast<FrameIndexSDNode>(N)) {
1374     SDValue TFI = CurDAG->getTargetFrameIndex(FI->getIndex(),
1375                                               FI->getValueType(0));
1376 
1377     // If we can resolve this to a frame index access, this will be relative to
1378     // either the stack or frame pointer SGPR.
1379     return std::make_pair(
1380         TFI, CurDAG->getRegister(Info->getStackPtrOffsetReg(), MVT::i32));
1381   }
1382 
1383   // If we don't know this private access is a local stack object, it needs to
1384   // be relative to the entry point's scratch wave offset register.
1385   return std::make_pair(N, CurDAG->getRegister(Info->getScratchWaveOffsetReg(),
1386                                                MVT::i32));
1387 }
1388 
1389 bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffen(SDNode *Parent,
1390                                                  SDValue Addr, SDValue &Rsrc,
1391                                                  SDValue &VAddr, SDValue &SOffset,
1392                                                  SDValue &ImmOffset) const {
1393 
1394   SDLoc DL(Addr);
1395   MachineFunction &MF = CurDAG->getMachineFunction();
1396   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1397 
1398   Rsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1399 
1400   if (ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr)) {
1401     unsigned Imm = CAddr->getZExtValue();
1402 
1403     SDValue HighBits = CurDAG->getTargetConstant(Imm & ~4095, DL, MVT::i32);
1404     MachineSDNode *MovHighBits = CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32,
1405                                                         DL, MVT::i32, HighBits);
1406     VAddr = SDValue(MovHighBits, 0);
1407 
1408     // In a call sequence, stores to the argument stack area are relative to the
1409     // stack pointer.
1410     const MachinePointerInfo &PtrInfo = cast<MemSDNode>(Parent)->getPointerInfo();
1411     unsigned SOffsetReg = isStackPtrRelative(PtrInfo) ?
1412       Info->getStackPtrOffsetReg() : Info->getScratchWaveOffsetReg();
1413 
1414     SOffset = CurDAG->getRegister(SOffsetReg, MVT::i32);
1415     ImmOffset = CurDAG->getTargetConstant(Imm & 4095, DL, MVT::i16);
1416     return true;
1417   }
1418 
1419   if (CurDAG->isBaseWithConstantOffset(Addr)) {
1420     // (add n0, c1)
1421 
1422     SDValue N0 = Addr.getOperand(0);
1423     SDValue N1 = Addr.getOperand(1);
1424 
1425     // Offsets in vaddr must be positive if range checking is enabled.
1426     //
1427     // The total computation of vaddr + soffset + offset must not overflow.  If
1428     // vaddr is negative, even if offset is 0 the sgpr offset add will end up
1429     // overflowing.
1430     //
1431     // Prior to gfx9, MUBUF instructions with the vaddr offset enabled would
1432     // always perform a range check. If a negative vaddr base index was used,
1433     // this would fail the range check. The overall address computation would
1434     // compute a valid address, but this doesn't happen due to the range
1435     // check. For out-of-bounds MUBUF loads, a 0 is returned.
1436     //
1437     // Therefore it should be safe to fold any VGPR offset on gfx9 into the
1438     // MUBUF vaddr, but not on older subtargets which can only do this if the
1439     // sign bit is known 0.
1440     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1441     if (SIInstrInfo::isLegalMUBUFImmOffset(C1->getZExtValue()) &&
1442         (!Subtarget->privateMemoryResourceIsRangeChecked() ||
1443          CurDAG->SignBitIsZero(N0))) {
1444       std::tie(VAddr, SOffset) = foldFrameIndex(N0);
1445       ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i16);
1446       return true;
1447     }
1448   }
1449 
1450   // (node)
1451   std::tie(VAddr, SOffset) = foldFrameIndex(Addr);
1452   ImmOffset = CurDAG->getTargetConstant(0, DL, MVT::i16);
1453   return true;
1454 }
1455 
1456 bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffset(SDNode *Parent,
1457                                                   SDValue Addr,
1458                                                   SDValue &SRsrc,
1459                                                   SDValue &SOffset,
1460                                                   SDValue &Offset) const {
1461   ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Addr);
1462   if (!CAddr || !SIInstrInfo::isLegalMUBUFImmOffset(CAddr->getZExtValue()))
1463     return false;
1464 
1465   SDLoc DL(Addr);
1466   MachineFunction &MF = CurDAG->getMachineFunction();
1467   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1468 
1469   SRsrc = CurDAG->getRegister(Info->getScratchRSrcReg(), MVT::v4i32);
1470 
1471   const MachinePointerInfo &PtrInfo = cast<MemSDNode>(Parent)->getPointerInfo();
1472   unsigned SOffsetReg = isStackPtrRelative(PtrInfo) ?
1473     Info->getStackPtrOffsetReg() : Info->getScratchWaveOffsetReg();
1474 
1475   // FIXME: Get from MachinePointerInfo? We should only be using the frame
1476   // offset if we know this is in a call sequence.
1477   SOffset = CurDAG->getRegister(SOffsetReg, MVT::i32);
1478 
1479   Offset = CurDAG->getTargetConstant(CAddr->getZExtValue(), DL, MVT::i16);
1480   return true;
1481 }
1482 
1483 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1484                                            SDValue &SOffset, SDValue &Offset,
1485                                            SDValue &GLC, SDValue &SLC,
1486                                            SDValue &TFE, SDValue &DLC) const {
1487   SDValue Ptr, VAddr, Offen, Idxen, Addr64;
1488   const SIInstrInfo *TII =
1489     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1490 
1491   if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
1492               GLC, SLC, TFE, DLC))
1493     return false;
1494 
1495   if (!cast<ConstantSDNode>(Offen)->getSExtValue() &&
1496       !cast<ConstantSDNode>(Idxen)->getSExtValue() &&
1497       !cast<ConstantSDNode>(Addr64)->getSExtValue()) {
1498     uint64_t Rsrc = TII->getDefaultRsrcDataFormat() |
1499                     APInt::getAllOnesValue(32).getZExtValue(); // Size
1500     SDLoc DL(Addr);
1501 
1502     const SITargetLowering& Lowering =
1503       *static_cast<const SITargetLowering*>(getTargetLowering());
1504 
1505     SRsrc = SDValue(Lowering.buildRSRC(*CurDAG, DL, Ptr, 0, Rsrc), 0);
1506     return true;
1507   }
1508   return false;
1509 }
1510 
1511 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1512                                            SDValue &Soffset, SDValue &Offset
1513                                            ) const {
1514   SDValue GLC, SLC, TFE, DLC;
1515 
1516   return SelectMUBUFOffset(Addr, SRsrc, Soffset, Offset, GLC, SLC, TFE, DLC);
1517 }
1518 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1519                                            SDValue &Soffset, SDValue &Offset,
1520                                            SDValue &SLC) const {
1521   SDValue GLC, TFE, DLC;
1522 
1523   return SelectMUBUFOffset(Addr, SRsrc, Soffset, Offset, GLC, SLC, TFE, DLC);
1524 }
1525 
1526 template <bool IsSigned>
1527 bool AMDGPUDAGToDAGISel::SelectFlatOffset(SDNode *N,
1528                                           SDValue Addr,
1529                                           SDValue &VAddr,
1530                                           SDValue &Offset,
1531                                           SDValue &SLC) const {
1532   return static_cast<const SITargetLowering*>(getTargetLowering())->
1533     SelectFlatOffset(IsSigned, *CurDAG, N, Addr, VAddr, Offset, SLC);
1534 }
1535 
1536 bool AMDGPUDAGToDAGISel::SelectFlatAtomic(SDNode *N,
1537                                           SDValue Addr,
1538                                           SDValue &VAddr,
1539                                           SDValue &Offset,
1540                                           SDValue &SLC) const {
1541   return SelectFlatOffset<false>(N, Addr, VAddr, Offset, SLC);
1542 }
1543 
1544 bool AMDGPUDAGToDAGISel::SelectFlatAtomicSigned(SDNode *N,
1545                                           SDValue Addr,
1546                                           SDValue &VAddr,
1547                                           SDValue &Offset,
1548                                           SDValue &SLC) const {
1549   return SelectFlatOffset<true>(N, Addr, VAddr, Offset, SLC);
1550 }
1551 
1552 bool AMDGPUDAGToDAGISel::SelectSMRDOffset(SDValue ByteOffsetNode,
1553                                           SDValue &Offset, bool &Imm) const {
1554 
1555   // FIXME: Handle non-constant offsets.
1556   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ByteOffsetNode);
1557   if (!C)
1558     return false;
1559 
1560   SDLoc SL(ByteOffsetNode);
1561   GCNSubtarget::Generation Gen = Subtarget->getGeneration();
1562   int64_t ByteOffset = C->getSExtValue();
1563   int64_t EncodedOffset = AMDGPU::getSMRDEncodedOffset(*Subtarget, ByteOffset);
1564 
1565   if (AMDGPU::isLegalSMRDImmOffset(*Subtarget, ByteOffset)) {
1566     Offset = CurDAG->getTargetConstant(EncodedOffset, SL, MVT::i32);
1567     Imm = true;
1568     return true;
1569   }
1570 
1571   if (!isUInt<32>(EncodedOffset) || !isUInt<32>(ByteOffset))
1572     return false;
1573 
1574   if (Gen == AMDGPUSubtarget::SEA_ISLANDS && isUInt<32>(EncodedOffset)) {
1575     // 32-bit Immediates are supported on Sea Islands.
1576     Offset = CurDAG->getTargetConstant(EncodedOffset, SL, MVT::i32);
1577   } else {
1578     SDValue C32Bit = CurDAG->getTargetConstant(ByteOffset, SL, MVT::i32);
1579     Offset = SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32,
1580                                             C32Bit), 0);
1581   }
1582   Imm = false;
1583   return true;
1584 }
1585 
1586 SDValue AMDGPUDAGToDAGISel::Expand32BitAddress(SDValue Addr) const {
1587   if (Addr.getValueType() != MVT::i32)
1588     return Addr;
1589 
1590   // Zero-extend a 32-bit address.
1591   SDLoc SL(Addr);
1592 
1593   const MachineFunction &MF = CurDAG->getMachineFunction();
1594   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1595   unsigned AddrHiVal = Info->get32BitAddressHighBits();
1596   SDValue AddrHi = CurDAG->getTargetConstant(AddrHiVal, SL, MVT::i32);
1597 
1598   const SDValue Ops[] = {
1599     CurDAG->getTargetConstant(AMDGPU::SReg_64_XEXECRegClassID, SL, MVT::i32),
1600     Addr,
1601     CurDAG->getTargetConstant(AMDGPU::sub0, SL, MVT::i32),
1602     SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SL, MVT::i32, AddrHi),
1603             0),
1604     CurDAG->getTargetConstant(AMDGPU::sub1, SL, MVT::i32),
1605   };
1606 
1607   return SDValue(CurDAG->getMachineNode(AMDGPU::REG_SEQUENCE, SL, MVT::i64,
1608                                         Ops), 0);
1609 }
1610 
1611 bool AMDGPUDAGToDAGISel::SelectSMRD(SDValue Addr, SDValue &SBase,
1612                                      SDValue &Offset, bool &Imm) const {
1613   SDLoc SL(Addr);
1614 
1615   // A 32-bit (address + offset) should not cause unsigned 32-bit integer
1616   // wraparound, because s_load instructions perform the addition in 64 bits.
1617   if ((Addr.getValueType() != MVT::i32 ||
1618        Addr->getFlags().hasNoUnsignedWrap()) &&
1619       CurDAG->isBaseWithConstantOffset(Addr)) {
1620     SDValue N0 = Addr.getOperand(0);
1621     SDValue N1 = Addr.getOperand(1);
1622 
1623     if (SelectSMRDOffset(N1, Offset, Imm)) {
1624       SBase = Expand32BitAddress(N0);
1625       return true;
1626     }
1627   }
1628   SBase = Expand32BitAddress(Addr);
1629   Offset = CurDAG->getTargetConstant(0, SL, MVT::i32);
1630   Imm = true;
1631   return true;
1632 }
1633 
1634 bool AMDGPUDAGToDAGISel::SelectSMRDImm(SDValue Addr, SDValue &SBase,
1635                                        SDValue &Offset) const {
1636   bool Imm;
1637   return SelectSMRD(Addr, SBase, Offset, Imm) && Imm;
1638 }
1639 
1640 bool AMDGPUDAGToDAGISel::SelectSMRDImm32(SDValue Addr, SDValue &SBase,
1641                                          SDValue &Offset) const {
1642 
1643   if (Subtarget->getGeneration() != AMDGPUSubtarget::SEA_ISLANDS)
1644     return false;
1645 
1646   bool Imm;
1647   if (!SelectSMRD(Addr, SBase, Offset, Imm))
1648     return false;
1649 
1650   return !Imm && isa<ConstantSDNode>(Offset);
1651 }
1652 
1653 bool AMDGPUDAGToDAGISel::SelectSMRDSgpr(SDValue Addr, SDValue &SBase,
1654                                         SDValue &Offset) const {
1655   bool Imm;
1656   return SelectSMRD(Addr, SBase, Offset, Imm) && !Imm &&
1657          !isa<ConstantSDNode>(Offset);
1658 }
1659 
1660 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm(SDValue Addr,
1661                                              SDValue &Offset) const {
1662   bool Imm;
1663   return SelectSMRDOffset(Addr, Offset, Imm) && Imm;
1664 }
1665 
1666 bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm32(SDValue Addr,
1667                                                SDValue &Offset) const {
1668   if (Subtarget->getGeneration() != AMDGPUSubtarget::SEA_ISLANDS)
1669     return false;
1670 
1671   bool Imm;
1672   if (!SelectSMRDOffset(Addr, Offset, Imm))
1673     return false;
1674 
1675   return !Imm && isa<ConstantSDNode>(Offset);
1676 }
1677 
1678 bool AMDGPUDAGToDAGISel::SelectMOVRELOffset(SDValue Index,
1679                                             SDValue &Base,
1680                                             SDValue &Offset) const {
1681   SDLoc DL(Index);
1682 
1683   if (CurDAG->isBaseWithConstantOffset(Index)) {
1684     SDValue N0 = Index.getOperand(0);
1685     SDValue N1 = Index.getOperand(1);
1686     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
1687 
1688     // (add n0, c0)
1689     // Don't peel off the offset (c0) if doing so could possibly lead
1690     // the base (n0) to be negative.
1691     if (C1->getSExtValue() <= 0 || CurDAG->SignBitIsZero(N0)) {
1692       Base = N0;
1693       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), DL, MVT::i32);
1694       return true;
1695     }
1696   }
1697 
1698   if (isa<ConstantSDNode>(Index))
1699     return false;
1700 
1701   Base = Index;
1702   Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
1703   return true;
1704 }
1705 
1706 SDNode *AMDGPUDAGToDAGISel::getS_BFE(unsigned Opcode, const SDLoc &DL,
1707                                      SDValue Val, uint32_t Offset,
1708                                      uint32_t Width) {
1709   // Transformation function, pack the offset and width of a BFE into
1710   // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
1711   // source, bits [5:0] contain the offset and bits [22:16] the width.
1712   uint32_t PackedVal = Offset | (Width << 16);
1713   SDValue PackedConst = CurDAG->getTargetConstant(PackedVal, DL, MVT::i32);
1714 
1715   return CurDAG->getMachineNode(Opcode, DL, MVT::i32, Val, PackedConst);
1716 }
1717 
1718 void AMDGPUDAGToDAGISel::SelectS_BFEFromShifts(SDNode *N) {
1719   // "(a << b) srl c)" ---> "BFE_U32 a, (c-b), (32-c)
1720   // "(a << b) sra c)" ---> "BFE_I32 a, (c-b), (32-c)
1721   // Predicate: 0 < b <= c < 32
1722 
1723   const SDValue &Shl = N->getOperand(0);
1724   ConstantSDNode *B = dyn_cast<ConstantSDNode>(Shl->getOperand(1));
1725   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
1726 
1727   if (B && C) {
1728     uint32_t BVal = B->getZExtValue();
1729     uint32_t CVal = C->getZExtValue();
1730 
1731     if (0 < BVal && BVal <= CVal && CVal < 32) {
1732       bool Signed = N->getOpcode() == ISD::SRA;
1733       unsigned Opcode = Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32;
1734 
1735       ReplaceNode(N, getS_BFE(Opcode, SDLoc(N), Shl.getOperand(0), CVal - BVal,
1736                               32 - CVal));
1737       return;
1738     }
1739   }
1740   SelectCode(N);
1741 }
1742 
1743 void AMDGPUDAGToDAGISel::SelectS_BFE(SDNode *N) {
1744   switch (N->getOpcode()) {
1745   case ISD::AND:
1746     if (N->getOperand(0).getOpcode() == ISD::SRL) {
1747       // "(a srl b) & mask" ---> "BFE_U32 a, b, popcount(mask)"
1748       // Predicate: isMask(mask)
1749       const SDValue &Srl = N->getOperand(0);
1750       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(Srl.getOperand(1));
1751       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
1752 
1753       if (Shift && Mask) {
1754         uint32_t ShiftVal = Shift->getZExtValue();
1755         uint32_t MaskVal = Mask->getZExtValue();
1756 
1757         if (isMask_32(MaskVal)) {
1758           uint32_t WidthVal = countPopulation(MaskVal);
1759 
1760           ReplaceNode(N, getS_BFE(AMDGPU::S_BFE_U32, SDLoc(N),
1761                                   Srl.getOperand(0), ShiftVal, WidthVal));
1762           return;
1763         }
1764       }
1765     }
1766     break;
1767   case ISD::SRL:
1768     if (N->getOperand(0).getOpcode() == ISD::AND) {
1769       // "(a & mask) srl b)" ---> "BFE_U32 a, b, popcount(mask >> b)"
1770       // Predicate: isMask(mask >> b)
1771       const SDValue &And = N->getOperand(0);
1772       ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(N->getOperand(1));
1773       ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(And->getOperand(1));
1774 
1775       if (Shift && Mask) {
1776         uint32_t ShiftVal = Shift->getZExtValue();
1777         uint32_t MaskVal = Mask->getZExtValue() >> ShiftVal;
1778 
1779         if (isMask_32(MaskVal)) {
1780           uint32_t WidthVal = countPopulation(MaskVal);
1781 
1782           ReplaceNode(N, getS_BFE(AMDGPU::S_BFE_U32, SDLoc(N),
1783                                   And.getOperand(0), ShiftVal, WidthVal));
1784           return;
1785         }
1786       }
1787     } else if (N->getOperand(0).getOpcode() == ISD::SHL) {
1788       SelectS_BFEFromShifts(N);
1789       return;
1790     }
1791     break;
1792   case ISD::SRA:
1793     if (N->getOperand(0).getOpcode() == ISD::SHL) {
1794       SelectS_BFEFromShifts(N);
1795       return;
1796     }
1797     break;
1798 
1799   case ISD::SIGN_EXTEND_INREG: {
1800     // sext_inreg (srl x, 16), i8 -> bfe_i32 x, 16, 8
1801     SDValue Src = N->getOperand(0);
1802     if (Src.getOpcode() != ISD::SRL)
1803       break;
1804 
1805     const ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(Src.getOperand(1));
1806     if (!Amt)
1807       break;
1808 
1809     unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
1810     ReplaceNode(N, getS_BFE(AMDGPU::S_BFE_I32, SDLoc(N), Src.getOperand(0),
1811                             Amt->getZExtValue(), Width));
1812     return;
1813   }
1814   }
1815 
1816   SelectCode(N);
1817 }
1818 
1819 bool AMDGPUDAGToDAGISel::isCBranchSCC(const SDNode *N) const {
1820   assert(N->getOpcode() == ISD::BRCOND);
1821   if (!N->hasOneUse())
1822     return false;
1823 
1824   SDValue Cond = N->getOperand(1);
1825   if (Cond.getOpcode() == ISD::CopyToReg)
1826     Cond = Cond.getOperand(2);
1827 
1828   if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse())
1829     return false;
1830 
1831   MVT VT = Cond.getOperand(0).getSimpleValueType();
1832   if (VT == MVT::i32)
1833     return true;
1834 
1835   if (VT == MVT::i64) {
1836     auto ST = static_cast<const GCNSubtarget *>(Subtarget);
1837 
1838     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
1839     return (CC == ISD::SETEQ || CC == ISD::SETNE) && ST->hasScalarCompareEq64();
1840   }
1841 
1842   return false;
1843 }
1844 
1845 void AMDGPUDAGToDAGISel::SelectBRCOND(SDNode *N) {
1846   SDValue Cond = N->getOperand(1);
1847 
1848   if (Cond.isUndef()) {
1849     CurDAG->SelectNodeTo(N, AMDGPU::SI_BR_UNDEF, MVT::Other,
1850                          N->getOperand(2), N->getOperand(0));
1851     return;
1852   }
1853 
1854   const GCNSubtarget *ST = static_cast<const GCNSubtarget *>(Subtarget);
1855   const SIRegisterInfo *TRI = ST->getRegisterInfo();
1856 
1857   bool UseSCCBr = isCBranchSCC(N) && isUniformBr(N);
1858   unsigned BrOp = UseSCCBr ? AMDGPU::S_CBRANCH_SCC1 : AMDGPU::S_CBRANCH_VCCNZ;
1859   unsigned CondReg = UseSCCBr ? (unsigned)AMDGPU::SCC : TRI->getVCC();
1860   SDLoc SL(N);
1861 
1862   if (!UseSCCBr) {
1863     // This is the case that we are selecting to S_CBRANCH_VCCNZ.  We have not
1864     // analyzed what generates the vcc value, so we do not know whether vcc
1865     // bits for disabled lanes are 0.  Thus we need to mask out bits for
1866     // disabled lanes.
1867     //
1868     // For the case that we select S_CBRANCH_SCC1 and it gets
1869     // changed to S_CBRANCH_VCCNZ in SIFixSGPRCopies, SIFixSGPRCopies calls
1870     // SIInstrInfo::moveToVALU which inserts the S_AND).
1871     //
1872     // We could add an analysis of what generates the vcc value here and omit
1873     // the S_AND when is unnecessary. But it would be better to add a separate
1874     // pass after SIFixSGPRCopies to do the unnecessary S_AND removal, so it
1875     // catches both cases.
1876     Cond = SDValue(CurDAG->getMachineNode(ST->isWave32() ? AMDGPU::S_AND_B32
1877                                                          : AMDGPU::S_AND_B64,
1878                      SL, MVT::i1,
1879                      CurDAG->getRegister(ST->isWave32() ? AMDGPU::EXEC_LO
1880                                                         : AMDGPU::EXEC,
1881                                          MVT::i1),
1882                     Cond),
1883                    0);
1884   }
1885 
1886   SDValue VCC = CurDAG->getCopyToReg(N->getOperand(0), SL, CondReg, Cond);
1887   CurDAG->SelectNodeTo(N, BrOp, MVT::Other,
1888                        N->getOperand(2), // Basic Block
1889                        VCC.getValue(0));
1890 }
1891 
1892 void AMDGPUDAGToDAGISel::SelectFMAD_FMA(SDNode *N) {
1893   MVT VT = N->getSimpleValueType(0);
1894   bool IsFMA = N->getOpcode() == ISD::FMA;
1895   if (VT != MVT::f32 || (!Subtarget->hasMadMixInsts() &&
1896                          !Subtarget->hasFmaMixInsts()) ||
1897       ((IsFMA && Subtarget->hasMadMixInsts()) ||
1898        (!IsFMA && Subtarget->hasFmaMixInsts()))) {
1899     SelectCode(N);
1900     return;
1901   }
1902 
1903   SDValue Src0 = N->getOperand(0);
1904   SDValue Src1 = N->getOperand(1);
1905   SDValue Src2 = N->getOperand(2);
1906   unsigned Src0Mods, Src1Mods, Src2Mods;
1907 
1908   // Avoid using v_mad_mix_f32/v_fma_mix_f32 unless there is actually an operand
1909   // using the conversion from f16.
1910   bool Sel0 = SelectVOP3PMadMixModsImpl(Src0, Src0, Src0Mods);
1911   bool Sel1 = SelectVOP3PMadMixModsImpl(Src1, Src1, Src1Mods);
1912   bool Sel2 = SelectVOP3PMadMixModsImpl(Src2, Src2, Src2Mods);
1913 
1914   assert((IsFMA || !Subtarget->hasFP32Denormals()) &&
1915          "fmad selected with denormals enabled");
1916   // TODO: We can select this with f32 denormals enabled if all the sources are
1917   // converted from f16 (in which case fmad isn't legal).
1918 
1919   if (Sel0 || Sel1 || Sel2) {
1920     // For dummy operands.
1921     SDValue Zero = CurDAG->getTargetConstant(0, SDLoc(), MVT::i32);
1922     SDValue Ops[] = {
1923       CurDAG->getTargetConstant(Src0Mods, SDLoc(), MVT::i32), Src0,
1924       CurDAG->getTargetConstant(Src1Mods, SDLoc(), MVT::i32), Src1,
1925       CurDAG->getTargetConstant(Src2Mods, SDLoc(), MVT::i32), Src2,
1926       CurDAG->getTargetConstant(0, SDLoc(), MVT::i1),
1927       Zero, Zero
1928     };
1929 
1930     CurDAG->SelectNodeTo(N,
1931                          IsFMA ? AMDGPU::V_FMA_MIX_F32 : AMDGPU::V_MAD_MIX_F32,
1932                          MVT::f32, Ops);
1933   } else {
1934     SelectCode(N);
1935   }
1936 }
1937 
1938 // This is here because there isn't a way to use the generated sub0_sub1 as the
1939 // subreg index to EXTRACT_SUBREG in tablegen.
1940 void AMDGPUDAGToDAGISel::SelectATOMIC_CMP_SWAP(SDNode *N) {
1941   MemSDNode *Mem = cast<MemSDNode>(N);
1942   unsigned AS = Mem->getAddressSpace();
1943   if (AS == AMDGPUAS::FLAT_ADDRESS) {
1944     SelectCode(N);
1945     return;
1946   }
1947 
1948   MVT VT = N->getSimpleValueType(0);
1949   bool Is32 = (VT == MVT::i32);
1950   SDLoc SL(N);
1951 
1952   MachineSDNode *CmpSwap = nullptr;
1953   if (Subtarget->hasAddr64()) {
1954     SDValue SRsrc, VAddr, SOffset, Offset, SLC;
1955 
1956     if (SelectMUBUFAddr64(Mem->getBasePtr(), SRsrc, VAddr, SOffset, Offset, SLC)) {
1957       unsigned Opcode = Is32 ? AMDGPU::BUFFER_ATOMIC_CMPSWAP_ADDR64_RTN :
1958         AMDGPU::BUFFER_ATOMIC_CMPSWAP_X2_ADDR64_RTN;
1959       SDValue CmpVal = Mem->getOperand(2);
1960 
1961       // XXX - Do we care about glue operands?
1962 
1963       SDValue Ops[] = {
1964         CmpVal, VAddr, SRsrc, SOffset, Offset, SLC, Mem->getChain()
1965       };
1966 
1967       CmpSwap = CurDAG->getMachineNode(Opcode, SL, Mem->getVTList(), Ops);
1968     }
1969   }
1970 
1971   if (!CmpSwap) {
1972     SDValue SRsrc, SOffset, Offset, SLC;
1973     if (SelectMUBUFOffset(Mem->getBasePtr(), SRsrc, SOffset, Offset, SLC)) {
1974       unsigned Opcode = Is32 ? AMDGPU::BUFFER_ATOMIC_CMPSWAP_OFFSET_RTN :
1975         AMDGPU::BUFFER_ATOMIC_CMPSWAP_X2_OFFSET_RTN;
1976 
1977       SDValue CmpVal = Mem->getOperand(2);
1978       SDValue Ops[] = {
1979         CmpVal, SRsrc, SOffset, Offset, SLC, Mem->getChain()
1980       };
1981 
1982       CmpSwap = CurDAG->getMachineNode(Opcode, SL, Mem->getVTList(), Ops);
1983     }
1984   }
1985 
1986   if (!CmpSwap) {
1987     SelectCode(N);
1988     return;
1989   }
1990 
1991   MachineMemOperand *MMO = Mem->getMemOperand();
1992   CurDAG->setNodeMemRefs(CmpSwap, {MMO});
1993 
1994   unsigned SubReg = Is32 ? AMDGPU::sub0 : AMDGPU::sub0_sub1;
1995   SDValue Extract
1996     = CurDAG->getTargetExtractSubreg(SubReg, SL, VT, SDValue(CmpSwap, 0));
1997 
1998   ReplaceUses(SDValue(N, 0), Extract);
1999   ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 1));
2000   CurDAG->RemoveDeadNode(N);
2001 }
2002 
2003 void AMDGPUDAGToDAGISel::SelectDSAppendConsume(SDNode *N, unsigned IntrID) {
2004   // The address is assumed to be uniform, so if it ends up in a VGPR, it will
2005   // be copied to an SGPR with readfirstlane.
2006   unsigned Opc = IntrID == Intrinsic::amdgcn_ds_append ?
2007     AMDGPU::DS_APPEND : AMDGPU::DS_CONSUME;
2008 
2009   SDValue Chain = N->getOperand(0);
2010   SDValue Ptr = N->getOperand(2);
2011   MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
2012   MachineMemOperand *MMO = M->getMemOperand();
2013   bool IsGDS = M->getAddressSpace() == AMDGPUAS::REGION_ADDRESS;
2014 
2015   SDValue Offset;
2016   if (CurDAG->isBaseWithConstantOffset(Ptr)) {
2017     SDValue PtrBase = Ptr.getOperand(0);
2018     SDValue PtrOffset = Ptr.getOperand(1);
2019 
2020     const APInt &OffsetVal = cast<ConstantSDNode>(PtrOffset)->getAPIntValue();
2021     if (isDSOffsetLegal(PtrBase, OffsetVal.getZExtValue(), 16)) {
2022       N = glueCopyToM0(N, PtrBase);
2023       Offset = CurDAG->getTargetConstant(OffsetVal, SDLoc(), MVT::i32);
2024     }
2025   }
2026 
2027   if (!Offset) {
2028     N = glueCopyToM0(N, Ptr);
2029     Offset = CurDAG->getTargetConstant(0, SDLoc(), MVT::i32);
2030   }
2031 
2032   SDValue Ops[] = {
2033     Offset,
2034     CurDAG->getTargetConstant(IsGDS, SDLoc(), MVT::i32),
2035     Chain,
2036     N->getOperand(N->getNumOperands() - 1) // New glue
2037   };
2038 
2039   SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
2040   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
2041 }
2042 
2043 void AMDGPUDAGToDAGISel::SelectDS_GWS(SDNode *N, unsigned IntrID) {
2044   SDLoc SL(N);
2045   SDValue VSrc0 = N->getOperand(2);
2046   SDValue BaseOffset = N->getOperand(3);
2047   int ImmOffset = 0;
2048   MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(N);
2049   MachineMemOperand *MMO = M->getMemOperand();
2050 
2051   // Don't worry if the offset ends up in a VGPR. Only one lane will have
2052   // effect, so SIFixSGPRCopies will validly insert readfirstlane.
2053 
2054   // The resource id offset is computed as (<isa opaque base> + M0[21:16] +
2055   // offset field) % 64. Some versions of the programming guide omit the m0
2056   // part, or claim it's from offset 0.
2057   if (ConstantSDNode *ConstOffset = dyn_cast<ConstantSDNode>(BaseOffset)) {
2058     // If we have a constant offset, try to use the default value for m0 as a
2059     // base to possibly avoid setting it up.
2060     glueCopyToM0(N, CurDAG->getTargetConstant(-1, SL, MVT::i32));
2061     ImmOffset = ConstOffset->getZExtValue() + 1;
2062   } else {
2063     if (CurDAG->isBaseWithConstantOffset(BaseOffset)) {
2064       ImmOffset = BaseOffset.getConstantOperandVal(1);
2065       BaseOffset = BaseOffset.getOperand(0);
2066     }
2067 
2068     // Prefer to do the shift in an SGPR since it should be possible to use m0
2069     // as the result directly. If it's already an SGPR, it will be eliminated
2070     // later.
2071     SDNode *SGPROffset
2072       = CurDAG->getMachineNode(AMDGPU::V_READFIRSTLANE_B32, SL, MVT::i32,
2073                                BaseOffset);
2074     // Shift to offset in m0
2075     SDNode *M0Base
2076       = CurDAG->getMachineNode(AMDGPU::S_LSHL_B32, SL, MVT::i32,
2077                                SDValue(SGPROffset, 0),
2078                                CurDAG->getTargetConstant(16, SL, MVT::i32));
2079     glueCopyToM0(N, SDValue(M0Base, 0));
2080   }
2081 
2082   // The manual doesn't mention this, but it seems only v0 works.
2083   SDValue V0 = CurDAG->getRegister(AMDGPU::VGPR0, MVT::i32);
2084 
2085   SDValue CopyToV0 = CurDAG->getCopyToReg(
2086     N->getOperand(0), SL, V0, VSrc0,
2087     N->getOperand(N->getNumOperands() - 1));
2088 
2089   SDValue OffsetField = CurDAG->getTargetConstant(ImmOffset, SL, MVT::i32);
2090 
2091   // TODO: Can this just be removed from the instruction?
2092   SDValue GDS = CurDAG->getTargetConstant(1, SL, MVT::i1);
2093 
2094   unsigned Opc = IntrID == Intrinsic::amdgcn_ds_gws_init ?
2095     AMDGPU::DS_GWS_INIT : AMDGPU::DS_GWS_BARRIER;
2096 
2097   SDValue Ops[] = {
2098     V0,
2099     OffsetField,
2100     GDS,
2101     CopyToV0, // Chain
2102     CopyToV0.getValue(1) // Glue
2103   };
2104 
2105   SDNode *Selected = CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops);
2106   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Selected), {MMO});
2107 }
2108 
2109 void AMDGPUDAGToDAGISel::SelectINTRINSIC_W_CHAIN(SDNode *N) {
2110   unsigned IntrID = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2111   switch (IntrID) {
2112   case Intrinsic::amdgcn_ds_append:
2113   case Intrinsic::amdgcn_ds_consume: {
2114     if (N->getValueType(0) != MVT::i32)
2115       break;
2116     SelectDSAppendConsume(N, IntrID);
2117     return;
2118   }
2119   }
2120 
2121   SelectCode(N);
2122 }
2123 
2124 void AMDGPUDAGToDAGISel::SelectINTRINSIC_VOID(SDNode *N) {
2125   unsigned IntrID = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2126   switch (IntrID) {
2127   case Intrinsic::amdgcn_ds_gws_init:
2128   case Intrinsic::amdgcn_ds_gws_barrier:
2129     SelectDS_GWS(N, IntrID);
2130     return;
2131   default:
2132     break;
2133   }
2134 
2135   SelectCode(N);
2136 }
2137 
2138 bool AMDGPUDAGToDAGISel::SelectVOP3ModsImpl(SDValue In, SDValue &Src,
2139                                             unsigned &Mods) const {
2140   Mods = 0;
2141   Src = In;
2142 
2143   if (Src.getOpcode() == ISD::FNEG) {
2144     Mods |= SISrcMods::NEG;
2145     Src = Src.getOperand(0);
2146   }
2147 
2148   if (Src.getOpcode() == ISD::FABS) {
2149     Mods |= SISrcMods::ABS;
2150     Src = Src.getOperand(0);
2151   }
2152 
2153   return true;
2154 }
2155 
2156 bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
2157                                         SDValue &SrcMods) const {
2158   unsigned Mods;
2159   if (SelectVOP3ModsImpl(In, Src, Mods)) {
2160     SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2161     return true;
2162   }
2163 
2164   return false;
2165 }
2166 
2167 bool AMDGPUDAGToDAGISel::SelectVOP3Mods_NNaN(SDValue In, SDValue &Src,
2168                                              SDValue &SrcMods) const {
2169   SelectVOP3Mods(In, Src, SrcMods);
2170   return isNoNanSrc(Src);
2171 }
2172 
2173 bool AMDGPUDAGToDAGISel::SelectVOP3NoMods(SDValue In, SDValue &Src) const {
2174   if (In.getOpcode() == ISD::FABS || In.getOpcode() == ISD::FNEG)
2175     return false;
2176 
2177   Src = In;
2178   return true;
2179 }
2180 
2181 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
2182                                          SDValue &SrcMods, SDValue &Clamp,
2183                                          SDValue &Omod) const {
2184   SDLoc DL(In);
2185   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
2186   Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
2187 
2188   return SelectVOP3Mods(In, Src, SrcMods);
2189 }
2190 
2191 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0Clamp0OMod(SDValue In, SDValue &Src,
2192                                                    SDValue &SrcMods,
2193                                                    SDValue &Clamp,
2194                                                    SDValue &Omod) const {
2195   Clamp = Omod = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);
2196   return SelectVOP3Mods(In, Src, SrcMods);
2197 }
2198 
2199 bool AMDGPUDAGToDAGISel::SelectVOP3OMods(SDValue In, SDValue &Src,
2200                                          SDValue &Clamp, SDValue &Omod) const {
2201   Src = In;
2202 
2203   SDLoc DL(In);
2204   Clamp = CurDAG->getTargetConstant(0, DL, MVT::i1);
2205   Omod = CurDAG->getTargetConstant(0, DL, MVT::i1);
2206 
2207   return true;
2208 }
2209 
2210 bool AMDGPUDAGToDAGISel::SelectVOP3PMods(SDValue In, SDValue &Src,
2211                                          SDValue &SrcMods) const {
2212   unsigned Mods = 0;
2213   Src = In;
2214 
2215   if (Src.getOpcode() == ISD::FNEG) {
2216     Mods ^= (SISrcMods::NEG | SISrcMods::NEG_HI);
2217     Src = Src.getOperand(0);
2218   }
2219 
2220   if (Src.getOpcode() == ISD::BUILD_VECTOR) {
2221     unsigned VecMods = Mods;
2222 
2223     SDValue Lo = stripBitcast(Src.getOperand(0));
2224     SDValue Hi = stripBitcast(Src.getOperand(1));
2225 
2226     if (Lo.getOpcode() == ISD::FNEG) {
2227       Lo = stripBitcast(Lo.getOperand(0));
2228       Mods ^= SISrcMods::NEG;
2229     }
2230 
2231     if (Hi.getOpcode() == ISD::FNEG) {
2232       Hi = stripBitcast(Hi.getOperand(0));
2233       Mods ^= SISrcMods::NEG_HI;
2234     }
2235 
2236     if (isExtractHiElt(Lo, Lo))
2237       Mods |= SISrcMods::OP_SEL_0;
2238 
2239     if (isExtractHiElt(Hi, Hi))
2240       Mods |= SISrcMods::OP_SEL_1;
2241 
2242     Lo = stripExtractLoElt(Lo);
2243     Hi = stripExtractLoElt(Hi);
2244 
2245     if (Lo == Hi && !isInlineImmediate(Lo.getNode())) {
2246       // Really a scalar input. Just select from the low half of the register to
2247       // avoid packing.
2248 
2249       Src = Lo;
2250       SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2251       return true;
2252     }
2253 
2254     Mods = VecMods;
2255   }
2256 
2257   // Packed instructions do not have abs modifiers.
2258   Mods |= SISrcMods::OP_SEL_1;
2259 
2260   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2261   return true;
2262 }
2263 
2264 bool AMDGPUDAGToDAGISel::SelectVOP3PMods0(SDValue In, SDValue &Src,
2265                                           SDValue &SrcMods,
2266                                           SDValue &Clamp) const {
2267   SDLoc SL(In);
2268 
2269   // FIXME: Handle clamp and op_sel
2270   Clamp = CurDAG->getTargetConstant(0, SL, MVT::i32);
2271 
2272   return SelectVOP3PMods(In, Src, SrcMods);
2273 }
2274 
2275 bool AMDGPUDAGToDAGISel::SelectVOP3OpSel(SDValue In, SDValue &Src,
2276                                          SDValue &SrcMods) const {
2277   Src = In;
2278   // FIXME: Handle op_sel
2279   SrcMods = CurDAG->getTargetConstant(0, SDLoc(In), MVT::i32);
2280   return true;
2281 }
2282 
2283 bool AMDGPUDAGToDAGISel::SelectVOP3OpSel0(SDValue In, SDValue &Src,
2284                                           SDValue &SrcMods,
2285                                           SDValue &Clamp) const {
2286   SDLoc SL(In);
2287 
2288   // FIXME: Handle clamp
2289   Clamp = CurDAG->getTargetConstant(0, SL, MVT::i32);
2290 
2291   return SelectVOP3OpSel(In, Src, SrcMods);
2292 }
2293 
2294 bool AMDGPUDAGToDAGISel::SelectVOP3OpSelMods(SDValue In, SDValue &Src,
2295                                              SDValue &SrcMods) const {
2296   // FIXME: Handle op_sel
2297   return SelectVOP3Mods(In, Src, SrcMods);
2298 }
2299 
2300 bool AMDGPUDAGToDAGISel::SelectVOP3OpSelMods0(SDValue In, SDValue &Src,
2301                                               SDValue &SrcMods,
2302                                               SDValue &Clamp) const {
2303   SDLoc SL(In);
2304 
2305   // FIXME: Handle clamp
2306   Clamp = CurDAG->getTargetConstant(0, SL, MVT::i32);
2307 
2308   return SelectVOP3OpSelMods(In, Src, SrcMods);
2309 }
2310 
2311 // The return value is not whether the match is possible (which it always is),
2312 // but whether or not it a conversion is really used.
2313 bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsImpl(SDValue In, SDValue &Src,
2314                                                    unsigned &Mods) const {
2315   Mods = 0;
2316   SelectVOP3ModsImpl(In, Src, Mods);
2317 
2318   if (Src.getOpcode() == ISD::FP_EXTEND) {
2319     Src = Src.getOperand(0);
2320     assert(Src.getValueType() == MVT::f16);
2321     Src = stripBitcast(Src);
2322 
2323     // Be careful about folding modifiers if we already have an abs. fneg is
2324     // applied last, so we don't want to apply an earlier fneg.
2325     if ((Mods & SISrcMods::ABS) == 0) {
2326       unsigned ModsTmp;
2327       SelectVOP3ModsImpl(Src, Src, ModsTmp);
2328 
2329       if ((ModsTmp & SISrcMods::NEG) != 0)
2330         Mods ^= SISrcMods::NEG;
2331 
2332       if ((ModsTmp & SISrcMods::ABS) != 0)
2333         Mods |= SISrcMods::ABS;
2334     }
2335 
2336     // op_sel/op_sel_hi decide the source type and source.
2337     // If the source's op_sel_hi is set, it indicates to do a conversion from fp16.
2338     // If the sources's op_sel is set, it picks the high half of the source
2339     // register.
2340 
2341     Mods |= SISrcMods::OP_SEL_1;
2342     if (isExtractHiElt(Src, Src)) {
2343       Mods |= SISrcMods::OP_SEL_0;
2344 
2345       // TODO: Should we try to look for neg/abs here?
2346     }
2347 
2348     return true;
2349   }
2350 
2351   return false;
2352 }
2353 
2354 bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixMods(SDValue In, SDValue &Src,
2355                                                SDValue &SrcMods) const {
2356   unsigned Mods = 0;
2357   SelectVOP3PMadMixModsImpl(In, Src, Mods);
2358   SrcMods = CurDAG->getTargetConstant(Mods, SDLoc(In), MVT::i32);
2359   return true;
2360 }
2361 
2362 SDValue AMDGPUDAGToDAGISel::getHi16Elt(SDValue In) const {
2363   if (In.isUndef())
2364     return CurDAG->getUNDEF(MVT::i32);
2365 
2366   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(In)) {
2367     SDLoc SL(In);
2368     return CurDAG->getConstant(C->getZExtValue() << 16, SL, MVT::i32);
2369   }
2370 
2371   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(In)) {
2372     SDLoc SL(In);
2373     return CurDAG->getConstant(
2374       C->getValueAPF().bitcastToAPInt().getZExtValue() << 16, SL, MVT::i32);
2375   }
2376 
2377   SDValue Src;
2378   if (isExtractHiElt(In, Src))
2379     return Src;
2380 
2381   return SDValue();
2382 }
2383 
2384 bool AMDGPUDAGToDAGISel::isVGPRImm(const SDNode * N) const {
2385   if (Subtarget->getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS) {
2386     return false;
2387   }
2388   const SIRegisterInfo *SIRI =
2389     static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
2390   const SIInstrInfo * SII =
2391     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2392 
2393   unsigned Limit = 0;
2394   bool AllUsesAcceptSReg = true;
2395   for (SDNode::use_iterator U = N->use_begin(), E = SDNode::use_end();
2396     Limit < 10 && U != E; ++U, ++Limit) {
2397     const TargetRegisterClass *RC = getOperandRegClass(*U, U.getOperandNo());
2398 
2399     // If the register class is unknown, it could be an unknown
2400     // register class that needs to be an SGPR, e.g. an inline asm
2401     // constraint
2402     if (!RC || SIRI->isSGPRClass(RC))
2403       return false;
2404 
2405     if (RC != &AMDGPU::VS_32RegClass) {
2406       AllUsesAcceptSReg = false;
2407       SDNode * User = *U;
2408       if (User->isMachineOpcode()) {
2409         unsigned Opc = User->getMachineOpcode();
2410         MCInstrDesc Desc = SII->get(Opc);
2411         if (Desc.isCommutable()) {
2412           unsigned OpIdx = Desc.getNumDefs() + U.getOperandNo();
2413           unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
2414           if (SII->findCommutedOpIndices(Desc, OpIdx, CommuteIdx1)) {
2415             unsigned CommutedOpNo = CommuteIdx1 - Desc.getNumDefs();
2416             const TargetRegisterClass *CommutedRC = getOperandRegClass(*U, CommutedOpNo);
2417             if (CommutedRC == &AMDGPU::VS_32RegClass)
2418               AllUsesAcceptSReg = true;
2419           }
2420         }
2421       }
2422       // If "AllUsesAcceptSReg == false" so far we haven't suceeded
2423       // commuting current user. This means have at least one use
2424       // that strictly require VGPR. Thus, we will not attempt to commute
2425       // other user instructions.
2426       if (!AllUsesAcceptSReg)
2427         break;
2428     }
2429   }
2430   return !AllUsesAcceptSReg && (Limit < 10);
2431 }
2432 
2433 bool AMDGPUDAGToDAGISel::isUniformLoad(const SDNode * N) const {
2434   auto Ld = cast<LoadSDNode>(N);
2435 
2436   return Ld->getAlignment() >= 4 &&
2437         (
2438           (
2439             (
2440               Ld->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS       ||
2441               Ld->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT
2442             )
2443             &&
2444             !N->isDivergent()
2445           )
2446           ||
2447           (
2448             Subtarget->getScalarizeGlobalBehavior() &&
2449             Ld->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
2450             !Ld->isVolatile() &&
2451             !N->isDivergent() &&
2452             static_cast<const SITargetLowering *>(
2453               getTargetLowering())->isMemOpHasNoClobberedMemOperand(N)
2454           )
2455         );
2456 }
2457 
2458 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
2459   const AMDGPUTargetLowering& Lowering =
2460     *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
2461   bool IsModified = false;
2462   do {
2463     IsModified = false;
2464 
2465     // Go over all selected nodes and try to fold them a bit more
2466     SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_begin();
2467     while (Position != CurDAG->allnodes_end()) {
2468       SDNode *Node = &*Position++;
2469       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(Node);
2470       if (!MachineNode)
2471         continue;
2472 
2473       SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
2474       if (ResNode != Node) {
2475         if (ResNode)
2476           ReplaceUses(Node, ResNode);
2477         IsModified = true;
2478       }
2479     }
2480     CurDAG->RemoveDeadNodes();
2481   } while (IsModified);
2482 }
2483 
2484 bool R600DAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
2485   Subtarget = &MF.getSubtarget<R600Subtarget>();
2486   return SelectionDAGISel::runOnMachineFunction(MF);
2487 }
2488 
2489 bool R600DAGToDAGISel::isConstantLoad(const MemSDNode *N, int CbId) const {
2490   if (!N->readMem())
2491     return false;
2492   if (CbId == -1)
2493     return N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
2494            N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT;
2495 
2496   return N->getAddressSpace() == AMDGPUAS::CONSTANT_BUFFER_0 + CbId;
2497 }
2498 
2499 bool R600DAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
2500                                                          SDValue& IntPtr) {
2501   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
2502     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, SDLoc(Addr),
2503                                        true);
2504     return true;
2505   }
2506   return false;
2507 }
2508 
2509 bool R600DAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
2510     SDValue& BaseReg, SDValue &Offset) {
2511   if (!isa<ConstantSDNode>(Addr)) {
2512     BaseReg = Addr;
2513     Offset = CurDAG->getIntPtrConstant(0, SDLoc(Addr), true);
2514     return true;
2515   }
2516   return false;
2517 }
2518 
2519 void R600DAGToDAGISel::Select(SDNode *N) {
2520   unsigned int Opc = N->getOpcode();
2521   if (N->isMachineOpcode()) {
2522     N->setNodeId(-1);
2523     return;   // Already selected.
2524   }
2525 
2526   switch (Opc) {
2527   default: break;
2528   case AMDGPUISD::BUILD_VERTICAL_VECTOR:
2529   case ISD::SCALAR_TO_VECTOR:
2530   case ISD::BUILD_VECTOR: {
2531     EVT VT = N->getValueType(0);
2532     unsigned NumVectorElts = VT.getVectorNumElements();
2533     unsigned RegClassID;
2534     // BUILD_VECTOR was lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
2535     // that adds a 128 bits reg copy when going through TwoAddressInstructions
2536     // pass. We want to avoid 128 bits copies as much as possible because they
2537     // can't be bundled by our scheduler.
2538     switch(NumVectorElts) {
2539     case 2: RegClassID = R600::R600_Reg64RegClassID; break;
2540     case 4:
2541       if (Opc == AMDGPUISD::BUILD_VERTICAL_VECTOR)
2542         RegClassID = R600::R600_Reg128VerticalRegClassID;
2543       else
2544         RegClassID = R600::R600_Reg128RegClassID;
2545       break;
2546     default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
2547     }
2548     SelectBuildVector(N, RegClassID);
2549     return;
2550   }
2551   }
2552 
2553   SelectCode(N);
2554 }
2555 
2556 bool R600DAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
2557                                           SDValue &Offset) {
2558   ConstantSDNode *C;
2559   SDLoc DL(Addr);
2560 
2561   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
2562     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
2563     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
2564   } else if ((Addr.getOpcode() == AMDGPUISD::DWORDADDR) &&
2565              (C = dyn_cast<ConstantSDNode>(Addr.getOperand(0)))) {
2566     Base = CurDAG->getRegister(R600::INDIRECT_BASE_ADDR, MVT::i32);
2567     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
2568   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
2569             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
2570     Base = Addr.getOperand(0);
2571     Offset = CurDAG->getTargetConstant(C->getZExtValue(), DL, MVT::i32);
2572   } else {
2573     Base = Addr;
2574     Offset = CurDAG->getTargetConstant(0, DL, MVT::i32);
2575   }
2576 
2577   return true;
2578 }
2579 
2580 bool R600DAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
2581                                           SDValue &Offset) {
2582   ConstantSDNode *IMMOffset;
2583 
2584   if (Addr.getOpcode() == ISD::ADD
2585       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
2586       && isInt<16>(IMMOffset->getZExtValue())) {
2587 
2588       Base = Addr.getOperand(0);
2589       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), SDLoc(Addr),
2590                                          MVT::i32);
2591       return true;
2592   // If the pointer address is constant, we can move it to the offset field.
2593   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
2594              && isInt<16>(IMMOffset->getZExtValue())) {
2595     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
2596                                   SDLoc(CurDAG->getEntryNode()),
2597                                   R600::ZERO, MVT::i32);
2598     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), SDLoc(Addr),
2599                                        MVT::i32);
2600     return true;
2601   }
2602 
2603   // Default case, no offset
2604   Base = Addr;
2605   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
2606   return true;
2607 }
2608