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