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