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