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