1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
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 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #if defined(_MSC_VER) || defined(__MINGW32__)
15 // Provide M_PI.
16 #define _USE_MATH_DEFINES
17 #endif
18 
19 #include "SIISelLowering.h"
20 #include "AMDGPU.h"
21 #include "AMDGPUSubtarget.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
24 #include "SIDefines.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "Utils/AMDGPUBaseInfo.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/CallingConvLower.h"
41 #include "llvm/CodeGen/DAGCombine.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineLoopInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
93 static cl::opt<bool> DisableLoopAlignment(
94   "amdgpu-disable-loop-alignment",
95   cl::desc("Do not align and prefetch loops"),
96   cl::init(false));
97 
98 static bool hasFP32Denormals(const MachineFunction &MF) {
99   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
100   return Info->getMode().allFP32Denormals();
101 }
102 
103 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
104   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
105   return Info->getMode().allFP64FP16Denormals();
106 }
107 
108 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
109   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
110   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
111     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
112       return AMDGPU::SGPR0 + Reg;
113     }
114   }
115   llvm_unreachable("Cannot allocate sgpr");
116 }
117 
118 SITargetLowering::SITargetLowering(const TargetMachine &TM,
119                                    const GCNSubtarget &STI)
120     : AMDGPUTargetLowering(TM, STI),
121       Subtarget(&STI) {
122   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
123   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
124 
125   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
126   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
127 
128   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
129   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
130   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
131 
132   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
133   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
134 
135   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
136   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
137 
138   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
139   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
140 
141   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
142   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
143 
144   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
145   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
146 
147   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
148   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
149 
150   if (Subtarget->has16BitInsts()) {
151     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
152     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
153 
154     // Unless there are also VOP3P operations, not operations are really legal.
155     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
156     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
157     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
158     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
159   }
160 
161   if (Subtarget->hasMAIInsts()) {
162     addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
163     addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
164   }
165 
166   computeRegisterProperties(Subtarget->getRegisterInfo());
167 
168   // The boolean content concept here is too inflexible. Compares only ever
169   // really produce a 1-bit result. Any copy/extend from these will turn into a
170   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
171   // it's what most targets use.
172   setBooleanContents(ZeroOrOneBooleanContent);
173   setBooleanVectorContents(ZeroOrOneBooleanContent);
174 
175   // We need to custom lower vector stores from local memory
176   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
177   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
178   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
179   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
180   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
181   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
182   setOperationAction(ISD::LOAD, MVT::i1, Custom);
183   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
184 
185   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
186   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
187   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
188   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
189   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
190   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
191   setOperationAction(ISD::STORE, MVT::i1, Custom);
192   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
193 
194   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
195   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
196   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
197   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
198   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
199   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
200   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
201   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
202   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
203   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
204   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
205 
206   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
207   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
208 
209   setOperationAction(ISD::SELECT, MVT::i1, Promote);
210   setOperationAction(ISD::SELECT, MVT::i64, Custom);
211   setOperationAction(ISD::SELECT, MVT::f64, Promote);
212   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
213 
214   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
215   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
216   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
217   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
218   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
219 
220   setOperationAction(ISD::SETCC, MVT::i1, Promote);
221   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
222   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
223   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
224 
225   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
226   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
227 
228   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
229   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
230   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
231   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
232   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
233   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
234   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
235   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
236 
237   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
238   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
239   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
240   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
241   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
242   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
243 
244   setOperationAction(ISD::UADDO, MVT::i32, Legal);
245   setOperationAction(ISD::USUBO, MVT::i32, Legal);
246 
247   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
248   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
249 
250   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
251   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
252   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
253 
254 #if 0
255   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
256   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
257 #endif
258 
259   // We only support LOAD/STORE and vector manipulation ops for vectors
260   // with > 4 elements.
261   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
262                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
263                   MVT::v32i32, MVT::v32f32 }) {
264     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
265       switch (Op) {
266       case ISD::LOAD:
267       case ISD::STORE:
268       case ISD::BUILD_VECTOR:
269       case ISD::BITCAST:
270       case ISD::EXTRACT_VECTOR_ELT:
271       case ISD::INSERT_VECTOR_ELT:
272       case ISD::INSERT_SUBVECTOR:
273       case ISD::EXTRACT_SUBVECTOR:
274       case ISD::SCALAR_TO_VECTOR:
275         break;
276       case ISD::CONCAT_VECTORS:
277         setOperationAction(Op, VT, Custom);
278         break;
279       default:
280         setOperationAction(Op, VT, Expand);
281         break;
282       }
283     }
284   }
285 
286   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
287 
288   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
289   // is expanded to avoid having two separate loops in case the index is a VGPR.
290 
291   // Most operations are naturally 32-bit vector operations. We only support
292   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
293   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
294     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
295     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
296 
297     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
298     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
299 
300     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
301     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
302 
303     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
305   }
306 
307   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
308   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
309   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
310   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
311 
312   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
313   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
314 
315   // Avoid stack access for these.
316   // TODO: Generalize to more vector types.
317   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
318   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
319   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
320   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
321 
322   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
323   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
324   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
325   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
326   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
327 
328   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
329   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
330   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
331 
332   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
333   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
334   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
335   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
336 
337   // Deal with vec3 vector operations when widened to vec4.
338   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
339   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
340   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
341   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
342 
343   // Deal with vec5 vector operations when widened to vec8.
344   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
345   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
346   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
347   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
348 
349   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
350   // and output demarshalling
351   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
352   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
353 
354   // We can't return success/failure, only the old value,
355   // let LLVM add the comparison
356   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
357   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
358 
359   if (Subtarget->hasFlatAddressSpace()) {
360     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
361     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
362   }
363 
364   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
365 
366   // FIXME: This should be narrowed to i32, but that only happens if i64 is
367   // illegal.
368   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
369   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
370   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
371 
372   // On SI this is s_memtime and s_memrealtime on VI.
373   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
374   setOperationAction(ISD::TRAP, MVT::Other, Custom);
375   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
376 
377   if (Subtarget->has16BitInsts()) {
378     setOperationAction(ISD::FPOW, MVT::f16, Promote);
379     setOperationAction(ISD::FLOG, MVT::f16, Custom);
380     setOperationAction(ISD::FEXP, MVT::f16, Custom);
381     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
382   }
383 
384   // v_mad_f32 does not support denormals. We report it as unconditionally
385   // legal, and the context where it is formed will disallow it when fp32
386   // denormals are enabled.
387   setOperationAction(ISD::FMAD, MVT::f32, Legal);
388 
389   if (!Subtarget->hasBFI()) {
390     // fcopysign can be done in a single instruction with BFI.
391     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
392     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
393   }
394 
395   if (!Subtarget->hasBCNT(32))
396     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
397 
398   if (!Subtarget->hasBCNT(64))
399     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
400 
401   if (Subtarget->hasFFBH())
402     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
403 
404   if (Subtarget->hasFFBL())
405     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
406 
407   // We only really have 32-bit BFE instructions (and 16-bit on VI).
408   //
409   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
410   // effort to match them now. We want this to be false for i64 cases when the
411   // extraction isn't restricted to the upper or lower half. Ideally we would
412   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
413   // span the midpoint are probably relatively rare, so don't worry about them
414   // for now.
415   if (Subtarget->hasBFE())
416     setHasExtractBitsInsn(true);
417 
418   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
419   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
420   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
421   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
422 
423 
424   // These are really only legal for ieee_mode functions. We should be avoiding
425   // them for functions that don't have ieee_mode enabled, so just say they are
426   // legal.
427   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
428   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
429   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
430   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
431 
432 
433   if (Subtarget->haveRoundOpsF64()) {
434     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
435     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
436     setOperationAction(ISD::FRINT, MVT::f64, Legal);
437   } else {
438     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
439     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
440     setOperationAction(ISD::FRINT, MVT::f64, Custom);
441     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
442   }
443 
444   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
445 
446   setOperationAction(ISD::FSIN, MVT::f32, Custom);
447   setOperationAction(ISD::FCOS, MVT::f32, Custom);
448   setOperationAction(ISD::FDIV, MVT::f32, Custom);
449   setOperationAction(ISD::FDIV, MVT::f64, Custom);
450 
451   if (Subtarget->has16BitInsts()) {
452     setOperationAction(ISD::Constant, MVT::i16, Legal);
453 
454     setOperationAction(ISD::SMIN, MVT::i16, Legal);
455     setOperationAction(ISD::SMAX, MVT::i16, Legal);
456 
457     setOperationAction(ISD::UMIN, MVT::i16, Legal);
458     setOperationAction(ISD::UMAX, MVT::i16, Legal);
459 
460     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
461     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
462 
463     setOperationAction(ISD::ROTR, MVT::i16, Promote);
464     setOperationAction(ISD::ROTL, MVT::i16, Promote);
465 
466     setOperationAction(ISD::SDIV, MVT::i16, Promote);
467     setOperationAction(ISD::UDIV, MVT::i16, Promote);
468     setOperationAction(ISD::SREM, MVT::i16, Promote);
469     setOperationAction(ISD::UREM, MVT::i16, Promote);
470 
471     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
472 
473     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
474     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
475     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
476     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
477     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
478 
479     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
480 
481     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
482 
483     setOperationAction(ISD::LOAD, MVT::i16, Custom);
484 
485     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
486 
487     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
488     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
489     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
490     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
491 
492     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
493     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
494 
495     // F16 - Constant Actions.
496     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
497 
498     // F16 - Load/Store Actions.
499     setOperationAction(ISD::LOAD, MVT::f16, Promote);
500     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
501     setOperationAction(ISD::STORE, MVT::f16, Promote);
502     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
503 
504     // F16 - VOP1 Actions.
505     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
506     setOperationAction(ISD::FCOS, MVT::f16, Custom);
507     setOperationAction(ISD::FSIN, MVT::f16, Custom);
508 
509     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
510     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
511 
512     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
513     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
514     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
515     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
516     setOperationAction(ISD::FROUND, MVT::f16, Custom);
517 
518     // F16 - VOP2 Actions.
519     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
520     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
521 
522     setOperationAction(ISD::FDIV, MVT::f16, Custom);
523 
524     // F16 - VOP3 Actions.
525     setOperationAction(ISD::FMA, MVT::f16, Legal);
526     if (STI.hasMadF16())
527       setOperationAction(ISD::FMAD, MVT::f16, Legal);
528 
529     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
530       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
531         switch (Op) {
532         case ISD::LOAD:
533         case ISD::STORE:
534         case ISD::BUILD_VECTOR:
535         case ISD::BITCAST:
536         case ISD::EXTRACT_VECTOR_ELT:
537         case ISD::INSERT_VECTOR_ELT:
538         case ISD::INSERT_SUBVECTOR:
539         case ISD::EXTRACT_SUBVECTOR:
540         case ISD::SCALAR_TO_VECTOR:
541           break;
542         case ISD::CONCAT_VECTORS:
543           setOperationAction(Op, VT, Custom);
544           break;
545         default:
546           setOperationAction(Op, VT, Expand);
547           break;
548         }
549       }
550     }
551 
552     // v_perm_b32 can handle either of these.
553     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
554     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
555     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
556 
557     // XXX - Do these do anything? Vector constants turn into build_vector.
558     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
559     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
560 
561     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
562     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
563 
564     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
565     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
566     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
567     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
568 
569     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
570     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
571     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
572     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
573 
574     setOperationAction(ISD::AND, MVT::v2i16, Promote);
575     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
576     setOperationAction(ISD::OR, MVT::v2i16, Promote);
577     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
578     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
579     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
580 
581     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
582     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
583     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
584     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
585 
586     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
587     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
588     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
589     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
590 
591     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
592     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
593     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
594     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
595 
596     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
597     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
598     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
599 
600     if (!Subtarget->hasVOP3PInsts()) {
601       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
602       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
603     }
604 
605     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
606     // This isn't really legal, but this avoids the legalizer unrolling it (and
607     // allows matching fneg (fabs x) patterns)
608     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
609 
610     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
611     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
612     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
613     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
614 
615     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
616     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
617 
618     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
619     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
620   }
621 
622   if (Subtarget->hasVOP3PInsts()) {
623     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
624     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
625     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
626     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
627     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
628     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
629     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
630     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
631     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
632     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
633 
634     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
635     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
636     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
637 
638     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
639     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
640 
641     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
642 
643     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
644     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
645 
646     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
647     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
648 
649     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
650     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
651     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
652     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
653     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
654     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
655 
656     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
657     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
658     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
659     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
660 
661     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
662     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
663     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
664 
665     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
666     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
667 
668     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
669     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
670     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
671 
672     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
673     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
674     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
675   }
676 
677   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
678   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
679 
680   if (Subtarget->has16BitInsts()) {
681     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
682     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
683     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
684     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
685   } else {
686     // Legalization hack.
687     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
688     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
689 
690     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
691     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
692   }
693 
694   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
695     setOperationAction(ISD::SELECT, VT, Custom);
696   }
697 
698   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
699   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
700   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
701   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
702   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
703   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
704   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
705 
706   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
707   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
708   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
709   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
710   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
711   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
712   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
713   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
714   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
715 
716   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
717   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
718   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
719   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
720   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
721   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
722   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
723   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
724 
725   setTargetDAGCombine(ISD::ADD);
726   setTargetDAGCombine(ISD::ADDCARRY);
727   setTargetDAGCombine(ISD::SUB);
728   setTargetDAGCombine(ISD::SUBCARRY);
729   setTargetDAGCombine(ISD::FADD);
730   setTargetDAGCombine(ISD::FSUB);
731   setTargetDAGCombine(ISD::FMINNUM);
732   setTargetDAGCombine(ISD::FMAXNUM);
733   setTargetDAGCombine(ISD::FMINNUM_IEEE);
734   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
735   setTargetDAGCombine(ISD::FMA);
736   setTargetDAGCombine(ISD::SMIN);
737   setTargetDAGCombine(ISD::SMAX);
738   setTargetDAGCombine(ISD::UMIN);
739   setTargetDAGCombine(ISD::UMAX);
740   setTargetDAGCombine(ISD::SETCC);
741   setTargetDAGCombine(ISD::AND);
742   setTargetDAGCombine(ISD::OR);
743   setTargetDAGCombine(ISD::XOR);
744   setTargetDAGCombine(ISD::SINT_TO_FP);
745   setTargetDAGCombine(ISD::UINT_TO_FP);
746   setTargetDAGCombine(ISD::FCANONICALIZE);
747   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
748   setTargetDAGCombine(ISD::ZERO_EXTEND);
749   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
750   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
751   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
752 
753   // All memory operations. Some folding on the pointer operand is done to help
754   // matching the constant offsets in the addressing modes.
755   setTargetDAGCombine(ISD::LOAD);
756   setTargetDAGCombine(ISD::STORE);
757   setTargetDAGCombine(ISD::ATOMIC_LOAD);
758   setTargetDAGCombine(ISD::ATOMIC_STORE);
759   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
760   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
761   setTargetDAGCombine(ISD::ATOMIC_SWAP);
762   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
763   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
764   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
765   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
766   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
767   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
768   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
769   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
770   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
771   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
772   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
773 
774   setSchedulingPreference(Sched::RegPressure);
775 }
776 
777 const GCNSubtarget *SITargetLowering::getSubtarget() const {
778   return Subtarget;
779 }
780 
781 //===----------------------------------------------------------------------===//
782 // TargetLowering queries
783 //===----------------------------------------------------------------------===//
784 
785 // v_mad_mix* support a conversion from f16 to f32.
786 //
787 // There is only one special case when denormals are enabled we don't currently,
788 // where this is OK to use.
789 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
790                                        EVT DestVT, EVT SrcVT) const {
791   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
792           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
793     DestVT.getScalarType() == MVT::f32 &&
794     SrcVT.getScalarType() == MVT::f16 &&
795     // TODO: This probably only requires no input flushing?
796     !hasFP32Denormals(DAG.getMachineFunction());
797 }
798 
799 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
800   // SI has some legal vector types, but no legal vector operations. Say no
801   // shuffles are legal in order to prefer scalarizing some vector operations.
802   return false;
803 }
804 
805 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
806                                                     CallingConv::ID CC,
807                                                     EVT VT) const {
808   if (CC == CallingConv::AMDGPU_KERNEL)
809     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
810 
811   if (VT.isVector()) {
812     EVT ScalarVT = VT.getScalarType();
813     unsigned Size = ScalarVT.getSizeInBits();
814     if (Size == 32)
815       return ScalarVT.getSimpleVT();
816 
817     if (Size > 32)
818       return MVT::i32;
819 
820     if (Size == 16 && Subtarget->has16BitInsts())
821       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
822   } else if (VT.getSizeInBits() > 32)
823     return MVT::i32;
824 
825   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
826 }
827 
828 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
829                                                          CallingConv::ID CC,
830                                                          EVT VT) const {
831   if (CC == CallingConv::AMDGPU_KERNEL)
832     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
833 
834   if (VT.isVector()) {
835     unsigned NumElts = VT.getVectorNumElements();
836     EVT ScalarVT = VT.getScalarType();
837     unsigned Size = ScalarVT.getSizeInBits();
838 
839     if (Size == 32)
840       return NumElts;
841 
842     if (Size > 32)
843       return NumElts * ((Size + 31) / 32);
844 
845     if (Size == 16 && Subtarget->has16BitInsts())
846       return (NumElts + 1) / 2;
847   } else if (VT.getSizeInBits() > 32)
848     return (VT.getSizeInBits() + 31) / 32;
849 
850   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
851 }
852 
853 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
854   LLVMContext &Context, CallingConv::ID CC,
855   EVT VT, EVT &IntermediateVT,
856   unsigned &NumIntermediates, MVT &RegisterVT) const {
857   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
858     unsigned NumElts = VT.getVectorNumElements();
859     EVT ScalarVT = VT.getScalarType();
860     unsigned Size = ScalarVT.getSizeInBits();
861     if (Size == 32) {
862       RegisterVT = ScalarVT.getSimpleVT();
863       IntermediateVT = RegisterVT;
864       NumIntermediates = NumElts;
865       return NumIntermediates;
866     }
867 
868     if (Size > 32) {
869       RegisterVT = MVT::i32;
870       IntermediateVT = RegisterVT;
871       NumIntermediates = NumElts * ((Size + 31) / 32);
872       return NumIntermediates;
873     }
874 
875     // FIXME: We should fix the ABI to be the same on targets without 16-bit
876     // support, but unless we can properly handle 3-vectors, it will be still be
877     // inconsistent.
878     if (Size == 16 && Subtarget->has16BitInsts()) {
879       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
880       IntermediateVT = RegisterVT;
881       NumIntermediates = (NumElts + 1) / 2;
882       return NumIntermediates;
883     }
884   }
885 
886   return TargetLowering::getVectorTypeBreakdownForCallingConv(
887     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
888 }
889 
890 // Peek through TFE struct returns to only use the data size.
891 static EVT memVTFromImageReturn(Type *Ty) {
892   auto *ST = dyn_cast<StructType>(Ty);
893   if (!ST)
894     return EVT::getEVT(Ty, true);
895 
896   // Some intrinsics return an aggregate type - special case to work out the
897   // correct memVT.
898   //
899   // Only limited forms of aggregate type currently expected.
900   if (ST->getNumContainedTypes() != 2 ||
901       !ST->getContainedType(1)->isIntegerTy(32))
902     return EVT();
903   return EVT::getEVT(ST->getContainedType(0));
904 }
905 
906 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
907                                           const CallInst &CI,
908                                           MachineFunction &MF,
909                                           unsigned IntrID) const {
910   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
911           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
912     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
913                                                   (Intrinsic::ID)IntrID);
914     if (Attr.hasFnAttribute(Attribute::ReadNone))
915       return false;
916 
917     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
918 
919     if (RsrcIntr->IsImage) {
920       Info.ptrVal = MFI->getImagePSV(
921         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
922         CI.getArgOperand(RsrcIntr->RsrcArg));
923       Info.align.reset();
924     } else {
925       Info.ptrVal = MFI->getBufferPSV(
926         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
927         CI.getArgOperand(RsrcIntr->RsrcArg));
928     }
929 
930     Info.flags = MachineMemOperand::MODereferenceable;
931     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
932       Info.opc = ISD::INTRINSIC_W_CHAIN;
933       // TODO: Account for dmask reducing loaded size.
934       Info.memVT = memVTFromImageReturn(CI.getType());
935       Info.flags |= MachineMemOperand::MOLoad;
936     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
937       Info.opc = ISD::INTRINSIC_VOID;
938       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
939       Info.flags |= MachineMemOperand::MOStore;
940     } else {
941       // Atomic
942       Info.opc = ISD::INTRINSIC_W_CHAIN;
943       Info.memVT = MVT::getVT(CI.getType());
944       Info.flags = MachineMemOperand::MOLoad |
945                    MachineMemOperand::MOStore |
946                    MachineMemOperand::MODereferenceable;
947 
948       // XXX - Should this be volatile without known ordering?
949       Info.flags |= MachineMemOperand::MOVolatile;
950     }
951     return true;
952   }
953 
954   switch (IntrID) {
955   case Intrinsic::amdgcn_atomic_inc:
956   case Intrinsic::amdgcn_atomic_dec:
957   case Intrinsic::amdgcn_ds_ordered_add:
958   case Intrinsic::amdgcn_ds_ordered_swap:
959   case Intrinsic::amdgcn_ds_fadd:
960   case Intrinsic::amdgcn_ds_fmin:
961   case Intrinsic::amdgcn_ds_fmax: {
962     Info.opc = ISD::INTRINSIC_W_CHAIN;
963     Info.memVT = MVT::getVT(CI.getType());
964     Info.ptrVal = CI.getOperand(0);
965     Info.align.reset();
966     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
967 
968     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
969     if (!Vol->isZero())
970       Info.flags |= MachineMemOperand::MOVolatile;
971 
972     return true;
973   }
974   case Intrinsic::amdgcn_buffer_atomic_fadd: {
975     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
976 
977     Info.opc = ISD::INTRINSIC_VOID;
978     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
979     Info.ptrVal = MFI->getBufferPSV(
980       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
981       CI.getArgOperand(1));
982     Info.align.reset();
983     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
984 
985     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
986     if (!Vol || !Vol->isZero())
987       Info.flags |= MachineMemOperand::MOVolatile;
988 
989     return true;
990   }
991   case Intrinsic::amdgcn_global_atomic_fadd: {
992     Info.opc = ISD::INTRINSIC_VOID;
993     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
994                             ->getPointerElementType());
995     Info.ptrVal = CI.getOperand(0);
996     Info.align.reset();
997     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
998 
999     return true;
1000   }
1001   case Intrinsic::amdgcn_ds_append:
1002   case Intrinsic::amdgcn_ds_consume: {
1003     Info.opc = ISD::INTRINSIC_W_CHAIN;
1004     Info.memVT = MVT::getVT(CI.getType());
1005     Info.ptrVal = CI.getOperand(0);
1006     Info.align.reset();
1007     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1008 
1009     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1010     if (!Vol->isZero())
1011       Info.flags |= MachineMemOperand::MOVolatile;
1012 
1013     return true;
1014   }
1015   case Intrinsic::amdgcn_ds_gws_init:
1016   case Intrinsic::amdgcn_ds_gws_barrier:
1017   case Intrinsic::amdgcn_ds_gws_sema_v:
1018   case Intrinsic::amdgcn_ds_gws_sema_br:
1019   case Intrinsic::amdgcn_ds_gws_sema_p:
1020   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1021     Info.opc = ISD::INTRINSIC_VOID;
1022 
1023     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1024     Info.ptrVal =
1025         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1026 
1027     // This is an abstract access, but we need to specify a type and size.
1028     Info.memVT = MVT::i32;
1029     Info.size = 4;
1030     Info.align = Align(4);
1031 
1032     Info.flags = MachineMemOperand::MOStore;
1033     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1034       Info.flags = MachineMemOperand::MOLoad;
1035     return true;
1036   }
1037   default:
1038     return false;
1039   }
1040 }
1041 
1042 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1043                                             SmallVectorImpl<Value*> &Ops,
1044                                             Type *&AccessTy) const {
1045   switch (II->getIntrinsicID()) {
1046   case Intrinsic::amdgcn_atomic_inc:
1047   case Intrinsic::amdgcn_atomic_dec:
1048   case Intrinsic::amdgcn_ds_ordered_add:
1049   case Intrinsic::amdgcn_ds_ordered_swap:
1050   case Intrinsic::amdgcn_ds_fadd:
1051   case Intrinsic::amdgcn_ds_fmin:
1052   case Intrinsic::amdgcn_ds_fmax: {
1053     Value *Ptr = II->getArgOperand(0);
1054     AccessTy = II->getType();
1055     Ops.push_back(Ptr);
1056     return true;
1057   }
1058   default:
1059     return false;
1060   }
1061 }
1062 
1063 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1064   if (!Subtarget->hasFlatInstOffsets()) {
1065     // Flat instructions do not have offsets, and only have the register
1066     // address.
1067     return AM.BaseOffs == 0 && AM.Scale == 0;
1068   }
1069 
1070   return AM.Scale == 0 &&
1071          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1072                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1073                                   /*Signed=*/false));
1074 }
1075 
1076 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1077   if (Subtarget->hasFlatGlobalInsts())
1078     return AM.Scale == 0 &&
1079            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1080                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1081                                     /*Signed=*/true));
1082 
1083   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1084       // Assume the we will use FLAT for all global memory accesses
1085       // on VI.
1086       // FIXME: This assumption is currently wrong.  On VI we still use
1087       // MUBUF instructions for the r + i addressing mode.  As currently
1088       // implemented, the MUBUF instructions only work on buffer < 4GB.
1089       // It may be possible to support > 4GB buffers with MUBUF instructions,
1090       // by setting the stride value in the resource descriptor which would
1091       // increase the size limit to (stride * 4GB).  However, this is risky,
1092       // because it has never been validated.
1093     return isLegalFlatAddressingMode(AM);
1094   }
1095 
1096   return isLegalMUBUFAddressingMode(AM);
1097 }
1098 
1099 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1100   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1101   // additionally can do r + r + i with addr64. 32-bit has more addressing
1102   // mode options. Depending on the resource constant, it can also do
1103   // (i64 r0) + (i32 r1) * (i14 i).
1104   //
1105   // Private arrays end up using a scratch buffer most of the time, so also
1106   // assume those use MUBUF instructions. Scratch loads / stores are currently
1107   // implemented as mubuf instructions with offen bit set, so slightly
1108   // different than the normal addr64.
1109   if (!isUInt<12>(AM.BaseOffs))
1110     return false;
1111 
1112   // FIXME: Since we can split immediate into soffset and immediate offset,
1113   // would it make sense to allow any immediate?
1114 
1115   switch (AM.Scale) {
1116   case 0: // r + i or just i, depending on HasBaseReg.
1117     return true;
1118   case 1:
1119     return true; // We have r + r or r + i.
1120   case 2:
1121     if (AM.HasBaseReg) {
1122       // Reject 2 * r + r.
1123       return false;
1124     }
1125 
1126     // Allow 2 * r as r + r
1127     // Or  2 * r + i is allowed as r + r + i.
1128     return true;
1129   default: // Don't allow n * r
1130     return false;
1131   }
1132 }
1133 
1134 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1135                                              const AddrMode &AM, Type *Ty,
1136                                              unsigned AS, Instruction *I) const {
1137   // No global is ever allowed as a base.
1138   if (AM.BaseGV)
1139     return false;
1140 
1141   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1142     return isLegalGlobalAddressingMode(AM);
1143 
1144   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1145       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1146       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1147     // If the offset isn't a multiple of 4, it probably isn't going to be
1148     // correctly aligned.
1149     // FIXME: Can we get the real alignment here?
1150     if (AM.BaseOffs % 4 != 0)
1151       return isLegalMUBUFAddressingMode(AM);
1152 
1153     // There are no SMRD extloads, so if we have to do a small type access we
1154     // will use a MUBUF load.
1155     // FIXME?: We also need to do this if unaligned, but we don't know the
1156     // alignment here.
1157     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1158       return isLegalGlobalAddressingMode(AM);
1159 
1160     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1161       // SMRD instructions have an 8-bit, dword offset on SI.
1162       if (!isUInt<8>(AM.BaseOffs / 4))
1163         return false;
1164     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1165       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1166       // in 8-bits, it can use a smaller encoding.
1167       if (!isUInt<32>(AM.BaseOffs / 4))
1168         return false;
1169     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1170       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1171       if (!isUInt<20>(AM.BaseOffs))
1172         return false;
1173     } else
1174       llvm_unreachable("unhandled generation");
1175 
1176     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1177       return true;
1178 
1179     if (AM.Scale == 1 && AM.HasBaseReg)
1180       return true;
1181 
1182     return false;
1183 
1184   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1185     return isLegalMUBUFAddressingMode(AM);
1186   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1187              AS == AMDGPUAS::REGION_ADDRESS) {
1188     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1189     // field.
1190     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1191     // an 8-bit dword offset but we don't know the alignment here.
1192     if (!isUInt<16>(AM.BaseOffs))
1193       return false;
1194 
1195     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1196       return true;
1197 
1198     if (AM.Scale == 1 && AM.HasBaseReg)
1199       return true;
1200 
1201     return false;
1202   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1203              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1204     // For an unknown address space, this usually means that this is for some
1205     // reason being used for pure arithmetic, and not based on some addressing
1206     // computation. We don't have instructions that compute pointers with any
1207     // addressing modes, so treat them as having no offset like flat
1208     // instructions.
1209     return isLegalFlatAddressingMode(AM);
1210   } else {
1211     llvm_unreachable("unhandled address space");
1212   }
1213 }
1214 
1215 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1216                                         const SelectionDAG &DAG) const {
1217   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1218     return (MemVT.getSizeInBits() <= 4 * 32);
1219   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1220     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1221     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1222   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1223     return (MemVT.getSizeInBits() <= 2 * 32);
1224   }
1225   return true;
1226 }
1227 
1228 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1229     unsigned Size, unsigned AddrSpace, unsigned Align,
1230     MachineMemOperand::Flags Flags, bool *IsFast) const {
1231   if (IsFast)
1232     *IsFast = false;
1233 
1234   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1235       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1236     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1237     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1238     // with adjacent offsets.
1239     bool AlignedBy4 = (Align % 4 == 0);
1240     if (IsFast)
1241       *IsFast = AlignedBy4;
1242 
1243     return AlignedBy4;
1244   }
1245 
1246   // FIXME: We have to be conservative here and assume that flat operations
1247   // will access scratch.  If we had access to the IR function, then we
1248   // could determine if any private memory was used in the function.
1249   if (!Subtarget->hasUnalignedScratchAccess() &&
1250       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1251        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1252     bool AlignedBy4 = Align >= 4;
1253     if (IsFast)
1254       *IsFast = AlignedBy4;
1255 
1256     return AlignedBy4;
1257   }
1258 
1259   if (Subtarget->hasUnalignedBufferAccess()) {
1260     // If we have an uniform constant load, it still requires using a slow
1261     // buffer instruction if unaligned.
1262     if (IsFast) {
1263       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1264       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1265       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1266                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1267         Align >= 4 : Align != 2;
1268     }
1269 
1270     return true;
1271   }
1272 
1273   // Smaller than dword value must be aligned.
1274   if (Size < 32)
1275     return false;
1276 
1277   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1278   // byte-address are ignored, thus forcing Dword alignment.
1279   // This applies to private, global, and constant memory.
1280   if (IsFast)
1281     *IsFast = true;
1282 
1283   return Size >= 32 && Align >= 4;
1284 }
1285 
1286 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1287     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1288     bool *IsFast) const {
1289   if (IsFast)
1290     *IsFast = false;
1291 
1292   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1293   // which isn't a simple VT.
1294   // Until MVT is extended to handle this, simply check for the size and
1295   // rely on the condition below: allow accesses if the size is a multiple of 4.
1296   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1297                            VT.getStoreSize() > 16)) {
1298     return false;
1299   }
1300 
1301   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1302                                             Align, Flags, IsFast);
1303 }
1304 
1305 EVT SITargetLowering::getOptimalMemOpType(
1306     const MemOp &Op, const AttributeList &FuncAttributes) const {
1307   // FIXME: Should account for address space here.
1308 
1309   // The default fallback uses the private pointer size as a guess for a type to
1310   // use. Make sure we switch these to 64-bit accesses.
1311 
1312   if (Op.size() >= 16 &&
1313       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1314     return MVT::v4i32;
1315 
1316   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1317     return MVT::v2i32;
1318 
1319   // Use the default.
1320   return MVT::Other;
1321 }
1322 
1323 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1324                                            unsigned DestAS) const {
1325   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1326 }
1327 
1328 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1329   const MemSDNode *MemNode = cast<MemSDNode>(N);
1330   const Value *Ptr = MemNode->getMemOperand()->getValue();
1331   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1332   return I && I->getMetadata("amdgpu.noclobber");
1333 }
1334 
1335 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1336                                            unsigned DestAS) const {
1337   // Flat -> private/local is a simple truncate.
1338   // Flat -> global is no-op
1339   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1340     return true;
1341 
1342   return isNoopAddrSpaceCast(SrcAS, DestAS);
1343 }
1344 
1345 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1346   const MemSDNode *MemNode = cast<MemSDNode>(N);
1347 
1348   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1349 }
1350 
1351 TargetLoweringBase::LegalizeTypeAction
1352 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1353   int NumElts = VT.getVectorNumElements();
1354   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1355     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1356   return TargetLoweringBase::getPreferredVectorAction(VT);
1357 }
1358 
1359 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1360                                                          Type *Ty) const {
1361   // FIXME: Could be smarter if called for vector constants.
1362   return true;
1363 }
1364 
1365 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1366   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1367     switch (Op) {
1368     case ISD::LOAD:
1369     case ISD::STORE:
1370 
1371     // These operations are done with 32-bit instructions anyway.
1372     case ISD::AND:
1373     case ISD::OR:
1374     case ISD::XOR:
1375     case ISD::SELECT:
1376       // TODO: Extensions?
1377       return true;
1378     default:
1379       return false;
1380     }
1381   }
1382 
1383   // SimplifySetCC uses this function to determine whether or not it should
1384   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1385   if (VT == MVT::i1 && Op == ISD::SETCC)
1386     return false;
1387 
1388   return TargetLowering::isTypeDesirableForOp(Op, VT);
1389 }
1390 
1391 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1392                                                    const SDLoc &SL,
1393                                                    SDValue Chain,
1394                                                    uint64_t Offset) const {
1395   const DataLayout &DL = DAG.getDataLayout();
1396   MachineFunction &MF = DAG.getMachineFunction();
1397   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1398 
1399   const ArgDescriptor *InputPtrReg;
1400   const TargetRegisterClass *RC;
1401 
1402   std::tie(InputPtrReg, RC)
1403     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1404 
1405   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1406   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1407   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1408     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1409 
1410   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1411 }
1412 
1413 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1414                                             const SDLoc &SL) const {
1415   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1416                                                FIRST_IMPLICIT);
1417   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1418 }
1419 
1420 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1421                                          const SDLoc &SL, SDValue Val,
1422                                          bool Signed,
1423                                          const ISD::InputArg *Arg) const {
1424   // First, if it is a widened vector, narrow it.
1425   if (VT.isVector() &&
1426       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1427     EVT NarrowedVT =
1428         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1429                          VT.getVectorNumElements());
1430     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1431                       DAG.getConstant(0, SL, MVT::i32));
1432   }
1433 
1434   // Then convert the vector elements or scalar value.
1435   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1436       VT.bitsLT(MemVT)) {
1437     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1438     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1439   }
1440 
1441   if (MemVT.isFloatingPoint())
1442     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1443   else if (Signed)
1444     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1445   else
1446     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1447 
1448   return Val;
1449 }
1450 
1451 SDValue SITargetLowering::lowerKernargMemParameter(
1452   SelectionDAG &DAG, EVT VT, EVT MemVT,
1453   const SDLoc &SL, SDValue Chain,
1454   uint64_t Offset, unsigned Align, bool Signed,
1455   const ISD::InputArg *Arg) const {
1456   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1457 
1458   // Try to avoid using an extload by loading earlier than the argument address,
1459   // and extracting the relevant bits. The load should hopefully be merged with
1460   // the previous argument.
1461   if (MemVT.getStoreSize() < 4 && Align < 4) {
1462     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1463     int64_t AlignDownOffset = alignDown(Offset, 4);
1464     int64_t OffsetDiff = Offset - AlignDownOffset;
1465 
1466     EVT IntVT = MemVT.changeTypeToInteger();
1467 
1468     // TODO: If we passed in the base kernel offset we could have a better
1469     // alignment than 4, but we don't really need it.
1470     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1471     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1472                                MachineMemOperand::MODereferenceable |
1473                                MachineMemOperand::MOInvariant);
1474 
1475     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1476     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1477 
1478     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1479     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1480     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1481 
1482 
1483     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1484   }
1485 
1486   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1487   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1488                              MachineMemOperand::MODereferenceable |
1489                              MachineMemOperand::MOInvariant);
1490 
1491   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1492   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1493 }
1494 
1495 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1496                                               const SDLoc &SL, SDValue Chain,
1497                                               const ISD::InputArg &Arg) const {
1498   MachineFunction &MF = DAG.getMachineFunction();
1499   MachineFrameInfo &MFI = MF.getFrameInfo();
1500 
1501   if (Arg.Flags.isByVal()) {
1502     unsigned Size = Arg.Flags.getByValSize();
1503     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1504     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1505   }
1506 
1507   unsigned ArgOffset = VA.getLocMemOffset();
1508   unsigned ArgSize = VA.getValVT().getStoreSize();
1509 
1510   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1511 
1512   // Create load nodes to retrieve arguments from the stack.
1513   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1514   SDValue ArgValue;
1515 
1516   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1517   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1518   MVT MemVT = VA.getValVT();
1519 
1520   switch (VA.getLocInfo()) {
1521   default:
1522     break;
1523   case CCValAssign::BCvt:
1524     MemVT = VA.getLocVT();
1525     break;
1526   case CCValAssign::SExt:
1527     ExtType = ISD::SEXTLOAD;
1528     break;
1529   case CCValAssign::ZExt:
1530     ExtType = ISD::ZEXTLOAD;
1531     break;
1532   case CCValAssign::AExt:
1533     ExtType = ISD::EXTLOAD;
1534     break;
1535   }
1536 
1537   ArgValue = DAG.getExtLoad(
1538     ExtType, SL, VA.getLocVT(), Chain, FIN,
1539     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1540     MemVT);
1541   return ArgValue;
1542 }
1543 
1544 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1545   const SIMachineFunctionInfo &MFI,
1546   EVT VT,
1547   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1548   const ArgDescriptor *Reg;
1549   const TargetRegisterClass *RC;
1550 
1551   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1552   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1553 }
1554 
1555 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1556                                    CallingConv::ID CallConv,
1557                                    ArrayRef<ISD::InputArg> Ins,
1558                                    BitVector &Skipped,
1559                                    FunctionType *FType,
1560                                    SIMachineFunctionInfo *Info) {
1561   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1562     const ISD::InputArg *Arg = &Ins[I];
1563 
1564     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1565            "vector type argument should have been split");
1566 
1567     // First check if it's a PS input addr.
1568     if (CallConv == CallingConv::AMDGPU_PS &&
1569         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1570       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1571 
1572       // Inconveniently only the first part of the split is marked as isSplit,
1573       // so skip to the end. We only want to increment PSInputNum once for the
1574       // entire split argument.
1575       if (Arg->Flags.isSplit()) {
1576         while (!Arg->Flags.isSplitEnd()) {
1577           assert((!Arg->VT.isVector() ||
1578                   Arg->VT.getScalarSizeInBits() == 16) &&
1579                  "unexpected vector split in ps argument type");
1580           if (!SkipArg)
1581             Splits.push_back(*Arg);
1582           Arg = &Ins[++I];
1583         }
1584       }
1585 
1586       if (SkipArg) {
1587         // We can safely skip PS inputs.
1588         Skipped.set(Arg->getOrigArgIndex());
1589         ++PSInputNum;
1590         continue;
1591       }
1592 
1593       Info->markPSInputAllocated(PSInputNum);
1594       if (Arg->Used)
1595         Info->markPSInputEnabled(PSInputNum);
1596 
1597       ++PSInputNum;
1598     }
1599 
1600     Splits.push_back(*Arg);
1601   }
1602 }
1603 
1604 // Allocate special inputs passed in VGPRs.
1605 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1606                                                       MachineFunction &MF,
1607                                                       const SIRegisterInfo &TRI,
1608                                                       SIMachineFunctionInfo &Info) const {
1609   const LLT S32 = LLT::scalar(32);
1610   MachineRegisterInfo &MRI = MF.getRegInfo();
1611 
1612   if (Info.hasWorkItemIDX()) {
1613     Register Reg = AMDGPU::VGPR0;
1614     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1615 
1616     CCInfo.AllocateReg(Reg);
1617     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1618   }
1619 
1620   if (Info.hasWorkItemIDY()) {
1621     Register Reg = AMDGPU::VGPR1;
1622     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1623 
1624     CCInfo.AllocateReg(Reg);
1625     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1626   }
1627 
1628   if (Info.hasWorkItemIDZ()) {
1629     Register Reg = AMDGPU::VGPR2;
1630     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1631 
1632     CCInfo.AllocateReg(Reg);
1633     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1634   }
1635 }
1636 
1637 // Try to allocate a VGPR at the end of the argument list, or if no argument
1638 // VGPRs are left allocating a stack slot.
1639 // If \p Mask is is given it indicates bitfield position in the register.
1640 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1641 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1642                                          ArgDescriptor Arg = ArgDescriptor()) {
1643   if (Arg.isSet())
1644     return ArgDescriptor::createArg(Arg, Mask);
1645 
1646   ArrayRef<MCPhysReg> ArgVGPRs
1647     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1648   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1649   if (RegIdx == ArgVGPRs.size()) {
1650     // Spill to stack required.
1651     int64_t Offset = CCInfo.AllocateStack(4, 4);
1652 
1653     return ArgDescriptor::createStack(Offset, Mask);
1654   }
1655 
1656   unsigned Reg = ArgVGPRs[RegIdx];
1657   Reg = CCInfo.AllocateReg(Reg);
1658   assert(Reg != AMDGPU::NoRegister);
1659 
1660   MachineFunction &MF = CCInfo.getMachineFunction();
1661   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1662   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1663   return ArgDescriptor::createRegister(Reg, Mask);
1664 }
1665 
1666 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1667                                              const TargetRegisterClass *RC,
1668                                              unsigned NumArgRegs) {
1669   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1670   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1671   if (RegIdx == ArgSGPRs.size())
1672     report_fatal_error("ran out of SGPRs for arguments");
1673 
1674   unsigned Reg = ArgSGPRs[RegIdx];
1675   Reg = CCInfo.AllocateReg(Reg);
1676   assert(Reg != AMDGPU::NoRegister);
1677 
1678   MachineFunction &MF = CCInfo.getMachineFunction();
1679   MF.addLiveIn(Reg, RC);
1680   return ArgDescriptor::createRegister(Reg);
1681 }
1682 
1683 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1684   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1685 }
1686 
1687 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1688   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1689 }
1690 
1691 /// Allocate implicit function VGPR arguments at the end of allocated user
1692 /// arguments.
1693 void SITargetLowering::allocateSpecialInputVGPRs(
1694   CCState &CCInfo, MachineFunction &MF,
1695   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1696   const unsigned Mask = 0x3ff;
1697   ArgDescriptor Arg;
1698 
1699   if (Info.hasWorkItemIDX()) {
1700     Arg = allocateVGPR32Input(CCInfo, Mask);
1701     Info.setWorkItemIDX(Arg);
1702   }
1703 
1704   if (Info.hasWorkItemIDY()) {
1705     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1706     Info.setWorkItemIDY(Arg);
1707   }
1708 
1709   if (Info.hasWorkItemIDZ())
1710     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1711 }
1712 
1713 /// Allocate implicit function VGPR arguments in fixed registers.
1714 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1715   CCState &CCInfo, MachineFunction &MF,
1716   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1717   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1718   if (!Reg)
1719     report_fatal_error("failed to allocated VGPR for implicit arguments");
1720 
1721   const unsigned Mask = 0x3ff;
1722   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1723   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1724   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1725 }
1726 
1727 void SITargetLowering::allocateSpecialInputSGPRs(
1728   CCState &CCInfo,
1729   MachineFunction &MF,
1730   const SIRegisterInfo &TRI,
1731   SIMachineFunctionInfo &Info) const {
1732   auto &ArgInfo = Info.getArgInfo();
1733 
1734   // TODO: Unify handling with private memory pointers.
1735 
1736   if (Info.hasDispatchPtr())
1737     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1738 
1739   if (Info.hasQueuePtr())
1740     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1741 
1742   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1743   // constant offset from the kernarg segment.
1744   if (Info.hasImplicitArgPtr())
1745     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1746 
1747   if (Info.hasDispatchID())
1748     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1749 
1750   // flat_scratch_init is not applicable for non-kernel functions.
1751 
1752   if (Info.hasWorkGroupIDX())
1753     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1754 
1755   if (Info.hasWorkGroupIDY())
1756     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1757 
1758   if (Info.hasWorkGroupIDZ())
1759     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1760 }
1761 
1762 // Allocate special inputs passed in user SGPRs.
1763 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1764                                             MachineFunction &MF,
1765                                             const SIRegisterInfo &TRI,
1766                                             SIMachineFunctionInfo &Info) const {
1767   if (Info.hasImplicitBufferPtr()) {
1768     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1769     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1770     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1771   }
1772 
1773   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1774   if (Info.hasPrivateSegmentBuffer()) {
1775     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1776     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1777     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1778   }
1779 
1780   if (Info.hasDispatchPtr()) {
1781     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1782     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1783     CCInfo.AllocateReg(DispatchPtrReg);
1784   }
1785 
1786   if (Info.hasQueuePtr()) {
1787     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1788     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1789     CCInfo.AllocateReg(QueuePtrReg);
1790   }
1791 
1792   if (Info.hasKernargSegmentPtr()) {
1793     MachineRegisterInfo &MRI = MF.getRegInfo();
1794     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1795     CCInfo.AllocateReg(InputPtrReg);
1796 
1797     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1798     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1799   }
1800 
1801   if (Info.hasDispatchID()) {
1802     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1803     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1804     CCInfo.AllocateReg(DispatchIDReg);
1805   }
1806 
1807   if (Info.hasFlatScratchInit()) {
1808     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1809     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1810     CCInfo.AllocateReg(FlatScratchInitReg);
1811   }
1812 
1813   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1814   // these from the dispatch pointer.
1815 }
1816 
1817 // Allocate special input registers that are initialized per-wave.
1818 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1819                                            MachineFunction &MF,
1820                                            SIMachineFunctionInfo &Info,
1821                                            CallingConv::ID CallConv,
1822                                            bool IsShader) const {
1823   if (Info.hasWorkGroupIDX()) {
1824     unsigned Reg = Info.addWorkGroupIDX();
1825     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1826     CCInfo.AllocateReg(Reg);
1827   }
1828 
1829   if (Info.hasWorkGroupIDY()) {
1830     unsigned Reg = Info.addWorkGroupIDY();
1831     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1832     CCInfo.AllocateReg(Reg);
1833   }
1834 
1835   if (Info.hasWorkGroupIDZ()) {
1836     unsigned Reg = Info.addWorkGroupIDZ();
1837     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1838     CCInfo.AllocateReg(Reg);
1839   }
1840 
1841   if (Info.hasWorkGroupInfo()) {
1842     unsigned Reg = Info.addWorkGroupInfo();
1843     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1844     CCInfo.AllocateReg(Reg);
1845   }
1846 
1847   if (Info.hasPrivateSegmentWaveByteOffset()) {
1848     // Scratch wave offset passed in system SGPR.
1849     unsigned PrivateSegmentWaveByteOffsetReg;
1850 
1851     if (IsShader) {
1852       PrivateSegmentWaveByteOffsetReg =
1853         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1854 
1855       // This is true if the scratch wave byte offset doesn't have a fixed
1856       // location.
1857       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1858         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1859         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1860       }
1861     } else
1862       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1863 
1864     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1865     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1866   }
1867 }
1868 
1869 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1870                                      MachineFunction &MF,
1871                                      const SIRegisterInfo &TRI,
1872                                      SIMachineFunctionInfo &Info) {
1873   // Now that we've figured out where the scratch register inputs are, see if
1874   // should reserve the arguments and use them directly.
1875   MachineFrameInfo &MFI = MF.getFrameInfo();
1876   bool HasStackObjects = MFI.hasStackObjects();
1877   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1878 
1879   // Record that we know we have non-spill stack objects so we don't need to
1880   // check all stack objects later.
1881   if (HasStackObjects)
1882     Info.setHasNonSpillStackObjects(true);
1883 
1884   // Everything live out of a block is spilled with fast regalloc, so it's
1885   // almost certain that spilling will be required.
1886   if (TM.getOptLevel() == CodeGenOpt::None)
1887     HasStackObjects = true;
1888 
1889   // For now assume stack access is needed in any callee functions, so we need
1890   // the scratch registers to pass in.
1891   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1892 
1893   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1894     // If we have stack objects, we unquestionably need the private buffer
1895     // resource. For the Code Object V2 ABI, this will be the first 4 user
1896     // SGPR inputs. We can reserve those and use them directly.
1897 
1898     Register PrivateSegmentBufferReg =
1899         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1900     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1901   } else {
1902     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1903     // We tentatively reserve the last registers (skipping the last registers
1904     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1905     // we'll replace these with the ones immediately after those which were
1906     // really allocated. In the prologue copies will be inserted from the
1907     // argument to these reserved registers.
1908 
1909     // Without HSA, relocations are used for the scratch pointer and the
1910     // buffer resource setup is always inserted in the prologue. Scratch wave
1911     // offset is still in an input SGPR.
1912     Info.setScratchRSrcReg(ReservedBufferReg);
1913   }
1914 
1915   MachineRegisterInfo &MRI = MF.getRegInfo();
1916 
1917   // For entry functions we have to set up the stack pointer if we use it,
1918   // whereas non-entry functions get this "for free". This means there is no
1919   // intrinsic advantage to using S32 over S34 in cases where we do not have
1920   // calls but do need a frame pointer (i.e. if we are requested to have one
1921   // because frame pointer elimination is disabled). To keep things simple we
1922   // only ever use S32 as the call ABI stack pointer, and so using it does not
1923   // imply we need a separate frame pointer.
1924   //
1925   // Try to use s32 as the SP, but move it if it would interfere with input
1926   // arguments. This won't work with calls though.
1927   //
1928   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1929   // registers.
1930   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1931     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1932   } else {
1933     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1934 
1935     if (MFI.hasCalls())
1936       report_fatal_error("call in graphics shader with too many input SGPRs");
1937 
1938     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1939       if (!MRI.isLiveIn(Reg)) {
1940         Info.setStackPtrOffsetReg(Reg);
1941         break;
1942       }
1943     }
1944 
1945     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1946       report_fatal_error("failed to find register for SP");
1947   }
1948 
1949   // hasFP should be accurate for entry functions even before the frame is
1950   // finalized, because it does not rely on the known stack size, only
1951   // properties like whether variable sized objects are present.
1952   if (ST.getFrameLowering()->hasFP(MF)) {
1953     Info.setFrameOffsetReg(AMDGPU::SGPR33);
1954   }
1955 }
1956 
1957 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1958   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1959   return !Info->isEntryFunction();
1960 }
1961 
1962 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1963 
1964 }
1965 
1966 void SITargetLowering::insertCopiesSplitCSR(
1967   MachineBasicBlock *Entry,
1968   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1969   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1970 
1971   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1972   if (!IStart)
1973     return;
1974 
1975   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1976   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1977   MachineBasicBlock::iterator MBBI = Entry->begin();
1978   for (const MCPhysReg *I = IStart; *I; ++I) {
1979     const TargetRegisterClass *RC = nullptr;
1980     if (AMDGPU::SReg_64RegClass.contains(*I))
1981       RC = &AMDGPU::SGPR_64RegClass;
1982     else if (AMDGPU::SReg_32RegClass.contains(*I))
1983       RC = &AMDGPU::SGPR_32RegClass;
1984     else
1985       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1986 
1987     Register NewVR = MRI->createVirtualRegister(RC);
1988     // Create copy from CSR to a virtual register.
1989     Entry->addLiveIn(*I);
1990     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1991       .addReg(*I);
1992 
1993     // Insert the copy-back instructions right before the terminator.
1994     for (auto *Exit : Exits)
1995       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1996               TII->get(TargetOpcode::COPY), *I)
1997         .addReg(NewVR);
1998   }
1999 }
2000 
2001 SDValue SITargetLowering::LowerFormalArguments(
2002     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2003     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2004     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2005   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2006 
2007   MachineFunction &MF = DAG.getMachineFunction();
2008   const Function &Fn = MF.getFunction();
2009   FunctionType *FType = MF.getFunction().getFunctionType();
2010   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2011 
2012   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2013     DiagnosticInfoUnsupported NoGraphicsHSA(
2014         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2015     DAG.getContext()->diagnose(NoGraphicsHSA);
2016     return DAG.getEntryNode();
2017   }
2018 
2019   SmallVector<ISD::InputArg, 16> Splits;
2020   SmallVector<CCValAssign, 16> ArgLocs;
2021   BitVector Skipped(Ins.size());
2022   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2023                  *DAG.getContext());
2024 
2025   bool IsShader = AMDGPU::isShader(CallConv);
2026   bool IsKernel = AMDGPU::isKernel(CallConv);
2027   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2028 
2029   if (IsShader) {
2030     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2031 
2032     // At least one interpolation mode must be enabled or else the GPU will
2033     // hang.
2034     //
2035     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2036     // set PSInputAddr, the user wants to enable some bits after the compilation
2037     // based on run-time states. Since we can't know what the final PSInputEna
2038     // will look like, so we shouldn't do anything here and the user should take
2039     // responsibility for the correct programming.
2040     //
2041     // Otherwise, the following restrictions apply:
2042     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2043     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2044     //   enabled too.
2045     if (CallConv == CallingConv::AMDGPU_PS) {
2046       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2047            ((Info->getPSInputAddr() & 0xF) == 0 &&
2048             Info->isPSInputAllocated(11))) {
2049         CCInfo.AllocateReg(AMDGPU::VGPR0);
2050         CCInfo.AllocateReg(AMDGPU::VGPR1);
2051         Info->markPSInputAllocated(0);
2052         Info->markPSInputEnabled(0);
2053       }
2054       if (Subtarget->isAmdPalOS()) {
2055         // For isAmdPalOS, the user does not enable some bits after compilation
2056         // based on run-time states; the register values being generated here are
2057         // the final ones set in hardware. Therefore we need to apply the
2058         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2059         // a bit is set in PSInputAddr but not PSInputEnable is where the
2060         // frontend set up an input arg for a particular interpolation mode, but
2061         // nothing uses that input arg. Really we should have an earlier pass
2062         // that removes such an arg.)
2063         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2064         if ((PsInputBits & 0x7F) == 0 ||
2065             ((PsInputBits & 0xF) == 0 &&
2066              (PsInputBits >> 11 & 1)))
2067           Info->markPSInputEnabled(
2068               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2069       }
2070     }
2071 
2072     assert(!Info->hasDispatchPtr() &&
2073            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2074            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2075            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2076            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2077            !Info->hasWorkItemIDZ());
2078   } else if (IsKernel) {
2079     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2080   } else {
2081     Splits.append(Ins.begin(), Ins.end());
2082   }
2083 
2084   if (IsEntryFunc) {
2085     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2086     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2087   } else {
2088     // For the fixed ABI, pass workitem IDs in the last argument register.
2089     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2090       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2091   }
2092 
2093   if (IsKernel) {
2094     analyzeFormalArgumentsCompute(CCInfo, Ins);
2095   } else {
2096     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2097     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2098   }
2099 
2100   SmallVector<SDValue, 16> Chains;
2101 
2102   // FIXME: This is the minimum kernel argument alignment. We should improve
2103   // this to the maximum alignment of the arguments.
2104   //
2105   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2106   // kern arg offset.
2107   const unsigned KernelArgBaseAlign = 16;
2108 
2109    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2110     const ISD::InputArg &Arg = Ins[i];
2111     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2112       InVals.push_back(DAG.getUNDEF(Arg.VT));
2113       continue;
2114     }
2115 
2116     CCValAssign &VA = ArgLocs[ArgIdx++];
2117     MVT VT = VA.getLocVT();
2118 
2119     if (IsEntryFunc && VA.isMemLoc()) {
2120       VT = Ins[i].VT;
2121       EVT MemVT = VA.getLocVT();
2122 
2123       const uint64_t Offset = VA.getLocMemOffset();
2124       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2125 
2126       SDValue Arg = lowerKernargMemParameter(
2127         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2128       Chains.push_back(Arg.getValue(1));
2129 
2130       auto *ParamTy =
2131         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2132       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2133           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2134                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2135         // On SI local pointers are just offsets into LDS, so they are always
2136         // less than 16-bits.  On CI and newer they could potentially be
2137         // real pointers, so we can't guarantee their size.
2138         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2139                           DAG.getValueType(MVT::i16));
2140       }
2141 
2142       InVals.push_back(Arg);
2143       continue;
2144     } else if (!IsEntryFunc && VA.isMemLoc()) {
2145       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2146       InVals.push_back(Val);
2147       if (!Arg.Flags.isByVal())
2148         Chains.push_back(Val.getValue(1));
2149       continue;
2150     }
2151 
2152     assert(VA.isRegLoc() && "Parameter must be in a register!");
2153 
2154     Register Reg = VA.getLocReg();
2155     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2156     EVT ValVT = VA.getValVT();
2157 
2158     Reg = MF.addLiveIn(Reg, RC);
2159     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2160 
2161     if (Arg.Flags.isSRet()) {
2162       // The return object should be reasonably addressable.
2163 
2164       // FIXME: This helps when the return is a real sret. If it is a
2165       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2166       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2167       unsigned NumBits
2168         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2169       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2170         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2171     }
2172 
2173     // If this is an 8 or 16-bit value, it is really passed promoted
2174     // to 32 bits. Insert an assert[sz]ext to capture this, then
2175     // truncate to the right size.
2176     switch (VA.getLocInfo()) {
2177     case CCValAssign::Full:
2178       break;
2179     case CCValAssign::BCvt:
2180       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2181       break;
2182     case CCValAssign::SExt:
2183       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2184                         DAG.getValueType(ValVT));
2185       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2186       break;
2187     case CCValAssign::ZExt:
2188       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2189                         DAG.getValueType(ValVT));
2190       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2191       break;
2192     case CCValAssign::AExt:
2193       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2194       break;
2195     default:
2196       llvm_unreachable("Unknown loc info!");
2197     }
2198 
2199     InVals.push_back(Val);
2200   }
2201 
2202   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2203     // Special inputs come after user arguments.
2204     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2205   }
2206 
2207   // Start adding system SGPRs.
2208   if (IsEntryFunc) {
2209     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2210   } else {
2211     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2212     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2213   }
2214 
2215   auto &ArgUsageInfo =
2216     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2217   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2218 
2219   unsigned StackArgSize = CCInfo.getNextStackOffset();
2220   Info->setBytesInStackArgArea(StackArgSize);
2221 
2222   return Chains.empty() ? Chain :
2223     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2224 }
2225 
2226 // TODO: If return values can't fit in registers, we should return as many as
2227 // possible in registers before passing on stack.
2228 bool SITargetLowering::CanLowerReturn(
2229   CallingConv::ID CallConv,
2230   MachineFunction &MF, bool IsVarArg,
2231   const SmallVectorImpl<ISD::OutputArg> &Outs,
2232   LLVMContext &Context) const {
2233   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2234   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2235   // for shaders. Vector types should be explicitly handled by CC.
2236   if (AMDGPU::isEntryFunctionCC(CallConv))
2237     return true;
2238 
2239   SmallVector<CCValAssign, 16> RVLocs;
2240   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2241   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2242 }
2243 
2244 SDValue
2245 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2246                               bool isVarArg,
2247                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2248                               const SmallVectorImpl<SDValue> &OutVals,
2249                               const SDLoc &DL, SelectionDAG &DAG) const {
2250   MachineFunction &MF = DAG.getMachineFunction();
2251   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2252 
2253   if (AMDGPU::isKernel(CallConv)) {
2254     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2255                                              OutVals, DL, DAG);
2256   }
2257 
2258   bool IsShader = AMDGPU::isShader(CallConv);
2259 
2260   Info->setIfReturnsVoid(Outs.empty());
2261   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2262 
2263   // CCValAssign - represent the assignment of the return value to a location.
2264   SmallVector<CCValAssign, 48> RVLocs;
2265   SmallVector<ISD::OutputArg, 48> Splits;
2266 
2267   // CCState - Info about the registers and stack slots.
2268   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2269                  *DAG.getContext());
2270 
2271   // Analyze outgoing return values.
2272   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2273 
2274   SDValue Flag;
2275   SmallVector<SDValue, 48> RetOps;
2276   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2277 
2278   // Add return address for callable functions.
2279   if (!Info->isEntryFunction()) {
2280     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2281     SDValue ReturnAddrReg = CreateLiveInRegister(
2282       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2283 
2284     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2285         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2286         MVT::i64);
2287     Chain =
2288         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2289     Flag = Chain.getValue(1);
2290     RetOps.push_back(ReturnAddrVirtualReg);
2291   }
2292 
2293   // Copy the result values into the output registers.
2294   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2295        ++I, ++RealRVLocIdx) {
2296     CCValAssign &VA = RVLocs[I];
2297     assert(VA.isRegLoc() && "Can only return in registers!");
2298     // TODO: Partially return in registers if return values don't fit.
2299     SDValue Arg = OutVals[RealRVLocIdx];
2300 
2301     // Copied from other backends.
2302     switch (VA.getLocInfo()) {
2303     case CCValAssign::Full:
2304       break;
2305     case CCValAssign::BCvt:
2306       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2307       break;
2308     case CCValAssign::SExt:
2309       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2310       break;
2311     case CCValAssign::ZExt:
2312       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2313       break;
2314     case CCValAssign::AExt:
2315       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2316       break;
2317     default:
2318       llvm_unreachable("Unknown loc info!");
2319     }
2320 
2321     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2322     Flag = Chain.getValue(1);
2323     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2324   }
2325 
2326   // FIXME: Does sret work properly?
2327   if (!Info->isEntryFunction()) {
2328     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2329     const MCPhysReg *I =
2330       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2331     if (I) {
2332       for (; *I; ++I) {
2333         if (AMDGPU::SReg_64RegClass.contains(*I))
2334           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2335         else if (AMDGPU::SReg_32RegClass.contains(*I))
2336           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2337         else
2338           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2339       }
2340     }
2341   }
2342 
2343   // Update chain and glue.
2344   RetOps[0] = Chain;
2345   if (Flag.getNode())
2346     RetOps.push_back(Flag);
2347 
2348   unsigned Opc = AMDGPUISD::ENDPGM;
2349   if (!IsWaveEnd)
2350     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2351   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2352 }
2353 
2354 SDValue SITargetLowering::LowerCallResult(
2355     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2356     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2357     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2358     SDValue ThisVal) const {
2359   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2360 
2361   // Assign locations to each value returned by this call.
2362   SmallVector<CCValAssign, 16> RVLocs;
2363   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2364                  *DAG.getContext());
2365   CCInfo.AnalyzeCallResult(Ins, RetCC);
2366 
2367   // Copy all of the result registers out of their specified physreg.
2368   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2369     CCValAssign VA = RVLocs[i];
2370     SDValue Val;
2371 
2372     if (VA.isRegLoc()) {
2373       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2374       Chain = Val.getValue(1);
2375       InFlag = Val.getValue(2);
2376     } else if (VA.isMemLoc()) {
2377       report_fatal_error("TODO: return values in memory");
2378     } else
2379       llvm_unreachable("unknown argument location type");
2380 
2381     switch (VA.getLocInfo()) {
2382     case CCValAssign::Full:
2383       break;
2384     case CCValAssign::BCvt:
2385       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2386       break;
2387     case CCValAssign::ZExt:
2388       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2389                         DAG.getValueType(VA.getValVT()));
2390       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2391       break;
2392     case CCValAssign::SExt:
2393       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2394                         DAG.getValueType(VA.getValVT()));
2395       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2396       break;
2397     case CCValAssign::AExt:
2398       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2399       break;
2400     default:
2401       llvm_unreachable("Unknown loc info!");
2402     }
2403 
2404     InVals.push_back(Val);
2405   }
2406 
2407   return Chain;
2408 }
2409 
2410 // Add code to pass special inputs required depending on used features separate
2411 // from the explicit user arguments present in the IR.
2412 void SITargetLowering::passSpecialInputs(
2413     CallLoweringInfo &CLI,
2414     CCState &CCInfo,
2415     const SIMachineFunctionInfo &Info,
2416     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2417     SmallVectorImpl<SDValue> &MemOpChains,
2418     SDValue Chain) const {
2419   // If we don't have a call site, this was a call inserted by
2420   // legalization. These can never use special inputs.
2421   if (!CLI.CS)
2422     return;
2423 
2424   SelectionDAG &DAG = CLI.DAG;
2425   const SDLoc &DL = CLI.DL;
2426 
2427   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2428   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2429 
2430   const AMDGPUFunctionArgInfo *CalleeArgInfo
2431     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2432   if (const Function *CalleeFunc = CLI.CS.getCalledFunction()) {
2433     auto &ArgUsageInfo =
2434       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2435     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2436   }
2437 
2438   // TODO: Unify with private memory register handling. This is complicated by
2439   // the fact that at least in kernels, the input argument is not necessarily
2440   // in the same location as the input.
2441   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2442     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2443     AMDGPUFunctionArgInfo::QUEUE_PTR,
2444     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2445     AMDGPUFunctionArgInfo::DISPATCH_ID,
2446     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2447     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2448     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2449   };
2450 
2451   for (auto InputID : InputRegs) {
2452     const ArgDescriptor *OutgoingArg;
2453     const TargetRegisterClass *ArgRC;
2454 
2455     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2456     if (!OutgoingArg)
2457       continue;
2458 
2459     const ArgDescriptor *IncomingArg;
2460     const TargetRegisterClass *IncomingArgRC;
2461     std::tie(IncomingArg, IncomingArgRC)
2462       = CallerArgInfo.getPreloadedValue(InputID);
2463     assert(IncomingArgRC == ArgRC);
2464 
2465     // All special arguments are ints for now.
2466     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2467     SDValue InputReg;
2468 
2469     if (IncomingArg) {
2470       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2471     } else {
2472       // The implicit arg ptr is special because it doesn't have a corresponding
2473       // input for kernels, and is computed from the kernarg segment pointer.
2474       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2475       InputReg = getImplicitArgPtr(DAG, DL);
2476     }
2477 
2478     if (OutgoingArg->isRegister()) {
2479       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2480       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2481         report_fatal_error("failed to allocate implicit input argument");
2482     } else {
2483       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2484       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2485                                               SpecialArgOffset);
2486       MemOpChains.push_back(ArgStore);
2487     }
2488   }
2489 
2490   // Pack workitem IDs into a single register or pass it as is if already
2491   // packed.
2492   const ArgDescriptor *OutgoingArg;
2493   const TargetRegisterClass *ArgRC;
2494 
2495   std::tie(OutgoingArg, ArgRC) =
2496     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2497   if (!OutgoingArg)
2498     std::tie(OutgoingArg, ArgRC) =
2499       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2500   if (!OutgoingArg)
2501     std::tie(OutgoingArg, ArgRC) =
2502       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2503   if (!OutgoingArg)
2504     return;
2505 
2506   const ArgDescriptor *IncomingArgX
2507     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2508   const ArgDescriptor *IncomingArgY
2509     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2510   const ArgDescriptor *IncomingArgZ
2511     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2512 
2513   SDValue InputReg;
2514   SDLoc SL;
2515 
2516   // If incoming ids are not packed we need to pack them.
2517   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2518     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2519 
2520   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2521     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2522     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2523                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2524     InputReg = InputReg.getNode() ?
2525                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2526   }
2527 
2528   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2529     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2530     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2531                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2532     InputReg = InputReg.getNode() ?
2533                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2534   }
2535 
2536   if (!InputReg.getNode()) {
2537     // Workitem ids are already packed, any of present incoming arguments
2538     // will carry all required fields.
2539     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2540       IncomingArgX ? *IncomingArgX :
2541       IncomingArgY ? *IncomingArgY :
2542                      *IncomingArgZ, ~0u);
2543     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2544   }
2545 
2546   if (OutgoingArg->isRegister()) {
2547     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2548     CCInfo.AllocateReg(OutgoingArg->getRegister());
2549   } else {
2550     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2551     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2552                                             SpecialArgOffset);
2553     MemOpChains.push_back(ArgStore);
2554   }
2555 }
2556 
2557 static bool canGuaranteeTCO(CallingConv::ID CC) {
2558   return CC == CallingConv::Fast;
2559 }
2560 
2561 /// Return true if we might ever do TCO for calls with this calling convention.
2562 static bool mayTailCallThisCC(CallingConv::ID CC) {
2563   switch (CC) {
2564   case CallingConv::C:
2565     return true;
2566   default:
2567     return canGuaranteeTCO(CC);
2568   }
2569 }
2570 
2571 bool SITargetLowering::isEligibleForTailCallOptimization(
2572     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2573     const SmallVectorImpl<ISD::OutputArg> &Outs,
2574     const SmallVectorImpl<SDValue> &OutVals,
2575     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2576   if (!mayTailCallThisCC(CalleeCC))
2577     return false;
2578 
2579   MachineFunction &MF = DAG.getMachineFunction();
2580   const Function &CallerF = MF.getFunction();
2581   CallingConv::ID CallerCC = CallerF.getCallingConv();
2582   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2583   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2584 
2585   // Kernels aren't callable, and don't have a live in return address so it
2586   // doesn't make sense to do a tail call with entry functions.
2587   if (!CallerPreserved)
2588     return false;
2589 
2590   bool CCMatch = CallerCC == CalleeCC;
2591 
2592   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2593     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2594       return true;
2595     return false;
2596   }
2597 
2598   // TODO: Can we handle var args?
2599   if (IsVarArg)
2600     return false;
2601 
2602   for (const Argument &Arg : CallerF.args()) {
2603     if (Arg.hasByValAttr())
2604       return false;
2605   }
2606 
2607   LLVMContext &Ctx = *DAG.getContext();
2608 
2609   // Check that the call results are passed in the same way.
2610   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2611                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2612                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2613     return false;
2614 
2615   // The callee has to preserve all registers the caller needs to preserve.
2616   if (!CCMatch) {
2617     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2618     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2619       return false;
2620   }
2621 
2622   // Nothing more to check if the callee is taking no arguments.
2623   if (Outs.empty())
2624     return true;
2625 
2626   SmallVector<CCValAssign, 16> ArgLocs;
2627   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2628 
2629   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2630 
2631   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2632   // If the stack arguments for this call do not fit into our own save area then
2633   // the call cannot be made tail.
2634   // TODO: Is this really necessary?
2635   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2636     return false;
2637 
2638   const MachineRegisterInfo &MRI = MF.getRegInfo();
2639   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2640 }
2641 
2642 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2643   if (!CI->isTailCall())
2644     return false;
2645 
2646   const Function *ParentFn = CI->getParent()->getParent();
2647   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2648     return false;
2649   return true;
2650 }
2651 
2652 // The wave scratch offset register is used as the global base pointer.
2653 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2654                                     SmallVectorImpl<SDValue> &InVals) const {
2655   SelectionDAG &DAG = CLI.DAG;
2656   const SDLoc &DL = CLI.DL;
2657   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2658   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2659   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2660   SDValue Chain = CLI.Chain;
2661   SDValue Callee = CLI.Callee;
2662   bool &IsTailCall = CLI.IsTailCall;
2663   CallingConv::ID CallConv = CLI.CallConv;
2664   bool IsVarArg = CLI.IsVarArg;
2665   bool IsSibCall = false;
2666   bool IsThisReturn = false;
2667   MachineFunction &MF = DAG.getMachineFunction();
2668 
2669   if (Callee.isUndef() || isNullConstant(Callee)) {
2670     if (!CLI.IsTailCall) {
2671       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2672         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2673     }
2674 
2675     return Chain;
2676   }
2677 
2678   if (IsVarArg) {
2679     return lowerUnhandledCall(CLI, InVals,
2680                               "unsupported call to variadic function ");
2681   }
2682 
2683   if (!CLI.CS.getInstruction())
2684     report_fatal_error("unsupported libcall legalization");
2685 
2686   if (!AMDGPUTargetMachine::EnableFixedFunctionABI && !CLI.CS.getCalledFunction()) {
2687     return lowerUnhandledCall(CLI, InVals,
2688                               "unsupported indirect call to function ");
2689   }
2690 
2691   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2692     return lowerUnhandledCall(CLI, InVals,
2693                               "unsupported required tail call to function ");
2694   }
2695 
2696   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2697     // Note the issue is with the CC of the calling function, not of the call
2698     // itself.
2699     return lowerUnhandledCall(CLI, InVals,
2700                           "unsupported call from graphics shader of function ");
2701   }
2702 
2703   if (IsTailCall) {
2704     IsTailCall = isEligibleForTailCallOptimization(
2705       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2706     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2707       report_fatal_error("failed to perform tail call elimination on a call "
2708                          "site marked musttail");
2709     }
2710 
2711     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2712 
2713     // A sibling call is one where we're under the usual C ABI and not planning
2714     // to change that but can still do a tail call:
2715     if (!TailCallOpt && IsTailCall)
2716       IsSibCall = true;
2717 
2718     if (IsTailCall)
2719       ++NumTailCalls;
2720   }
2721 
2722   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2723   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2724   SmallVector<SDValue, 8> MemOpChains;
2725 
2726   // Analyze operands of the call, assigning locations to each operand.
2727   SmallVector<CCValAssign, 16> ArgLocs;
2728   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2729   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2730 
2731   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2732     // With a fixed ABI, allocate fixed registers before user arguments.
2733     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2734   }
2735 
2736   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2737 
2738   // Get a count of how many bytes are to be pushed on the stack.
2739   unsigned NumBytes = CCInfo.getNextStackOffset();
2740 
2741   if (IsSibCall) {
2742     // Since we're not changing the ABI to make this a tail call, the memory
2743     // operands are already available in the caller's incoming argument space.
2744     NumBytes = 0;
2745   }
2746 
2747   // FPDiff is the byte offset of the call's argument area from the callee's.
2748   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2749   // by this amount for a tail call. In a sibling call it must be 0 because the
2750   // caller will deallocate the entire stack and the callee still expects its
2751   // arguments to begin at SP+0. Completely unused for non-tail calls.
2752   int32_t FPDiff = 0;
2753   MachineFrameInfo &MFI = MF.getFrameInfo();
2754 
2755   // Adjust the stack pointer for the new arguments...
2756   // These operations are automatically eliminated by the prolog/epilog pass
2757   if (!IsSibCall) {
2758     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2759 
2760     SmallVector<SDValue, 4> CopyFromChains;
2761 
2762     // In the HSA case, this should be an identity copy.
2763     SDValue ScratchRSrcReg
2764       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2765     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2766     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2767     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2768   }
2769 
2770   MVT PtrVT = MVT::i32;
2771 
2772   // Walk the register/memloc assignments, inserting copies/loads.
2773   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2774     CCValAssign &VA = ArgLocs[i];
2775     SDValue Arg = OutVals[i];
2776 
2777     // Promote the value if needed.
2778     switch (VA.getLocInfo()) {
2779     case CCValAssign::Full:
2780       break;
2781     case CCValAssign::BCvt:
2782       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2783       break;
2784     case CCValAssign::ZExt:
2785       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2786       break;
2787     case CCValAssign::SExt:
2788       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2789       break;
2790     case CCValAssign::AExt:
2791       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2792       break;
2793     case CCValAssign::FPExt:
2794       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2795       break;
2796     default:
2797       llvm_unreachable("Unknown loc info!");
2798     }
2799 
2800     if (VA.isRegLoc()) {
2801       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2802     } else {
2803       assert(VA.isMemLoc());
2804 
2805       SDValue DstAddr;
2806       MachinePointerInfo DstInfo;
2807 
2808       unsigned LocMemOffset = VA.getLocMemOffset();
2809       int32_t Offset = LocMemOffset;
2810 
2811       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2812       MaybeAlign Alignment;
2813 
2814       if (IsTailCall) {
2815         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2816         unsigned OpSize = Flags.isByVal() ?
2817           Flags.getByValSize() : VA.getValVT().getStoreSize();
2818 
2819         // FIXME: We can have better than the minimum byval required alignment.
2820         Alignment =
2821             Flags.isByVal()
2822                 ? Flags.getNonZeroByValAlign()
2823                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2824 
2825         Offset = Offset + FPDiff;
2826         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2827 
2828         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2829         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2830 
2831         // Make sure any stack arguments overlapping with where we're storing
2832         // are loaded before this eventual operation. Otherwise they'll be
2833         // clobbered.
2834 
2835         // FIXME: Why is this really necessary? This seems to just result in a
2836         // lot of code to copy the stack and write them back to the same
2837         // locations, which are supposed to be immutable?
2838         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2839       } else {
2840         DstAddr = PtrOff;
2841         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2842         Alignment =
2843             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2844       }
2845 
2846       if (Outs[i].Flags.isByVal()) {
2847         SDValue SizeNode =
2848             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2849         SDValue Cpy =
2850             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2851                           Outs[i].Flags.getNonZeroByValAlign(),
2852                           /*isVol = */ false, /*AlwaysInline = */ true,
2853                           /*isTailCall = */ false, DstInfo,
2854                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2855 
2856         MemOpChains.push_back(Cpy);
2857       } else {
2858         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2859                                      Alignment ? Alignment->value() : 0);
2860         MemOpChains.push_back(Store);
2861       }
2862     }
2863   }
2864 
2865   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2866     // Copy special input registers after user input arguments.
2867     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2868   }
2869 
2870   if (!MemOpChains.empty())
2871     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2872 
2873   // Build a sequence of copy-to-reg nodes chained together with token chain
2874   // and flag operands which copy the outgoing args into the appropriate regs.
2875   SDValue InFlag;
2876   for (auto &RegToPass : RegsToPass) {
2877     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2878                              RegToPass.second, InFlag);
2879     InFlag = Chain.getValue(1);
2880   }
2881 
2882 
2883   SDValue PhysReturnAddrReg;
2884   if (IsTailCall) {
2885     // Since the return is being combined with the call, we need to pass on the
2886     // return address.
2887 
2888     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2889     SDValue ReturnAddrReg = CreateLiveInRegister(
2890       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2891 
2892     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2893                                         MVT::i64);
2894     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2895     InFlag = Chain.getValue(1);
2896   }
2897 
2898   // We don't usually want to end the call-sequence here because we would tidy
2899   // the frame up *after* the call, however in the ABI-changing tail-call case
2900   // we've carefully laid out the parameters so that when sp is reset they'll be
2901   // in the correct location.
2902   if (IsTailCall && !IsSibCall) {
2903     Chain = DAG.getCALLSEQ_END(Chain,
2904                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2905                                DAG.getTargetConstant(0, DL, MVT::i32),
2906                                InFlag, DL);
2907     InFlag = Chain.getValue(1);
2908   }
2909 
2910   std::vector<SDValue> Ops;
2911   Ops.push_back(Chain);
2912   Ops.push_back(Callee);
2913   // Add a redundant copy of the callee global which will not be legalized, as
2914   // we need direct access to the callee later.
2915   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
2916     const GlobalValue *GV = GSD->getGlobal();
2917     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2918   } else {
2919     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
2920   }
2921 
2922   if (IsTailCall) {
2923     // Each tail call may have to adjust the stack by a different amount, so
2924     // this information must travel along with the operation for eventual
2925     // consumption by emitEpilogue.
2926     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2927 
2928     Ops.push_back(PhysReturnAddrReg);
2929   }
2930 
2931   // Add argument registers to the end of the list so that they are known live
2932   // into the call.
2933   for (auto &RegToPass : RegsToPass) {
2934     Ops.push_back(DAG.getRegister(RegToPass.first,
2935                                   RegToPass.second.getValueType()));
2936   }
2937 
2938   // Add a register mask operand representing the call-preserved registers.
2939 
2940   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2941   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2942   assert(Mask && "Missing call preserved mask for calling convention");
2943   Ops.push_back(DAG.getRegisterMask(Mask));
2944 
2945   if (InFlag.getNode())
2946     Ops.push_back(InFlag);
2947 
2948   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2949 
2950   // If we're doing a tall call, use a TC_RETURN here rather than an
2951   // actual call instruction.
2952   if (IsTailCall) {
2953     MFI.setHasTailCall();
2954     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2955   }
2956 
2957   // Returns a chain and a flag for retval copy to use.
2958   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2959   Chain = Call.getValue(0);
2960   InFlag = Call.getValue(1);
2961 
2962   uint64_t CalleePopBytes = NumBytes;
2963   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2964                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2965                              InFlag, DL);
2966   if (!Ins.empty())
2967     InFlag = Chain.getValue(1);
2968 
2969   // Handle result values, copying them out of physregs into vregs that we
2970   // return.
2971   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2972                          InVals, IsThisReturn,
2973                          IsThisReturn ? OutVals[0] : SDValue());
2974 }
2975 
2976 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
2977                                              const MachineFunction &MF) const {
2978   Register Reg = StringSwitch<Register>(RegName)
2979     .Case("m0", AMDGPU::M0)
2980     .Case("exec", AMDGPU::EXEC)
2981     .Case("exec_lo", AMDGPU::EXEC_LO)
2982     .Case("exec_hi", AMDGPU::EXEC_HI)
2983     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2984     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2985     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2986     .Default(Register());
2987 
2988   if (Reg == AMDGPU::NoRegister) {
2989     report_fatal_error(Twine("invalid register name \""
2990                              + StringRef(RegName)  + "\"."));
2991 
2992   }
2993 
2994   if (!Subtarget->hasFlatScrRegister() &&
2995        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2996     report_fatal_error(Twine("invalid register \""
2997                              + StringRef(RegName)  + "\" for subtarget."));
2998   }
2999 
3000   switch (Reg) {
3001   case AMDGPU::M0:
3002   case AMDGPU::EXEC_LO:
3003   case AMDGPU::EXEC_HI:
3004   case AMDGPU::FLAT_SCR_LO:
3005   case AMDGPU::FLAT_SCR_HI:
3006     if (VT.getSizeInBits() == 32)
3007       return Reg;
3008     break;
3009   case AMDGPU::EXEC:
3010   case AMDGPU::FLAT_SCR:
3011     if (VT.getSizeInBits() == 64)
3012       return Reg;
3013     break;
3014   default:
3015     llvm_unreachable("missing register type checking");
3016   }
3017 
3018   report_fatal_error(Twine("invalid type for register \""
3019                            + StringRef(RegName) + "\"."));
3020 }
3021 
3022 // If kill is not the last instruction, split the block so kill is always a
3023 // proper terminator.
3024 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3025                                                     MachineBasicBlock *BB) const {
3026   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3027 
3028   MachineBasicBlock::iterator SplitPoint(&MI);
3029   ++SplitPoint;
3030 
3031   if (SplitPoint == BB->end()) {
3032     // Don't bother with a new block.
3033     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3034     return BB;
3035   }
3036 
3037   MachineFunction *MF = BB->getParent();
3038   MachineBasicBlock *SplitBB
3039     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3040 
3041   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3042   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3043 
3044   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3045   BB->addSuccessor(SplitBB);
3046 
3047   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3048   return SplitBB;
3049 }
3050 
3051 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3052 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3053 // be the first instruction in the remainder block.
3054 //
3055 /// \returns { LoopBody, Remainder }
3056 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3057 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3058   MachineFunction *MF = MBB.getParent();
3059   MachineBasicBlock::iterator I(&MI);
3060 
3061   // To insert the loop we need to split the block. Move everything after this
3062   // point to a new block, and insert a new empty block between the two.
3063   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3064   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3065   MachineFunction::iterator MBBI(MBB);
3066   ++MBBI;
3067 
3068   MF->insert(MBBI, LoopBB);
3069   MF->insert(MBBI, RemainderBB);
3070 
3071   LoopBB->addSuccessor(LoopBB);
3072   LoopBB->addSuccessor(RemainderBB);
3073 
3074   // Move the rest of the block into a new block.
3075   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3076 
3077   if (InstInLoop) {
3078     auto Next = std::next(I);
3079 
3080     // Move instruction to loop body.
3081     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3082 
3083     // Move the rest of the block.
3084     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3085   } else {
3086     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3087   }
3088 
3089   MBB.addSuccessor(LoopBB);
3090 
3091   return std::make_pair(LoopBB, RemainderBB);
3092 }
3093 
3094 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3095 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3096   MachineBasicBlock *MBB = MI.getParent();
3097   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3098   auto I = MI.getIterator();
3099   auto E = std::next(I);
3100 
3101   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3102     .addImm(0);
3103 
3104   MIBundleBuilder Bundler(*MBB, I, E);
3105   finalizeBundle(*MBB, Bundler.begin());
3106 }
3107 
3108 MachineBasicBlock *
3109 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3110                                          MachineBasicBlock *BB) const {
3111   const DebugLoc &DL = MI.getDebugLoc();
3112 
3113   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3114 
3115   MachineBasicBlock *LoopBB;
3116   MachineBasicBlock *RemainderBB;
3117   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3118 
3119   // Apparently kill flags are only valid if the def is in the same block?
3120   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3121     Src->setIsKill(false);
3122 
3123   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3124 
3125   MachineBasicBlock::iterator I = LoopBB->end();
3126 
3127   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3128     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3129 
3130   // Clear TRAP_STS.MEM_VIOL
3131   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3132     .addImm(0)
3133     .addImm(EncodedReg);
3134 
3135   bundleInstWithWaitcnt(MI);
3136 
3137   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3138 
3139   // Load and check TRAP_STS.MEM_VIOL
3140   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3141     .addImm(EncodedReg);
3142 
3143   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3144   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3145     .addReg(Reg, RegState::Kill)
3146     .addImm(0);
3147   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3148     .addMBB(LoopBB);
3149 
3150   return RemainderBB;
3151 }
3152 
3153 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3154 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3155 // will only do one iteration. In the worst case, this will loop 64 times.
3156 //
3157 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3158 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3159   const SIInstrInfo *TII,
3160   MachineRegisterInfo &MRI,
3161   MachineBasicBlock &OrigBB,
3162   MachineBasicBlock &LoopBB,
3163   const DebugLoc &DL,
3164   const MachineOperand &IdxReg,
3165   unsigned InitReg,
3166   unsigned ResultReg,
3167   unsigned PhiReg,
3168   unsigned InitSaveExecReg,
3169   int Offset,
3170   bool UseGPRIdxMode,
3171   bool IsIndirectSrc) {
3172   MachineFunction *MF = OrigBB.getParent();
3173   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3174   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3175   MachineBasicBlock::iterator I = LoopBB.begin();
3176 
3177   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3178   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3179   Register NewExec = MRI.createVirtualRegister(BoolRC);
3180   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3181   Register CondReg = MRI.createVirtualRegister(BoolRC);
3182 
3183   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3184     .addReg(InitReg)
3185     .addMBB(&OrigBB)
3186     .addReg(ResultReg)
3187     .addMBB(&LoopBB);
3188 
3189   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3190     .addReg(InitSaveExecReg)
3191     .addMBB(&OrigBB)
3192     .addReg(NewExec)
3193     .addMBB(&LoopBB);
3194 
3195   // Read the next variant <- also loop target.
3196   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3197     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3198 
3199   // Compare the just read M0 value to all possible Idx values.
3200   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3201     .addReg(CurrentIdxReg)
3202     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3203 
3204   // Update EXEC, save the original EXEC value to VCC.
3205   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3206                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3207           NewExec)
3208     .addReg(CondReg, RegState::Kill);
3209 
3210   MRI.setSimpleHint(NewExec, CondReg);
3211 
3212   if (UseGPRIdxMode) {
3213     unsigned IdxReg;
3214     if (Offset == 0) {
3215       IdxReg = CurrentIdxReg;
3216     } else {
3217       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3218       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3219         .addReg(CurrentIdxReg, RegState::Kill)
3220         .addImm(Offset);
3221     }
3222     unsigned IdxMode = IsIndirectSrc ?
3223       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3224     MachineInstr *SetOn =
3225       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3226       .addReg(IdxReg, RegState::Kill)
3227       .addImm(IdxMode);
3228     SetOn->getOperand(3).setIsUndef();
3229   } else {
3230     // Move index from VCC into M0
3231     if (Offset == 0) {
3232       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3233         .addReg(CurrentIdxReg, RegState::Kill);
3234     } else {
3235       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3236         .addReg(CurrentIdxReg, RegState::Kill)
3237         .addImm(Offset);
3238     }
3239   }
3240 
3241   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3242   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3243   MachineInstr *InsertPt =
3244     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3245                                                   : AMDGPU::S_XOR_B64_term), Exec)
3246       .addReg(Exec)
3247       .addReg(NewExec);
3248 
3249   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3250   // s_cbranch_scc0?
3251 
3252   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3253   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3254     .addMBB(&LoopBB);
3255 
3256   return InsertPt->getIterator();
3257 }
3258 
3259 // This has slightly sub-optimal regalloc when the source vector is killed by
3260 // the read. The register allocator does not understand that the kill is
3261 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3262 // subregister from it, using 1 more VGPR than necessary. This was saved when
3263 // this was expanded after register allocation.
3264 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3265                                                   MachineBasicBlock &MBB,
3266                                                   MachineInstr &MI,
3267                                                   unsigned InitResultReg,
3268                                                   unsigned PhiReg,
3269                                                   int Offset,
3270                                                   bool UseGPRIdxMode,
3271                                                   bool IsIndirectSrc) {
3272   MachineFunction *MF = MBB.getParent();
3273   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3274   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3275   MachineRegisterInfo &MRI = MF->getRegInfo();
3276   const DebugLoc &DL = MI.getDebugLoc();
3277   MachineBasicBlock::iterator I(&MI);
3278 
3279   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3280   Register DstReg = MI.getOperand(0).getReg();
3281   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3282   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3283   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3284   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3285 
3286   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3287 
3288   // Save the EXEC mask
3289   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3290     .addReg(Exec);
3291 
3292   MachineBasicBlock *LoopBB;
3293   MachineBasicBlock *RemainderBB;
3294   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3295 
3296   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3297 
3298   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3299                                       InitResultReg, DstReg, PhiReg, TmpExec,
3300                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3301   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3302   MachineFunction::iterator MBBI(LoopBB);
3303   ++MBBI;
3304   MF->insert(MBBI, LandingPad);
3305   LoopBB->removeSuccessor(RemainderBB);
3306   LandingPad->addSuccessor(RemainderBB);
3307   LoopBB->addSuccessor(LandingPad);
3308   MachineBasicBlock::iterator First = LandingPad->begin();
3309   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3310     .addReg(SaveExec);
3311 
3312   return InsPt;
3313 }
3314 
3315 // Returns subreg index, offset
3316 static std::pair<unsigned, int>
3317 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3318                             const TargetRegisterClass *SuperRC,
3319                             unsigned VecReg,
3320                             int Offset) {
3321   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3322 
3323   // Skip out of bounds offsets, or else we would end up using an undefined
3324   // register.
3325   if (Offset >= NumElts || Offset < 0)
3326     return std::make_pair(AMDGPU::sub0, Offset);
3327 
3328   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3329 }
3330 
3331 // Return true if the index is an SGPR and was set.
3332 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3333                                  MachineRegisterInfo &MRI,
3334                                  MachineInstr &MI,
3335                                  int Offset,
3336                                  bool UseGPRIdxMode,
3337                                  bool IsIndirectSrc) {
3338   MachineBasicBlock *MBB = MI.getParent();
3339   const DebugLoc &DL = MI.getDebugLoc();
3340   MachineBasicBlock::iterator I(&MI);
3341 
3342   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3343   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3344 
3345   assert(Idx->getReg() != AMDGPU::NoRegister);
3346 
3347   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3348     return false;
3349 
3350   if (UseGPRIdxMode) {
3351     unsigned IdxMode = IsIndirectSrc ?
3352       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3353     if (Offset == 0) {
3354       MachineInstr *SetOn =
3355           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3356               .add(*Idx)
3357               .addImm(IdxMode);
3358 
3359       SetOn->getOperand(3).setIsUndef();
3360     } else {
3361       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3362       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3363           .add(*Idx)
3364           .addImm(Offset);
3365       MachineInstr *SetOn =
3366         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3367         .addReg(Tmp, RegState::Kill)
3368         .addImm(IdxMode);
3369 
3370       SetOn->getOperand(3).setIsUndef();
3371     }
3372 
3373     return true;
3374   }
3375 
3376   if (Offset == 0) {
3377     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3378       .add(*Idx);
3379   } else {
3380     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3381       .add(*Idx)
3382       .addImm(Offset);
3383   }
3384 
3385   return true;
3386 }
3387 
3388 // Control flow needs to be inserted if indexing with a VGPR.
3389 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3390                                           MachineBasicBlock &MBB,
3391                                           const GCNSubtarget &ST) {
3392   const SIInstrInfo *TII = ST.getInstrInfo();
3393   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3394   MachineFunction *MF = MBB.getParent();
3395   MachineRegisterInfo &MRI = MF->getRegInfo();
3396 
3397   Register Dst = MI.getOperand(0).getReg();
3398   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3399   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3400 
3401   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3402 
3403   unsigned SubReg;
3404   std::tie(SubReg, Offset)
3405     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3406 
3407   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3408 
3409   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3410     MachineBasicBlock::iterator I(&MI);
3411     const DebugLoc &DL = MI.getDebugLoc();
3412 
3413     if (UseGPRIdxMode) {
3414       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3415       // to avoid interfering with other uses, so probably requires a new
3416       // optimization pass.
3417       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3418         .addReg(SrcReg, RegState::Undef, SubReg)
3419         .addReg(SrcReg, RegState::Implicit)
3420         .addReg(AMDGPU::M0, RegState::Implicit);
3421       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3422     } else {
3423       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3424         .addReg(SrcReg, RegState::Undef, SubReg)
3425         .addReg(SrcReg, RegState::Implicit);
3426     }
3427 
3428     MI.eraseFromParent();
3429 
3430     return &MBB;
3431   }
3432 
3433   const DebugLoc &DL = MI.getDebugLoc();
3434   MachineBasicBlock::iterator I(&MI);
3435 
3436   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3437   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3438 
3439   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3440 
3441   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3442                               Offset, UseGPRIdxMode, true);
3443   MachineBasicBlock *LoopBB = InsPt->getParent();
3444 
3445   if (UseGPRIdxMode) {
3446     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3447       .addReg(SrcReg, RegState::Undef, SubReg)
3448       .addReg(SrcReg, RegState::Implicit)
3449       .addReg(AMDGPU::M0, RegState::Implicit);
3450     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3451   } else {
3452     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3453       .addReg(SrcReg, RegState::Undef, SubReg)
3454       .addReg(SrcReg, RegState::Implicit);
3455   }
3456 
3457   MI.eraseFromParent();
3458 
3459   return LoopBB;
3460 }
3461 
3462 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3463                                           MachineBasicBlock &MBB,
3464                                           const GCNSubtarget &ST) {
3465   const SIInstrInfo *TII = ST.getInstrInfo();
3466   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3467   MachineFunction *MF = MBB.getParent();
3468   MachineRegisterInfo &MRI = MF->getRegInfo();
3469 
3470   Register Dst = MI.getOperand(0).getReg();
3471   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3472   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3473   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3474   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3475   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3476 
3477   // This can be an immediate, but will be folded later.
3478   assert(Val->getReg());
3479 
3480   unsigned SubReg;
3481   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3482                                                          SrcVec->getReg(),
3483                                                          Offset);
3484   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3485 
3486   if (Idx->getReg() == AMDGPU::NoRegister) {
3487     MachineBasicBlock::iterator I(&MI);
3488     const DebugLoc &DL = MI.getDebugLoc();
3489 
3490     assert(Offset == 0);
3491 
3492     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3493         .add(*SrcVec)
3494         .add(*Val)
3495         .addImm(SubReg);
3496 
3497     MI.eraseFromParent();
3498     return &MBB;
3499   }
3500 
3501   const MCInstrDesc &MovRelDesc
3502     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3503 
3504   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3505     MachineBasicBlock::iterator I(&MI);
3506     const DebugLoc &DL = MI.getDebugLoc();
3507     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3508       .addReg(SrcVec->getReg())
3509       .add(*Val)
3510       .addImm(SubReg);
3511     if (UseGPRIdxMode)
3512       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3513 
3514     MI.eraseFromParent();
3515     return &MBB;
3516   }
3517 
3518   if (Val->isReg())
3519     MRI.clearKillFlags(Val->getReg());
3520 
3521   const DebugLoc &DL = MI.getDebugLoc();
3522 
3523   Register PhiReg = MRI.createVirtualRegister(VecRC);
3524 
3525   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3526                               Offset, UseGPRIdxMode, false);
3527   MachineBasicBlock *LoopBB = InsPt->getParent();
3528 
3529   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3530     .addReg(PhiReg)
3531     .add(*Val)
3532     .addImm(AMDGPU::sub0);
3533   if (UseGPRIdxMode)
3534     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3535 
3536   MI.eraseFromParent();
3537   return LoopBB;
3538 }
3539 
3540 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3541   MachineInstr &MI, MachineBasicBlock *BB) const {
3542 
3543   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3544   MachineFunction *MF = BB->getParent();
3545   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3546 
3547   if (TII->isMIMG(MI)) {
3548     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3549       report_fatal_error("missing mem operand from MIMG instruction");
3550     }
3551     // Add a memoperand for mimg instructions so that they aren't assumed to
3552     // be ordered memory instuctions.
3553 
3554     return BB;
3555   }
3556 
3557   switch (MI.getOpcode()) {
3558   case AMDGPU::S_ADD_U64_PSEUDO:
3559   case AMDGPU::S_SUB_U64_PSEUDO: {
3560     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3561     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3562     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3563     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3564     const DebugLoc &DL = MI.getDebugLoc();
3565 
3566     MachineOperand &Dest = MI.getOperand(0);
3567     MachineOperand &Src0 = MI.getOperand(1);
3568     MachineOperand &Src1 = MI.getOperand(2);
3569 
3570     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3571     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3572 
3573     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3574      Src0, BoolRC, AMDGPU::sub0,
3575      &AMDGPU::SReg_32RegClass);
3576     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3577       Src0, BoolRC, AMDGPU::sub1,
3578       &AMDGPU::SReg_32RegClass);
3579 
3580     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3581       Src1, BoolRC, AMDGPU::sub0,
3582       &AMDGPU::SReg_32RegClass);
3583     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3584       Src1, BoolRC, AMDGPU::sub1,
3585       &AMDGPU::SReg_32RegClass);
3586 
3587     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3588 
3589     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3590     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3591     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3592       .add(Src0Sub0)
3593       .add(Src1Sub0);
3594     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3595       .add(Src0Sub1)
3596       .add(Src1Sub1);
3597     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3598       .addReg(DestSub0)
3599       .addImm(AMDGPU::sub0)
3600       .addReg(DestSub1)
3601       .addImm(AMDGPU::sub1);
3602     MI.eraseFromParent();
3603     return BB;
3604   }
3605   case AMDGPU::SI_INIT_M0: {
3606     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3607             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3608         .add(MI.getOperand(0));
3609     MI.eraseFromParent();
3610     return BB;
3611   }
3612   case AMDGPU::SI_INIT_EXEC:
3613     // This should be before all vector instructions.
3614     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3615             AMDGPU::EXEC)
3616         .addImm(MI.getOperand(0).getImm());
3617     MI.eraseFromParent();
3618     return BB;
3619 
3620   case AMDGPU::SI_INIT_EXEC_LO:
3621     // This should be before all vector instructions.
3622     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3623             AMDGPU::EXEC_LO)
3624         .addImm(MI.getOperand(0).getImm());
3625     MI.eraseFromParent();
3626     return BB;
3627 
3628   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3629     // Extract the thread count from an SGPR input and set EXEC accordingly.
3630     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3631     //
3632     // S_BFE_U32 count, input, {shift, 7}
3633     // S_BFM_B64 exec, count, 0
3634     // S_CMP_EQ_U32 count, 64
3635     // S_CMOV_B64 exec, -1
3636     MachineInstr *FirstMI = &*BB->begin();
3637     MachineRegisterInfo &MRI = MF->getRegInfo();
3638     Register InputReg = MI.getOperand(0).getReg();
3639     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3640     bool Found = false;
3641 
3642     // Move the COPY of the input reg to the beginning, so that we can use it.
3643     for (auto I = BB->begin(); I != &MI; I++) {
3644       if (I->getOpcode() != TargetOpcode::COPY ||
3645           I->getOperand(0).getReg() != InputReg)
3646         continue;
3647 
3648       if (I == FirstMI) {
3649         FirstMI = &*++BB->begin();
3650       } else {
3651         I->removeFromParent();
3652         BB->insert(FirstMI, &*I);
3653       }
3654       Found = true;
3655       break;
3656     }
3657     assert(Found);
3658     (void)Found;
3659 
3660     // This should be before all vector instructions.
3661     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3662     bool isWave32 = getSubtarget()->isWave32();
3663     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3664     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3665         .addReg(InputReg)
3666         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3667     BuildMI(*BB, FirstMI, DebugLoc(),
3668             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3669             Exec)
3670         .addReg(CountReg)
3671         .addImm(0);
3672     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3673         .addReg(CountReg, RegState::Kill)
3674         .addImm(getSubtarget()->getWavefrontSize());
3675     BuildMI(*BB, FirstMI, DebugLoc(),
3676             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3677             Exec)
3678         .addImm(-1);
3679     MI.eraseFromParent();
3680     return BB;
3681   }
3682 
3683   case AMDGPU::GET_GROUPSTATICSIZE: {
3684     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3685            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3686     DebugLoc DL = MI.getDebugLoc();
3687     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3688         .add(MI.getOperand(0))
3689         .addImm(MFI->getLDSSize());
3690     MI.eraseFromParent();
3691     return BB;
3692   }
3693   case AMDGPU::SI_INDIRECT_SRC_V1:
3694   case AMDGPU::SI_INDIRECT_SRC_V2:
3695   case AMDGPU::SI_INDIRECT_SRC_V4:
3696   case AMDGPU::SI_INDIRECT_SRC_V8:
3697   case AMDGPU::SI_INDIRECT_SRC_V16:
3698     return emitIndirectSrc(MI, *BB, *getSubtarget());
3699   case AMDGPU::SI_INDIRECT_DST_V1:
3700   case AMDGPU::SI_INDIRECT_DST_V2:
3701   case AMDGPU::SI_INDIRECT_DST_V4:
3702   case AMDGPU::SI_INDIRECT_DST_V8:
3703   case AMDGPU::SI_INDIRECT_DST_V16:
3704     return emitIndirectDst(MI, *BB, *getSubtarget());
3705   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3706   case AMDGPU::SI_KILL_I1_PSEUDO:
3707     return splitKillBlock(MI, BB);
3708   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3709     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3710     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3711     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3712 
3713     Register Dst = MI.getOperand(0).getReg();
3714     Register Src0 = MI.getOperand(1).getReg();
3715     Register Src1 = MI.getOperand(2).getReg();
3716     const DebugLoc &DL = MI.getDebugLoc();
3717     Register SrcCond = MI.getOperand(3).getReg();
3718 
3719     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3720     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3721     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3722     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3723 
3724     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3725       .addReg(SrcCond);
3726     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3727       .addImm(0)
3728       .addReg(Src0, 0, AMDGPU::sub0)
3729       .addImm(0)
3730       .addReg(Src1, 0, AMDGPU::sub0)
3731       .addReg(SrcCondCopy);
3732     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3733       .addImm(0)
3734       .addReg(Src0, 0, AMDGPU::sub1)
3735       .addImm(0)
3736       .addReg(Src1, 0, AMDGPU::sub1)
3737       .addReg(SrcCondCopy);
3738 
3739     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3740       .addReg(DstLo)
3741       .addImm(AMDGPU::sub0)
3742       .addReg(DstHi)
3743       .addImm(AMDGPU::sub1);
3744     MI.eraseFromParent();
3745     return BB;
3746   }
3747   case AMDGPU::SI_BR_UNDEF: {
3748     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3749     const DebugLoc &DL = MI.getDebugLoc();
3750     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3751                            .add(MI.getOperand(0));
3752     Br->getOperand(1).setIsUndef(true); // read undef SCC
3753     MI.eraseFromParent();
3754     return BB;
3755   }
3756   case AMDGPU::ADJCALLSTACKUP:
3757   case AMDGPU::ADJCALLSTACKDOWN: {
3758     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3759     MachineInstrBuilder MIB(*MF, &MI);
3760 
3761     // Add an implicit use of the frame offset reg to prevent the restore copy
3762     // inserted after the call from being reorderd after stack operations in the
3763     // the caller's frame.
3764     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3765         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3766         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3767     return BB;
3768   }
3769   case AMDGPU::SI_CALL_ISEL: {
3770     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3771     const DebugLoc &DL = MI.getDebugLoc();
3772 
3773     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3774 
3775     MachineInstrBuilder MIB;
3776     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3777 
3778     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3779       MIB.add(MI.getOperand(I));
3780 
3781     MIB.cloneMemRefs(MI);
3782     MI.eraseFromParent();
3783     return BB;
3784   }
3785   case AMDGPU::V_ADD_I32_e32:
3786   case AMDGPU::V_SUB_I32_e32:
3787   case AMDGPU::V_SUBREV_I32_e32: {
3788     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3789     const DebugLoc &DL = MI.getDebugLoc();
3790     unsigned Opc = MI.getOpcode();
3791 
3792     bool NeedClampOperand = false;
3793     if (TII->pseudoToMCOpcode(Opc) == -1) {
3794       Opc = AMDGPU::getVOPe64(Opc);
3795       NeedClampOperand = true;
3796     }
3797 
3798     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3799     if (TII->isVOP3(*I)) {
3800       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3801       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3802       I.addReg(TRI->getVCC(), RegState::Define);
3803     }
3804     I.add(MI.getOperand(1))
3805      .add(MI.getOperand(2));
3806     if (NeedClampOperand)
3807       I.addImm(0); // clamp bit for e64 encoding
3808 
3809     TII->legalizeOperands(*I);
3810 
3811     MI.eraseFromParent();
3812     return BB;
3813   }
3814   case AMDGPU::DS_GWS_INIT:
3815   case AMDGPU::DS_GWS_SEMA_V:
3816   case AMDGPU::DS_GWS_SEMA_BR:
3817   case AMDGPU::DS_GWS_SEMA_P:
3818   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3819   case AMDGPU::DS_GWS_BARRIER:
3820     // A s_waitcnt 0 is required to be the instruction immediately following.
3821     if (getSubtarget()->hasGWSAutoReplay()) {
3822       bundleInstWithWaitcnt(MI);
3823       return BB;
3824     }
3825 
3826     return emitGWSMemViolTestLoop(MI, BB);
3827   default:
3828     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3829   }
3830 }
3831 
3832 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3833   return isTypeLegal(VT.getScalarType());
3834 }
3835 
3836 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3837   // This currently forces unfolding various combinations of fsub into fma with
3838   // free fneg'd operands. As long as we have fast FMA (controlled by
3839   // isFMAFasterThanFMulAndFAdd), we should perform these.
3840 
3841   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3842   // most of these combines appear to be cycle neutral but save on instruction
3843   // count / code size.
3844   return true;
3845 }
3846 
3847 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3848                                          EVT VT) const {
3849   if (!VT.isVector()) {
3850     return MVT::i1;
3851   }
3852   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3853 }
3854 
3855 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3856   // TODO: Should i16 be used always if legal? For now it would force VALU
3857   // shifts.
3858   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3859 }
3860 
3861 // Answering this is somewhat tricky and depends on the specific device which
3862 // have different rates for fma or all f64 operations.
3863 //
3864 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3865 // regardless of which device (although the number of cycles differs between
3866 // devices), so it is always profitable for f64.
3867 //
3868 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3869 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3870 // which we can always do even without fused FP ops since it returns the same
3871 // result as the separate operations and since it is always full
3872 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3873 // however does not support denormals, so we do report fma as faster if we have
3874 // a fast fma device and require denormals.
3875 //
3876 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
3877                                                   EVT VT) const {
3878   VT = VT.getScalarType();
3879 
3880   switch (VT.getSimpleVT().SimpleTy) {
3881   case MVT::f32: {
3882     // This is as fast on some subtargets. However, we always have full rate f32
3883     // mad available which returns the same result as the separate operations
3884     // which we should prefer over fma. We can't use this if we want to support
3885     // denormals, so only report this in these cases.
3886     if (hasFP32Denormals(MF))
3887       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3888 
3889     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3890     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3891   }
3892   case MVT::f64:
3893     return true;
3894   case MVT::f16:
3895     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
3896   default:
3897     break;
3898   }
3899 
3900   return false;
3901 }
3902 
3903 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG,
3904                                               const SDNode *N) const {
3905   // TODO: Check future ftz flag
3906   // v_mad_f32/v_mac_f32 do not support denormals.
3907   EVT VT = N->getValueType(0);
3908   if (VT == MVT::f32)
3909     return !hasFP32Denormals(DAG.getMachineFunction());
3910   if (VT == MVT::f16) {
3911     return Subtarget->hasMadF16() &&
3912            !hasFP64FP16Denormals(DAG.getMachineFunction());
3913   }
3914 
3915   return false;
3916 }
3917 
3918 //===----------------------------------------------------------------------===//
3919 // Custom DAG Lowering Operations
3920 //===----------------------------------------------------------------------===//
3921 
3922 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3923 // wider vector type is legal.
3924 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3925                                              SelectionDAG &DAG) const {
3926   unsigned Opc = Op.getOpcode();
3927   EVT VT = Op.getValueType();
3928   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
3929 
3930   SDValue Lo, Hi;
3931   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3932 
3933   SDLoc SL(Op);
3934   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3935                              Op->getFlags());
3936   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3937                              Op->getFlags());
3938 
3939   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3940 }
3941 
3942 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3943 // wider vector type is legal.
3944 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3945                                               SelectionDAG &DAG) const {
3946   unsigned Opc = Op.getOpcode();
3947   EVT VT = Op.getValueType();
3948   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3949 
3950   SDValue Lo0, Hi0;
3951   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3952   SDValue Lo1, Hi1;
3953   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3954 
3955   SDLoc SL(Op);
3956 
3957   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3958                              Op->getFlags());
3959   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3960                              Op->getFlags());
3961 
3962   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3963 }
3964 
3965 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
3966                                               SelectionDAG &DAG) const {
3967   unsigned Opc = Op.getOpcode();
3968   EVT VT = Op.getValueType();
3969   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3970 
3971   SDValue Lo0, Hi0;
3972   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3973   SDValue Lo1, Hi1;
3974   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3975   SDValue Lo2, Hi2;
3976   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
3977 
3978   SDLoc SL(Op);
3979 
3980   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
3981                              Op->getFlags());
3982   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
3983                              Op->getFlags());
3984 
3985   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3986 }
3987 
3988 
3989 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3990   switch (Op.getOpcode()) {
3991   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3992   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3993   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3994   case ISD::LOAD: {
3995     SDValue Result = LowerLOAD(Op, DAG);
3996     assert((!Result.getNode() ||
3997             Result.getNode()->getNumValues() == 2) &&
3998            "Load should return a value and a chain");
3999     return Result;
4000   }
4001 
4002   case ISD::FSIN:
4003   case ISD::FCOS:
4004     return LowerTrig(Op, DAG);
4005   case ISD::SELECT: return LowerSELECT(Op, DAG);
4006   case ISD::FDIV: return LowerFDIV(Op, DAG);
4007   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4008   case ISD::STORE: return LowerSTORE(Op, DAG);
4009   case ISD::GlobalAddress: {
4010     MachineFunction &MF = DAG.getMachineFunction();
4011     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4012     return LowerGlobalAddress(MFI, Op, DAG);
4013   }
4014   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4015   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4016   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4017   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4018   case ISD::INSERT_SUBVECTOR:
4019     return lowerINSERT_SUBVECTOR(Op, DAG);
4020   case ISD::INSERT_VECTOR_ELT:
4021     return lowerINSERT_VECTOR_ELT(Op, DAG);
4022   case ISD::EXTRACT_VECTOR_ELT:
4023     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4024   case ISD::VECTOR_SHUFFLE:
4025     return lowerVECTOR_SHUFFLE(Op, DAG);
4026   case ISD::BUILD_VECTOR:
4027     return lowerBUILD_VECTOR(Op, DAG);
4028   case ISD::FP_ROUND:
4029     return lowerFP_ROUND(Op, DAG);
4030   case ISD::TRAP:
4031     return lowerTRAP(Op, DAG);
4032   case ISD::DEBUGTRAP:
4033     return lowerDEBUGTRAP(Op, DAG);
4034   case ISD::FABS:
4035   case ISD::FNEG:
4036   case ISD::FCANONICALIZE:
4037   case ISD::BSWAP:
4038     return splitUnaryVectorOp(Op, DAG);
4039   case ISD::FMINNUM:
4040   case ISD::FMAXNUM:
4041     return lowerFMINNUM_FMAXNUM(Op, DAG);
4042   case ISD::FMA:
4043     return splitTernaryVectorOp(Op, DAG);
4044   case ISD::SHL:
4045   case ISD::SRA:
4046   case ISD::SRL:
4047   case ISD::ADD:
4048   case ISD::SUB:
4049   case ISD::MUL:
4050   case ISD::SMIN:
4051   case ISD::SMAX:
4052   case ISD::UMIN:
4053   case ISD::UMAX:
4054   case ISD::FADD:
4055   case ISD::FMUL:
4056   case ISD::FMINNUM_IEEE:
4057   case ISD::FMAXNUM_IEEE:
4058     return splitBinaryVectorOp(Op, DAG);
4059   }
4060   return SDValue();
4061 }
4062 
4063 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4064                                        const SDLoc &DL,
4065                                        SelectionDAG &DAG, bool Unpacked) {
4066   if (!LoadVT.isVector())
4067     return Result;
4068 
4069   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4070     // Truncate to v2i16/v4i16.
4071     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4072 
4073     // Workaround legalizer not scalarizing truncate after vector op
4074     // legalization byt not creating intermediate vector trunc.
4075     SmallVector<SDValue, 4> Elts;
4076     DAG.ExtractVectorElements(Result, Elts);
4077     for (SDValue &Elt : Elts)
4078       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4079 
4080     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4081 
4082     // Bitcast to original type (v2f16/v4f16).
4083     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4084   }
4085 
4086   // Cast back to the original packed type.
4087   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4088 }
4089 
4090 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4091                                               MemSDNode *M,
4092                                               SelectionDAG &DAG,
4093                                               ArrayRef<SDValue> Ops,
4094                                               bool IsIntrinsic) const {
4095   SDLoc DL(M);
4096 
4097   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4098   EVT LoadVT = M->getValueType(0);
4099 
4100   EVT EquivLoadVT = LoadVT;
4101   if (Unpacked && LoadVT.isVector()) {
4102     EquivLoadVT = LoadVT.isVector() ?
4103       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4104                        LoadVT.getVectorNumElements()) : LoadVT;
4105   }
4106 
4107   // Change from v4f16/v2f16 to EquivLoadVT.
4108   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4109 
4110   SDValue Load
4111     = DAG.getMemIntrinsicNode(
4112       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4113       VTList, Ops, M->getMemoryVT(),
4114       M->getMemOperand());
4115   if (!Unpacked) // Just adjusted the opcode.
4116     return Load;
4117 
4118   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4119 
4120   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4121 }
4122 
4123 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4124                                              SelectionDAG &DAG,
4125                                              ArrayRef<SDValue> Ops) const {
4126   SDLoc DL(M);
4127   EVT LoadVT = M->getValueType(0);
4128   EVT EltType = LoadVT.getScalarType();
4129   EVT IntVT = LoadVT.changeTypeToInteger();
4130 
4131   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4132 
4133   unsigned Opc =
4134       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4135 
4136   if (IsD16) {
4137     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4138   }
4139 
4140   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4141   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4142     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4143 
4144   if (isTypeLegal(LoadVT)) {
4145     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4146                                M->getMemOperand(), DAG);
4147   }
4148 
4149   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4150   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4151   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4152                                         M->getMemOperand(), DAG);
4153   return DAG.getMergeValues(
4154       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4155       DL);
4156 }
4157 
4158 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4159                                   SDNode *N, SelectionDAG &DAG) {
4160   EVT VT = N->getValueType(0);
4161   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4162   int CondCode = CD->getSExtValue();
4163   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4164       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4165     return DAG.getUNDEF(VT);
4166 
4167   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4168 
4169   SDValue LHS = N->getOperand(1);
4170   SDValue RHS = N->getOperand(2);
4171 
4172   SDLoc DL(N);
4173 
4174   EVT CmpVT = LHS.getValueType();
4175   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4176     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4177       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4178     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4179     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4180   }
4181 
4182   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4183 
4184   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4185   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4186 
4187   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4188                               DAG.getCondCode(CCOpcode));
4189   if (VT.bitsEq(CCVT))
4190     return SetCC;
4191   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4192 }
4193 
4194 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4195                                   SDNode *N, SelectionDAG &DAG) {
4196   EVT VT = N->getValueType(0);
4197   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4198 
4199   int CondCode = CD->getSExtValue();
4200   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4201       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4202     return DAG.getUNDEF(VT);
4203   }
4204 
4205   SDValue Src0 = N->getOperand(1);
4206   SDValue Src1 = N->getOperand(2);
4207   EVT CmpVT = Src0.getValueType();
4208   SDLoc SL(N);
4209 
4210   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4211     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4212     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4213   }
4214 
4215   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4216   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4217   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4218   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4219   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4220                               Src1, DAG.getCondCode(CCOpcode));
4221   if (VT.bitsEq(CCVT))
4222     return SetCC;
4223   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4224 }
4225 
4226 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4227                                           SmallVectorImpl<SDValue> &Results,
4228                                           SelectionDAG &DAG) const {
4229   switch (N->getOpcode()) {
4230   case ISD::INSERT_VECTOR_ELT: {
4231     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4232       Results.push_back(Res);
4233     return;
4234   }
4235   case ISD::EXTRACT_VECTOR_ELT: {
4236     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4237       Results.push_back(Res);
4238     return;
4239   }
4240   case ISD::INTRINSIC_WO_CHAIN: {
4241     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4242     switch (IID) {
4243     case Intrinsic::amdgcn_cvt_pkrtz: {
4244       SDValue Src0 = N->getOperand(1);
4245       SDValue Src1 = N->getOperand(2);
4246       SDLoc SL(N);
4247       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4248                                 Src0, Src1);
4249       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4250       return;
4251     }
4252     case Intrinsic::amdgcn_cvt_pknorm_i16:
4253     case Intrinsic::amdgcn_cvt_pknorm_u16:
4254     case Intrinsic::amdgcn_cvt_pk_i16:
4255     case Intrinsic::amdgcn_cvt_pk_u16: {
4256       SDValue Src0 = N->getOperand(1);
4257       SDValue Src1 = N->getOperand(2);
4258       SDLoc SL(N);
4259       unsigned Opcode;
4260 
4261       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4262         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4263       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4264         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4265       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4266         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4267       else
4268         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4269 
4270       EVT VT = N->getValueType(0);
4271       if (isTypeLegal(VT))
4272         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4273       else {
4274         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4275         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4276       }
4277       return;
4278     }
4279     }
4280     break;
4281   }
4282   case ISD::INTRINSIC_W_CHAIN: {
4283     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4284       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4285         // FIXME: Hacky
4286         Results.push_back(Res.getOperand(0));
4287         Results.push_back(Res.getOperand(1));
4288       } else {
4289         Results.push_back(Res);
4290         Results.push_back(Res.getValue(1));
4291       }
4292       return;
4293     }
4294 
4295     break;
4296   }
4297   case ISD::SELECT: {
4298     SDLoc SL(N);
4299     EVT VT = N->getValueType(0);
4300     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4301     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4302     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4303 
4304     EVT SelectVT = NewVT;
4305     if (NewVT.bitsLT(MVT::i32)) {
4306       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4307       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4308       SelectVT = MVT::i32;
4309     }
4310 
4311     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4312                                     N->getOperand(0), LHS, RHS);
4313 
4314     if (NewVT != SelectVT)
4315       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4316     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4317     return;
4318   }
4319   case ISD::FNEG: {
4320     if (N->getValueType(0) != MVT::v2f16)
4321       break;
4322 
4323     SDLoc SL(N);
4324     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4325 
4326     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4327                              BC,
4328                              DAG.getConstant(0x80008000, SL, MVT::i32));
4329     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4330     return;
4331   }
4332   case ISD::FABS: {
4333     if (N->getValueType(0) != MVT::v2f16)
4334       break;
4335 
4336     SDLoc SL(N);
4337     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4338 
4339     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4340                              BC,
4341                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4342     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4343     return;
4344   }
4345   default:
4346     break;
4347   }
4348 }
4349 
4350 /// Helper function for LowerBRCOND
4351 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4352 
4353   SDNode *Parent = Value.getNode();
4354   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4355        I != E; ++I) {
4356 
4357     if (I.getUse().get() != Value)
4358       continue;
4359 
4360     if (I->getOpcode() == Opcode)
4361       return *I;
4362   }
4363   return nullptr;
4364 }
4365 
4366 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4367   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4368     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4369     case Intrinsic::amdgcn_if:
4370       return AMDGPUISD::IF;
4371     case Intrinsic::amdgcn_else:
4372       return AMDGPUISD::ELSE;
4373     case Intrinsic::amdgcn_loop:
4374       return AMDGPUISD::LOOP;
4375     case Intrinsic::amdgcn_end_cf:
4376       llvm_unreachable("should not occur");
4377     default:
4378       return 0;
4379     }
4380   }
4381 
4382   // break, if_break, else_break are all only used as inputs to loop, not
4383   // directly as branch conditions.
4384   return 0;
4385 }
4386 
4387 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4388   const Triple &TT = getTargetMachine().getTargetTriple();
4389   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4390           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4391          AMDGPU::shouldEmitConstantsToTextSection(TT);
4392 }
4393 
4394 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4395   // FIXME: Either avoid relying on address space here or change the default
4396   // address space for functions to avoid the explicit check.
4397   return (GV->getValueType()->isFunctionTy() ||
4398           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4399          !shouldEmitFixup(GV) &&
4400          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4401 }
4402 
4403 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4404   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4405 }
4406 
4407 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4408   if (!GV->hasExternalLinkage())
4409     return true;
4410 
4411   const auto OS = getTargetMachine().getTargetTriple().getOS();
4412   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4413 }
4414 
4415 /// This transforms the control flow intrinsics to get the branch destination as
4416 /// last parameter, also switches branch target with BR if the need arise
4417 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4418                                       SelectionDAG &DAG) const {
4419   SDLoc DL(BRCOND);
4420 
4421   SDNode *Intr = BRCOND.getOperand(1).getNode();
4422   SDValue Target = BRCOND.getOperand(2);
4423   SDNode *BR = nullptr;
4424   SDNode *SetCC = nullptr;
4425 
4426   if (Intr->getOpcode() == ISD::SETCC) {
4427     // As long as we negate the condition everything is fine
4428     SetCC = Intr;
4429     Intr = SetCC->getOperand(0).getNode();
4430 
4431   } else {
4432     // Get the target from BR if we don't negate the condition
4433     BR = findUser(BRCOND, ISD::BR);
4434     Target = BR->getOperand(1);
4435   }
4436 
4437   // FIXME: This changes the types of the intrinsics instead of introducing new
4438   // nodes with the correct types.
4439   // e.g. llvm.amdgcn.loop
4440 
4441   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4442   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4443 
4444   unsigned CFNode = isCFIntrinsic(Intr);
4445   if (CFNode == 0) {
4446     // This is a uniform branch so we don't need to legalize.
4447     return BRCOND;
4448   }
4449 
4450   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4451                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4452 
4453   assert(!SetCC ||
4454         (SetCC->getConstantOperandVal(1) == 1 &&
4455          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4456                                                              ISD::SETNE));
4457 
4458   // operands of the new intrinsic call
4459   SmallVector<SDValue, 4> Ops;
4460   if (HaveChain)
4461     Ops.push_back(BRCOND.getOperand(0));
4462 
4463   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4464   Ops.push_back(Target);
4465 
4466   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4467 
4468   // build the new intrinsic call
4469   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4470 
4471   if (!HaveChain) {
4472     SDValue Ops[] =  {
4473       SDValue(Result, 0),
4474       BRCOND.getOperand(0)
4475     };
4476 
4477     Result = DAG.getMergeValues(Ops, DL).getNode();
4478   }
4479 
4480   if (BR) {
4481     // Give the branch instruction our target
4482     SDValue Ops[] = {
4483       BR->getOperand(0),
4484       BRCOND.getOperand(2)
4485     };
4486     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4487     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4488     BR = NewBR.getNode();
4489   }
4490 
4491   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4492 
4493   // Copy the intrinsic results to registers
4494   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4495     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4496     if (!CopyToReg)
4497       continue;
4498 
4499     Chain = DAG.getCopyToReg(
4500       Chain, DL,
4501       CopyToReg->getOperand(1),
4502       SDValue(Result, i - 1),
4503       SDValue());
4504 
4505     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4506   }
4507 
4508   // Remove the old intrinsic from the chain
4509   DAG.ReplaceAllUsesOfValueWith(
4510     SDValue(Intr, Intr->getNumValues() - 1),
4511     Intr->getOperand(0));
4512 
4513   return Chain;
4514 }
4515 
4516 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4517                                           SelectionDAG &DAG) const {
4518   MVT VT = Op.getSimpleValueType();
4519   SDLoc DL(Op);
4520   // Checking the depth
4521   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4522     return DAG.getConstant(0, DL, VT);
4523 
4524   MachineFunction &MF = DAG.getMachineFunction();
4525   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4526   // Check for kernel and shader functions
4527   if (Info->isEntryFunction())
4528     return DAG.getConstant(0, DL, VT);
4529 
4530   MachineFrameInfo &MFI = MF.getFrameInfo();
4531   // There is a call to @llvm.returnaddress in this function
4532   MFI.setReturnAddressIsTaken(true);
4533 
4534   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4535   // Get the return address reg and mark it as an implicit live-in
4536   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4537 
4538   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4539 }
4540 
4541 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4542                                             SDValue Op,
4543                                             const SDLoc &DL,
4544                                             EVT VT) const {
4545   return Op.getValueType().bitsLE(VT) ?
4546       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4547     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4548                 DAG.getTargetConstant(0, DL, MVT::i32));
4549 }
4550 
4551 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4552   assert(Op.getValueType() == MVT::f16 &&
4553          "Do not know how to custom lower FP_ROUND for non-f16 type");
4554 
4555   SDValue Src = Op.getOperand(0);
4556   EVT SrcVT = Src.getValueType();
4557   if (SrcVT != MVT::f64)
4558     return Op;
4559 
4560   SDLoc DL(Op);
4561 
4562   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4563   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4564   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4565 }
4566 
4567 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4568                                                SelectionDAG &DAG) const {
4569   EVT VT = Op.getValueType();
4570   const MachineFunction &MF = DAG.getMachineFunction();
4571   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4572   bool IsIEEEMode = Info->getMode().IEEE;
4573 
4574   // FIXME: Assert during selection that this is only selected for
4575   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4576   // mode functions, but this happens to be OK since it's only done in cases
4577   // where there is known no sNaN.
4578   if (IsIEEEMode)
4579     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4580 
4581   if (VT == MVT::v4f16)
4582     return splitBinaryVectorOp(Op, DAG);
4583   return Op;
4584 }
4585 
4586 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4587   SDLoc SL(Op);
4588   SDValue Chain = Op.getOperand(0);
4589 
4590   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4591       !Subtarget->isTrapHandlerEnabled())
4592     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4593 
4594   MachineFunction &MF = DAG.getMachineFunction();
4595   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4596   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4597   assert(UserSGPR != AMDGPU::NoRegister);
4598   SDValue QueuePtr = CreateLiveInRegister(
4599     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4600   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4601   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4602                                    QueuePtr, SDValue());
4603   SDValue Ops[] = {
4604     ToReg,
4605     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4606     SGPR01,
4607     ToReg.getValue(1)
4608   };
4609   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4610 }
4611 
4612 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4613   SDLoc SL(Op);
4614   SDValue Chain = Op.getOperand(0);
4615   MachineFunction &MF = DAG.getMachineFunction();
4616 
4617   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4618       !Subtarget->isTrapHandlerEnabled()) {
4619     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4620                                      "debugtrap handler not supported",
4621                                      Op.getDebugLoc(),
4622                                      DS_Warning);
4623     LLVMContext &Ctx = MF.getFunction().getContext();
4624     Ctx.diagnose(NoTrap);
4625     return Chain;
4626   }
4627 
4628   SDValue Ops[] = {
4629     Chain,
4630     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4631   };
4632   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4633 }
4634 
4635 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4636                                              SelectionDAG &DAG) const {
4637   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4638   if (Subtarget->hasApertureRegs()) {
4639     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4640         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4641         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4642     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4643         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4644         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4645     unsigned Encoding =
4646         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4647         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4648         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4649 
4650     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4651     SDValue ApertureReg = SDValue(
4652         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4653     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4654     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4655   }
4656 
4657   MachineFunction &MF = DAG.getMachineFunction();
4658   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4659   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4660   assert(UserSGPR != AMDGPU::NoRegister);
4661 
4662   SDValue QueuePtr = CreateLiveInRegister(
4663     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4664 
4665   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4666   // private_segment_aperture_base_hi.
4667   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4668 
4669   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4670 
4671   // TODO: Use custom target PseudoSourceValue.
4672   // TODO: We should use the value from the IR intrinsic call, but it might not
4673   // be available and how do we get it?
4674   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4675   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4676                      MinAlign(64, StructOffset),
4677                      MachineMemOperand::MODereferenceable |
4678                          MachineMemOperand::MOInvariant);
4679 }
4680 
4681 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4682                                              SelectionDAG &DAG) const {
4683   SDLoc SL(Op);
4684   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4685 
4686   SDValue Src = ASC->getOperand(0);
4687   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4688 
4689   const AMDGPUTargetMachine &TM =
4690     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4691 
4692   // flat -> local/private
4693   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4694     unsigned DestAS = ASC->getDestAddressSpace();
4695 
4696     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4697         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4698       unsigned NullVal = TM.getNullPointerValue(DestAS);
4699       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4700       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4701       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4702 
4703       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4704                          NonNull, Ptr, SegmentNullPtr);
4705     }
4706   }
4707 
4708   // local/private -> flat
4709   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4710     unsigned SrcAS = ASC->getSrcAddressSpace();
4711 
4712     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4713         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4714       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4715       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4716 
4717       SDValue NonNull
4718         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4719 
4720       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4721       SDValue CvtPtr
4722         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4723 
4724       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4725                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4726                          FlatNullPtr);
4727     }
4728   }
4729 
4730   // global <-> flat are no-ops and never emitted.
4731 
4732   const MachineFunction &MF = DAG.getMachineFunction();
4733   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4734     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4735   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4736 
4737   return DAG.getUNDEF(ASC->getValueType(0));
4738 }
4739 
4740 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4741 // the small vector and inserting them into the big vector. That is better than
4742 // the default expansion of doing it via a stack slot. Even though the use of
4743 // the stack slot would be optimized away afterwards, the stack slot itself
4744 // remains.
4745 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4746                                                 SelectionDAG &DAG) const {
4747   SDValue Vec = Op.getOperand(0);
4748   SDValue Ins = Op.getOperand(1);
4749   SDValue Idx = Op.getOperand(2);
4750   EVT VecVT = Vec.getValueType();
4751   EVT InsVT = Ins.getValueType();
4752   EVT EltVT = VecVT.getVectorElementType();
4753   unsigned InsNumElts = InsVT.getVectorNumElements();
4754   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4755   SDLoc SL(Op);
4756 
4757   for (unsigned I = 0; I != InsNumElts; ++I) {
4758     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4759                               DAG.getConstant(I, SL, MVT::i32));
4760     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4761                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4762   }
4763   return Vec;
4764 }
4765 
4766 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4767                                                  SelectionDAG &DAG) const {
4768   SDValue Vec = Op.getOperand(0);
4769   SDValue InsVal = Op.getOperand(1);
4770   SDValue Idx = Op.getOperand(2);
4771   EVT VecVT = Vec.getValueType();
4772   EVT EltVT = VecVT.getVectorElementType();
4773   unsigned VecSize = VecVT.getSizeInBits();
4774   unsigned EltSize = EltVT.getSizeInBits();
4775 
4776 
4777   assert(VecSize <= 64);
4778 
4779   unsigned NumElts = VecVT.getVectorNumElements();
4780   SDLoc SL(Op);
4781   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4782 
4783   if (NumElts == 4 && EltSize == 16 && KIdx) {
4784     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4785 
4786     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4787                                  DAG.getConstant(0, SL, MVT::i32));
4788     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4789                                  DAG.getConstant(1, SL, MVT::i32));
4790 
4791     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4792     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4793 
4794     unsigned Idx = KIdx->getZExtValue();
4795     bool InsertLo = Idx < 2;
4796     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4797       InsertLo ? LoVec : HiVec,
4798       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4799       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4800 
4801     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4802 
4803     SDValue Concat = InsertLo ?
4804       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4805       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4806 
4807     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4808   }
4809 
4810   if (isa<ConstantSDNode>(Idx))
4811     return SDValue();
4812 
4813   MVT IntVT = MVT::getIntegerVT(VecSize);
4814 
4815   // Avoid stack access for dynamic indexing.
4816   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4817 
4818   // Create a congruent vector with the target value in each element so that
4819   // the required element can be masked and ORed into the target vector.
4820   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4821                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4822 
4823   assert(isPowerOf2_32(EltSize));
4824   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4825 
4826   // Convert vector index to bit-index.
4827   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4828 
4829   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4830   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4831                             DAG.getConstant(0xffff, SL, IntVT),
4832                             ScaledIdx);
4833 
4834   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4835   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4836                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4837 
4838   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4839   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4840 }
4841 
4842 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4843                                                   SelectionDAG &DAG) const {
4844   SDLoc SL(Op);
4845 
4846   EVT ResultVT = Op.getValueType();
4847   SDValue Vec = Op.getOperand(0);
4848   SDValue Idx = Op.getOperand(1);
4849   EVT VecVT = Vec.getValueType();
4850   unsigned VecSize = VecVT.getSizeInBits();
4851   EVT EltVT = VecVT.getVectorElementType();
4852   assert(VecSize <= 64);
4853 
4854   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4855 
4856   // Make sure we do any optimizations that will make it easier to fold
4857   // source modifiers before obscuring it with bit operations.
4858 
4859   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4860   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4861     return Combined;
4862 
4863   unsigned EltSize = EltVT.getSizeInBits();
4864   assert(isPowerOf2_32(EltSize));
4865 
4866   MVT IntVT = MVT::getIntegerVT(VecSize);
4867   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4868 
4869   // Convert vector index to bit-index (* EltSize)
4870   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4871 
4872   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4873   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4874 
4875   if (ResultVT == MVT::f16) {
4876     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4877     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4878   }
4879 
4880   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4881 }
4882 
4883 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4884   assert(Elt % 2 == 0);
4885   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4886 }
4887 
4888 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4889                                               SelectionDAG &DAG) const {
4890   SDLoc SL(Op);
4891   EVT ResultVT = Op.getValueType();
4892   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4893 
4894   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4895   EVT EltVT = PackVT.getVectorElementType();
4896   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4897 
4898   // vector_shuffle <0,1,6,7> lhs, rhs
4899   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4900   //
4901   // vector_shuffle <6,7,2,3> lhs, rhs
4902   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4903   //
4904   // vector_shuffle <6,7,0,1> lhs, rhs
4905   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4906 
4907   // Avoid scalarizing when both halves are reading from consecutive elements.
4908   SmallVector<SDValue, 4> Pieces;
4909   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4910     if (elementPairIsContiguous(SVN->getMask(), I)) {
4911       const int Idx = SVN->getMaskElt(I);
4912       int VecIdx = Idx < SrcNumElts ? 0 : 1;
4913       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4914       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4915                                     PackVT, SVN->getOperand(VecIdx),
4916                                     DAG.getConstant(EltIdx, SL, MVT::i32));
4917       Pieces.push_back(SubVec);
4918     } else {
4919       const int Idx0 = SVN->getMaskElt(I);
4920       const int Idx1 = SVN->getMaskElt(I + 1);
4921       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4922       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
4923       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
4924       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
4925 
4926       SDValue Vec0 = SVN->getOperand(VecIdx0);
4927       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4928                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
4929 
4930       SDValue Vec1 = SVN->getOperand(VecIdx1);
4931       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4932                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
4933       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
4934     }
4935   }
4936 
4937   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
4938 }
4939 
4940 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4941                                             SelectionDAG &DAG) const {
4942   SDLoc SL(Op);
4943   EVT VT = Op.getValueType();
4944 
4945   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4946     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4947 
4948     // Turn into pair of packed build_vectors.
4949     // TODO: Special case for constants that can be materialized with s_mov_b64.
4950     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4951                                     { Op.getOperand(0), Op.getOperand(1) });
4952     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4953                                     { Op.getOperand(2), Op.getOperand(3) });
4954 
4955     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4956     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4957 
4958     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4959     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4960   }
4961 
4962   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4963   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4964 
4965   SDValue Lo = Op.getOperand(0);
4966   SDValue Hi = Op.getOperand(1);
4967 
4968   // Avoid adding defined bits with the zero_extend.
4969   if (Hi.isUndef()) {
4970     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4971     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4972     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4973   }
4974 
4975   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4976   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4977 
4978   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4979                               DAG.getConstant(16, SL, MVT::i32));
4980   if (Lo.isUndef())
4981     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4982 
4983   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4984   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4985 
4986   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4987   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4988 }
4989 
4990 bool
4991 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4992   // We can fold offsets for anything that doesn't require a GOT relocation.
4993   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4994           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4995           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4996          !shouldEmitGOTReloc(GA->getGlobal());
4997 }
4998 
4999 static SDValue
5000 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5001                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5002                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5003   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5004   // lowered to the following code sequence:
5005   //
5006   // For constant address space:
5007   //   s_getpc_b64 s[0:1]
5008   //   s_add_u32 s0, s0, $symbol
5009   //   s_addc_u32 s1, s1, 0
5010   //
5011   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5012   //   a fixup or relocation is emitted to replace $symbol with a literal
5013   //   constant, which is a pc-relative offset from the encoding of the $symbol
5014   //   operand to the global variable.
5015   //
5016   // For global address space:
5017   //   s_getpc_b64 s[0:1]
5018   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5019   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5020   //
5021   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5022   //   fixups or relocations are emitted to replace $symbol@*@lo and
5023   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5024   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5025   //   operand to the global variable.
5026   //
5027   // What we want here is an offset from the value returned by s_getpc
5028   // (which is the address of the s_add_u32 instruction) to the global
5029   // variable, but since the encoding of $symbol starts 4 bytes after the start
5030   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5031   // small. This requires us to add 4 to the global variable offset in order to
5032   // compute the correct address.
5033   SDValue PtrLo =
5034       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5035   SDValue PtrHi;
5036   if (GAFlags == SIInstrInfo::MO_NONE) {
5037     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5038   } else {
5039     PtrHi =
5040         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5041   }
5042   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5043 }
5044 
5045 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5046                                              SDValue Op,
5047                                              SelectionDAG &DAG) const {
5048   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5049   const GlobalValue *GV = GSD->getGlobal();
5050   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5051        shouldUseLDSConstAddress(GV)) ||
5052       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5053       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5054     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5055 
5056   SDLoc DL(GSD);
5057   EVT PtrVT = Op.getValueType();
5058 
5059   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5060     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5061                                             SIInstrInfo::MO_ABS32_LO);
5062     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5063   }
5064 
5065   if (shouldEmitFixup(GV))
5066     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5067   else if (shouldEmitPCReloc(GV))
5068     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5069                                    SIInstrInfo::MO_REL32);
5070 
5071   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5072                                             SIInstrInfo::MO_GOTPCREL32);
5073 
5074   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5075   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5076   const DataLayout &DataLayout = DAG.getDataLayout();
5077   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5078   MachinePointerInfo PtrInfo
5079     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5080 
5081   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5082                      MachineMemOperand::MODereferenceable |
5083                          MachineMemOperand::MOInvariant);
5084 }
5085 
5086 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5087                                    const SDLoc &DL, SDValue V) const {
5088   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5089   // the destination register.
5090   //
5091   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5092   // so we will end up with redundant moves to m0.
5093   //
5094   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5095 
5096   // A Null SDValue creates a glue result.
5097   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5098                                   V, Chain);
5099   return SDValue(M0, 0);
5100 }
5101 
5102 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5103                                                  SDValue Op,
5104                                                  MVT VT,
5105                                                  unsigned Offset) const {
5106   SDLoc SL(Op);
5107   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5108                                            DAG.getEntryNode(), Offset, 4, false);
5109   // The local size values will have the hi 16-bits as zero.
5110   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5111                      DAG.getValueType(VT));
5112 }
5113 
5114 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5115                                         EVT VT) {
5116   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5117                                       "non-hsa intrinsic with hsa target",
5118                                       DL.getDebugLoc());
5119   DAG.getContext()->diagnose(BadIntrin);
5120   return DAG.getUNDEF(VT);
5121 }
5122 
5123 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5124                                          EVT VT) {
5125   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5126                                       "intrinsic not supported on subtarget",
5127                                       DL.getDebugLoc());
5128   DAG.getContext()->diagnose(BadIntrin);
5129   return DAG.getUNDEF(VT);
5130 }
5131 
5132 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5133                                     ArrayRef<SDValue> Elts) {
5134   assert(!Elts.empty());
5135   MVT Type;
5136   unsigned NumElts;
5137 
5138   if (Elts.size() == 1) {
5139     Type = MVT::f32;
5140     NumElts = 1;
5141   } else if (Elts.size() == 2) {
5142     Type = MVT::v2f32;
5143     NumElts = 2;
5144   } else if (Elts.size() == 3) {
5145     Type = MVT::v3f32;
5146     NumElts = 3;
5147   } else if (Elts.size() <= 4) {
5148     Type = MVT::v4f32;
5149     NumElts = 4;
5150   } else if (Elts.size() <= 8) {
5151     Type = MVT::v8f32;
5152     NumElts = 8;
5153   } else {
5154     assert(Elts.size() <= 16);
5155     Type = MVT::v16f32;
5156     NumElts = 16;
5157   }
5158 
5159   SmallVector<SDValue, 16> VecElts(NumElts);
5160   for (unsigned i = 0; i < Elts.size(); ++i) {
5161     SDValue Elt = Elts[i];
5162     if (Elt.getValueType() != MVT::f32)
5163       Elt = DAG.getBitcast(MVT::f32, Elt);
5164     VecElts[i] = Elt;
5165   }
5166   for (unsigned i = Elts.size(); i < NumElts; ++i)
5167     VecElts[i] = DAG.getUNDEF(MVT::f32);
5168 
5169   if (NumElts == 1)
5170     return VecElts[0];
5171   return DAG.getBuildVector(Type, DL, VecElts);
5172 }
5173 
5174 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5175                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5176   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5177 
5178   uint64_t Value = CachePolicyConst->getZExtValue();
5179   SDLoc DL(CachePolicy);
5180   if (GLC) {
5181     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5182     Value &= ~(uint64_t)0x1;
5183   }
5184   if (SLC) {
5185     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5186     Value &= ~(uint64_t)0x2;
5187   }
5188   if (DLC) {
5189     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5190     Value &= ~(uint64_t)0x4;
5191   }
5192 
5193   return Value == 0;
5194 }
5195 
5196 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5197                               SDValue Src, int ExtraElts) {
5198   EVT SrcVT = Src.getValueType();
5199 
5200   SmallVector<SDValue, 8> Elts;
5201 
5202   if (SrcVT.isVector())
5203     DAG.ExtractVectorElements(Src, Elts);
5204   else
5205     Elts.push_back(Src);
5206 
5207   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5208   while (ExtraElts--)
5209     Elts.push_back(Undef);
5210 
5211   return DAG.getBuildVector(CastVT, DL, Elts);
5212 }
5213 
5214 // Re-construct the required return value for a image load intrinsic.
5215 // This is more complicated due to the optional use TexFailCtrl which means the required
5216 // return type is an aggregate
5217 static SDValue constructRetValue(SelectionDAG &DAG,
5218                                  MachineSDNode *Result,
5219                                  ArrayRef<EVT> ResultTypes,
5220                                  bool IsTexFail, bool Unpacked, bool IsD16,
5221                                  int DMaskPop, int NumVDataDwords,
5222                                  const SDLoc &DL, LLVMContext &Context) {
5223   // Determine the required return type. This is the same regardless of IsTexFail flag
5224   EVT ReqRetVT = ResultTypes[0];
5225   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5226   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5227     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5228 
5229   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5230     DMaskPop : (DMaskPop + 1) / 2;
5231 
5232   MVT DataDwordVT = NumDataDwords == 1 ?
5233     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5234 
5235   MVT MaskPopVT = MaskPopDwords == 1 ?
5236     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5237 
5238   SDValue Data(Result, 0);
5239   SDValue TexFail;
5240 
5241   if (IsTexFail) {
5242     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5243     if (MaskPopVT.isVector()) {
5244       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5245                          SDValue(Result, 0), ZeroIdx);
5246     } else {
5247       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5248                          SDValue(Result, 0), ZeroIdx);
5249     }
5250 
5251     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5252                           SDValue(Result, 0),
5253                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5254   }
5255 
5256   if (DataDwordVT.isVector())
5257     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5258                           NumDataDwords - MaskPopDwords);
5259 
5260   if (IsD16)
5261     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5262 
5263   if (!ReqRetVT.isVector())
5264     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5265 
5266   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5267 
5268   if (TexFail)
5269     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5270 
5271   if (Result->getNumValues() == 1)
5272     return Data;
5273 
5274   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5275 }
5276 
5277 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5278                          SDValue *LWE, bool &IsTexFail) {
5279   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5280 
5281   uint64_t Value = TexFailCtrlConst->getZExtValue();
5282   if (Value) {
5283     IsTexFail = true;
5284   }
5285 
5286   SDLoc DL(TexFailCtrlConst);
5287   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5288   Value &= ~(uint64_t)0x1;
5289   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5290   Value &= ~(uint64_t)0x2;
5291 
5292   return Value == 0;
5293 }
5294 
5295 SDValue SITargetLowering::lowerImage(SDValue Op,
5296                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5297                                      SelectionDAG &DAG) const {
5298   SDLoc DL(Op);
5299   MachineFunction &MF = DAG.getMachineFunction();
5300   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5301   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5302       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5303   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5304   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5305       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5306   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5307       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5308   unsigned IntrOpcode = Intr->BaseOpcode;
5309   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5310 
5311   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5312   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5313   bool IsD16 = false;
5314   bool IsA16 = false;
5315   SDValue VData;
5316   int NumVDataDwords;
5317   bool AdjustRetType = false;
5318 
5319   unsigned AddrIdx; // Index of first address argument
5320   unsigned DMask;
5321   unsigned DMaskLanes = 0;
5322 
5323   if (BaseOpcode->Atomic) {
5324     VData = Op.getOperand(2);
5325 
5326     bool Is64Bit = VData.getValueType() == MVT::i64;
5327     if (BaseOpcode->AtomicX2) {
5328       SDValue VData2 = Op.getOperand(3);
5329       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5330                                  {VData, VData2});
5331       if (Is64Bit)
5332         VData = DAG.getBitcast(MVT::v4i32, VData);
5333 
5334       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5335       DMask = Is64Bit ? 0xf : 0x3;
5336       NumVDataDwords = Is64Bit ? 4 : 2;
5337       AddrIdx = 4;
5338     } else {
5339       DMask = Is64Bit ? 0x3 : 0x1;
5340       NumVDataDwords = Is64Bit ? 2 : 1;
5341       AddrIdx = 3;
5342     }
5343   } else {
5344     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5345     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5346     DMask = DMaskConst->getZExtValue();
5347     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5348 
5349     if (BaseOpcode->Store) {
5350       VData = Op.getOperand(2);
5351 
5352       MVT StoreVT = VData.getSimpleValueType();
5353       if (StoreVT.getScalarType() == MVT::f16) {
5354         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5355           return Op; // D16 is unsupported for this instruction
5356 
5357         IsD16 = true;
5358         VData = handleD16VData(VData, DAG);
5359       }
5360 
5361       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5362     } else {
5363       // Work out the num dwords based on the dmask popcount and underlying type
5364       // and whether packing is supported.
5365       MVT LoadVT = ResultTypes[0].getSimpleVT();
5366       if (LoadVT.getScalarType() == MVT::f16) {
5367         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5368           return Op; // D16 is unsupported for this instruction
5369 
5370         IsD16 = true;
5371       }
5372 
5373       // Confirm that the return type is large enough for the dmask specified
5374       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5375           (!LoadVT.isVector() && DMaskLanes > 1))
5376           return Op;
5377 
5378       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5379         NumVDataDwords = (DMaskLanes + 1) / 2;
5380       else
5381         NumVDataDwords = DMaskLanes;
5382 
5383       AdjustRetType = true;
5384     }
5385 
5386     AddrIdx = DMaskIdx + 1;
5387   }
5388 
5389   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5390   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5391   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5392   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5393                        NumCoords + NumLCM;
5394   unsigned NumMIVAddrs = NumVAddrs;
5395 
5396   SmallVector<SDValue, 4> VAddrs;
5397 
5398   // Optimize _L to _LZ when _L is zero
5399   if (LZMappingInfo) {
5400     if (auto ConstantLod =
5401          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5402       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5403         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5404         NumMIVAddrs--;               // remove 'lod'
5405       }
5406     }
5407   }
5408 
5409   // Optimize _mip away, when 'lod' is zero
5410   if (MIPMappingInfo) {
5411     if (auto ConstantLod =
5412          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5413       if (ConstantLod->isNullValue()) {
5414         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5415         NumMIVAddrs--;               // remove 'lod'
5416       }
5417     }
5418   }
5419 
5420   // Check for 16 bit addresses and pack if true.
5421   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5422   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5423   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5424   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5425     // Illegal to use a16 images
5426     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5427       return Op;
5428 
5429     IsA16 = true;
5430     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5431     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5432       SDValue AddrLo;
5433       // Push back extra arguments.
5434       if (i < DimIdx) {
5435         AddrLo = Op.getOperand(i);
5436       } else {
5437         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5438         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5439         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5440             ((NumGradients / 2) % 2 == 1 &&
5441             (i == DimIdx + (NumGradients / 2) - 1 ||
5442              i == DimIdx + NumGradients - 1))) {
5443           AddrLo = Op.getOperand(i);
5444           if (AddrLo.getValueType() != MVT::i16)
5445             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5446           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5447         } else {
5448           AddrLo = DAG.getBuildVector(VectorVT, DL,
5449                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5450           i++;
5451         }
5452         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5453       }
5454       VAddrs.push_back(AddrLo);
5455     }
5456   } else {
5457     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5458       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5459   }
5460 
5461   // If the register allocator cannot place the address registers contiguously
5462   // without introducing moves, then using the non-sequential address encoding
5463   // is always preferable, since it saves VALU instructions and is usually a
5464   // wash in terms of code size or even better.
5465   //
5466   // However, we currently have no way of hinting to the register allocator that
5467   // MIMG addresses should be placed contiguously when it is possible to do so,
5468   // so force non-NSA for the common 2-address case as a heuristic.
5469   //
5470   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5471   // allocation when possible.
5472   bool UseNSA =
5473       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5474   SDValue VAddr;
5475   if (!UseNSA)
5476     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5477 
5478   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5479   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5480   unsigned CtrlIdx; // Index of texfailctrl argument
5481   SDValue Unorm;
5482   if (!BaseOpcode->Sampler) {
5483     Unorm = True;
5484     CtrlIdx = AddrIdx + NumVAddrs + 1;
5485   } else {
5486     auto UnormConst =
5487         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5488 
5489     Unorm = UnormConst->getZExtValue() ? True : False;
5490     CtrlIdx = AddrIdx + NumVAddrs + 3;
5491   }
5492 
5493   SDValue TFE;
5494   SDValue LWE;
5495   SDValue TexFail = Op.getOperand(CtrlIdx);
5496   bool IsTexFail = false;
5497   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5498     return Op;
5499 
5500   if (IsTexFail) {
5501     if (!DMaskLanes) {
5502       // Expecting to get an error flag since TFC is on - and dmask is 0
5503       // Force dmask to be at least 1 otherwise the instruction will fail
5504       DMask = 0x1;
5505       DMaskLanes = 1;
5506       NumVDataDwords = 1;
5507     }
5508     NumVDataDwords += 1;
5509     AdjustRetType = true;
5510   }
5511 
5512   // Has something earlier tagged that the return type needs adjusting
5513   // This happens if the instruction is a load or has set TexFailCtrl flags
5514   if (AdjustRetType) {
5515     // NumVDataDwords reflects the true number of dwords required in the return type
5516     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5517       // This is a no-op load. This can be eliminated
5518       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5519       if (isa<MemSDNode>(Op))
5520         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5521       return Undef;
5522     }
5523 
5524     EVT NewVT = NumVDataDwords > 1 ?
5525                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5526                 : MVT::i32;
5527 
5528     ResultTypes[0] = NewVT;
5529     if (ResultTypes.size() == 3) {
5530       // Original result was aggregate type used for TexFailCtrl results
5531       // The actual instruction returns as a vector type which has now been
5532       // created. Remove the aggregate result.
5533       ResultTypes.erase(&ResultTypes[1]);
5534     }
5535   }
5536 
5537   SDValue GLC;
5538   SDValue SLC;
5539   SDValue DLC;
5540   if (BaseOpcode->Atomic) {
5541     GLC = True; // TODO no-return optimization
5542     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5543                           IsGFX10 ? &DLC : nullptr))
5544       return Op;
5545   } else {
5546     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5547                           IsGFX10 ? &DLC : nullptr))
5548       return Op;
5549   }
5550 
5551   SmallVector<SDValue, 26> Ops;
5552   if (BaseOpcode->Store || BaseOpcode->Atomic)
5553     Ops.push_back(VData); // vdata
5554   if (UseNSA) {
5555     for (const SDValue &Addr : VAddrs)
5556       Ops.push_back(Addr);
5557   } else {
5558     Ops.push_back(VAddr);
5559   }
5560   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5561   if (BaseOpcode->Sampler)
5562     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5563   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5564   if (IsGFX10)
5565     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5566   Ops.push_back(Unorm);
5567   if (IsGFX10)
5568     Ops.push_back(DLC);
5569   Ops.push_back(GLC);
5570   Ops.push_back(SLC);
5571   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5572                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5573   if (IsGFX10)
5574     Ops.push_back(IsA16 ? True : False);
5575   Ops.push_back(TFE);
5576   Ops.push_back(LWE);
5577   if (!IsGFX10)
5578     Ops.push_back(DimInfo->DA ? True : False);
5579   if (BaseOpcode->HasD16)
5580     Ops.push_back(IsD16 ? True : False);
5581   if (isa<MemSDNode>(Op))
5582     Ops.push_back(Op.getOperand(0)); // chain
5583 
5584   int NumVAddrDwords =
5585       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5586   int Opcode = -1;
5587 
5588   if (IsGFX10) {
5589     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5590                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5591                                           : AMDGPU::MIMGEncGfx10Default,
5592                                    NumVDataDwords, NumVAddrDwords);
5593   } else {
5594     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5595       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5596                                      NumVDataDwords, NumVAddrDwords);
5597     if (Opcode == -1)
5598       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5599                                      NumVDataDwords, NumVAddrDwords);
5600   }
5601   assert(Opcode != -1);
5602 
5603   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5604   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5605     MachineMemOperand *MemRef = MemOp->getMemOperand();
5606     DAG.setNodeMemRefs(NewNode, {MemRef});
5607   }
5608 
5609   if (BaseOpcode->AtomicX2) {
5610     SmallVector<SDValue, 1> Elt;
5611     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5612     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5613   } else if (!BaseOpcode->Store) {
5614     return constructRetValue(DAG, NewNode,
5615                              OrigResultTypes, IsTexFail,
5616                              Subtarget->hasUnpackedD16VMem(), IsD16,
5617                              DMaskLanes, NumVDataDwords, DL,
5618                              *DAG.getContext());
5619   }
5620 
5621   return SDValue(NewNode, 0);
5622 }
5623 
5624 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5625                                        SDValue Offset, SDValue CachePolicy,
5626                                        SelectionDAG &DAG) const {
5627   MachineFunction &MF = DAG.getMachineFunction();
5628 
5629   const DataLayout &DataLayout = DAG.getDataLayout();
5630   unsigned Align =
5631       DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5632 
5633   MachineMemOperand *MMO = MF.getMachineMemOperand(
5634       MachinePointerInfo(),
5635       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5636           MachineMemOperand::MOInvariant,
5637       VT.getStoreSize(), Align);
5638 
5639   if (!Offset->isDivergent()) {
5640     SDValue Ops[] = {
5641         Rsrc,
5642         Offset, // Offset
5643         CachePolicy
5644     };
5645 
5646     // Widen vec3 load to vec4.
5647     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5648       EVT WidenedVT =
5649           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5650       auto WidenedOp = DAG.getMemIntrinsicNode(
5651           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5652           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5653       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5654                                    DAG.getVectorIdxConstant(0, DL));
5655       return Subvector;
5656     }
5657 
5658     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5659                                    DAG.getVTList(VT), Ops, VT, MMO);
5660   }
5661 
5662   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5663   // assume that the buffer is unswizzled.
5664   SmallVector<SDValue, 4> Loads;
5665   unsigned NumLoads = 1;
5666   MVT LoadVT = VT.getSimpleVT();
5667   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5668   assert((LoadVT.getScalarType() == MVT::i32 ||
5669           LoadVT.getScalarType() == MVT::f32));
5670 
5671   if (NumElts == 8 || NumElts == 16) {
5672     NumLoads = NumElts / 4;
5673     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5674   }
5675 
5676   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5677   SDValue Ops[] = {
5678       DAG.getEntryNode(),                               // Chain
5679       Rsrc,                                             // rsrc
5680       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5681       {},                                               // voffset
5682       {},                                               // soffset
5683       {},                                               // offset
5684       CachePolicy,                                      // cachepolicy
5685       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5686   };
5687 
5688   // Use the alignment to ensure that the required offsets will fit into the
5689   // immediate offsets.
5690   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5691 
5692   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5693   for (unsigned i = 0; i < NumLoads; ++i) {
5694     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5695     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5696                                         LoadVT, MMO, DAG));
5697   }
5698 
5699   if (NumElts == 8 || NumElts == 16)
5700     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5701 
5702   return Loads[0];
5703 }
5704 
5705 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5706                                                   SelectionDAG &DAG) const {
5707   MachineFunction &MF = DAG.getMachineFunction();
5708   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5709 
5710   EVT VT = Op.getValueType();
5711   SDLoc DL(Op);
5712   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5713 
5714   // TODO: Should this propagate fast-math-flags?
5715 
5716   switch (IntrinsicID) {
5717   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5718     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5719       return emitNonHSAIntrinsicError(DAG, DL, VT);
5720     return getPreloadedValue(DAG, *MFI, VT,
5721                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5722   }
5723   case Intrinsic::amdgcn_dispatch_ptr:
5724   case Intrinsic::amdgcn_queue_ptr: {
5725     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5726       DiagnosticInfoUnsupported BadIntrin(
5727           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5728           DL.getDebugLoc());
5729       DAG.getContext()->diagnose(BadIntrin);
5730       return DAG.getUNDEF(VT);
5731     }
5732 
5733     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5734       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5735     return getPreloadedValue(DAG, *MFI, VT, RegID);
5736   }
5737   case Intrinsic::amdgcn_implicitarg_ptr: {
5738     if (MFI->isEntryFunction())
5739       return getImplicitArgPtr(DAG, DL);
5740     return getPreloadedValue(DAG, *MFI, VT,
5741                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5742   }
5743   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5744     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
5745       // This only makes sense to call in a kernel, so just lower to null.
5746       return DAG.getConstant(0, DL, VT);
5747     }
5748 
5749     return getPreloadedValue(DAG, *MFI, VT,
5750                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5751   }
5752   case Intrinsic::amdgcn_dispatch_id: {
5753     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5754   }
5755   case Intrinsic::amdgcn_rcp:
5756     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5757   case Intrinsic::amdgcn_rsq:
5758     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5759   case Intrinsic::amdgcn_rsq_legacy:
5760     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5761       return emitRemovedIntrinsicError(DAG, DL, VT);
5762 
5763     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5764   case Intrinsic::amdgcn_rcp_legacy:
5765     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5766       return emitRemovedIntrinsicError(DAG, DL, VT);
5767     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5768   case Intrinsic::amdgcn_rsq_clamp: {
5769     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5770       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5771 
5772     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5773     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5774     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5775 
5776     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5777     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5778                               DAG.getConstantFP(Max, DL, VT));
5779     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5780                        DAG.getConstantFP(Min, DL, VT));
5781   }
5782   case Intrinsic::r600_read_ngroups_x:
5783     if (Subtarget->isAmdHsaOS())
5784       return emitNonHSAIntrinsicError(DAG, DL, VT);
5785 
5786     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5787                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5788   case Intrinsic::r600_read_ngroups_y:
5789     if (Subtarget->isAmdHsaOS())
5790       return emitNonHSAIntrinsicError(DAG, DL, VT);
5791 
5792     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5793                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5794   case Intrinsic::r600_read_ngroups_z:
5795     if (Subtarget->isAmdHsaOS())
5796       return emitNonHSAIntrinsicError(DAG, DL, VT);
5797 
5798     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5799                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5800   case Intrinsic::r600_read_global_size_x:
5801     if (Subtarget->isAmdHsaOS())
5802       return emitNonHSAIntrinsicError(DAG, DL, VT);
5803 
5804     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5805                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5806   case Intrinsic::r600_read_global_size_y:
5807     if (Subtarget->isAmdHsaOS())
5808       return emitNonHSAIntrinsicError(DAG, DL, VT);
5809 
5810     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5811                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5812   case Intrinsic::r600_read_global_size_z:
5813     if (Subtarget->isAmdHsaOS())
5814       return emitNonHSAIntrinsicError(DAG, DL, VT);
5815 
5816     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5817                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5818   case Intrinsic::r600_read_local_size_x:
5819     if (Subtarget->isAmdHsaOS())
5820       return emitNonHSAIntrinsicError(DAG, DL, VT);
5821 
5822     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5823                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5824   case Intrinsic::r600_read_local_size_y:
5825     if (Subtarget->isAmdHsaOS())
5826       return emitNonHSAIntrinsicError(DAG, DL, VT);
5827 
5828     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5829                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5830   case Intrinsic::r600_read_local_size_z:
5831     if (Subtarget->isAmdHsaOS())
5832       return emitNonHSAIntrinsicError(DAG, DL, VT);
5833 
5834     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5835                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5836   case Intrinsic::amdgcn_workgroup_id_x:
5837     return getPreloadedValue(DAG, *MFI, VT,
5838                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5839   case Intrinsic::amdgcn_workgroup_id_y:
5840     return getPreloadedValue(DAG, *MFI, VT,
5841                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5842   case Intrinsic::amdgcn_workgroup_id_z:
5843     return getPreloadedValue(DAG, *MFI, VT,
5844                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5845   case Intrinsic::amdgcn_workitem_id_x:
5846     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5847                           SDLoc(DAG.getEntryNode()),
5848                           MFI->getArgInfo().WorkItemIDX);
5849   case Intrinsic::amdgcn_workitem_id_y:
5850     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5851                           SDLoc(DAG.getEntryNode()),
5852                           MFI->getArgInfo().WorkItemIDY);
5853   case Intrinsic::amdgcn_workitem_id_z:
5854     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5855                           SDLoc(DAG.getEntryNode()),
5856                           MFI->getArgInfo().WorkItemIDZ);
5857   case Intrinsic::amdgcn_wavefrontsize:
5858     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5859                            SDLoc(Op), MVT::i32);
5860   case Intrinsic::amdgcn_s_buffer_load: {
5861     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5862     SDValue GLC;
5863     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5864     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5865                           IsGFX10 ? &DLC : nullptr))
5866       return Op;
5867     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5868                         DAG);
5869   }
5870   case Intrinsic::amdgcn_fdiv_fast:
5871     return lowerFDIV_FAST(Op, DAG);
5872   case Intrinsic::amdgcn_sin:
5873     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5874 
5875   case Intrinsic::amdgcn_cos:
5876     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5877 
5878   case Intrinsic::amdgcn_mul_u24:
5879     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5880   case Intrinsic::amdgcn_mul_i24:
5881     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5882 
5883   case Intrinsic::amdgcn_log_clamp: {
5884     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5885       return SDValue();
5886 
5887     DiagnosticInfoUnsupported BadIntrin(
5888       MF.getFunction(), "intrinsic not supported on subtarget",
5889       DL.getDebugLoc());
5890       DAG.getContext()->diagnose(BadIntrin);
5891       return DAG.getUNDEF(VT);
5892   }
5893   case Intrinsic::amdgcn_ldexp:
5894     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5895                        Op.getOperand(1), Op.getOperand(2));
5896 
5897   case Intrinsic::amdgcn_fract:
5898     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5899 
5900   case Intrinsic::amdgcn_class:
5901     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5902                        Op.getOperand(1), Op.getOperand(2));
5903   case Intrinsic::amdgcn_div_fmas:
5904     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5905                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5906                        Op.getOperand(4));
5907 
5908   case Intrinsic::amdgcn_div_fixup:
5909     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5910                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5911 
5912   case Intrinsic::amdgcn_trig_preop:
5913     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5914                        Op.getOperand(1), Op.getOperand(2));
5915   case Intrinsic::amdgcn_div_scale: {
5916     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5917 
5918     // Translate to the operands expected by the machine instruction. The
5919     // first parameter must be the same as the first instruction.
5920     SDValue Numerator = Op.getOperand(1);
5921     SDValue Denominator = Op.getOperand(2);
5922 
5923     // Note this order is opposite of the machine instruction's operations,
5924     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5925     // intrinsic has the numerator as the first operand to match a normal
5926     // division operation.
5927 
5928     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5929 
5930     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5931                        Denominator, Numerator);
5932   }
5933   case Intrinsic::amdgcn_icmp: {
5934     // There is a Pat that handles this variant, so return it as-is.
5935     if (Op.getOperand(1).getValueType() == MVT::i1 &&
5936         Op.getConstantOperandVal(2) == 0 &&
5937         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
5938       return Op;
5939     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
5940   }
5941   case Intrinsic::amdgcn_fcmp: {
5942     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
5943   }
5944   case Intrinsic::amdgcn_fmed3:
5945     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
5946                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5947   case Intrinsic::amdgcn_fdot2:
5948     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
5949                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5950                        Op.getOperand(4));
5951   case Intrinsic::amdgcn_fmul_legacy:
5952     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
5953                        Op.getOperand(1), Op.getOperand(2));
5954   case Intrinsic::amdgcn_sffbh:
5955     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
5956   case Intrinsic::amdgcn_sbfe:
5957     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
5958                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5959   case Intrinsic::amdgcn_ubfe:
5960     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
5961                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5962   case Intrinsic::amdgcn_cvt_pkrtz:
5963   case Intrinsic::amdgcn_cvt_pknorm_i16:
5964   case Intrinsic::amdgcn_cvt_pknorm_u16:
5965   case Intrinsic::amdgcn_cvt_pk_i16:
5966   case Intrinsic::amdgcn_cvt_pk_u16: {
5967     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
5968     EVT VT = Op.getValueType();
5969     unsigned Opcode;
5970 
5971     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
5972       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
5973     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
5974       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5975     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
5976       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5977     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
5978       Opcode = AMDGPUISD::CVT_PK_I16_I32;
5979     else
5980       Opcode = AMDGPUISD::CVT_PK_U16_U32;
5981 
5982     if (isTypeLegal(VT))
5983       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
5984 
5985     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
5986                                Op.getOperand(1), Op.getOperand(2));
5987     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
5988   }
5989   case Intrinsic::amdgcn_fmad_ftz:
5990     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
5991                        Op.getOperand(2), Op.getOperand(3));
5992 
5993   case Intrinsic::amdgcn_if_break:
5994     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
5995                                       Op->getOperand(1), Op->getOperand(2)), 0);
5996 
5997   case Intrinsic::amdgcn_groupstaticsize: {
5998     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
5999     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6000       return Op;
6001 
6002     const Module *M = MF.getFunction().getParent();
6003     const GlobalValue *GV =
6004         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6005     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6006                                             SIInstrInfo::MO_ABS32_LO);
6007     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6008   }
6009   case Intrinsic::amdgcn_is_shared:
6010   case Intrinsic::amdgcn_is_private: {
6011     SDLoc SL(Op);
6012     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6013       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6014     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6015     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6016                                  Op.getOperand(1));
6017 
6018     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6019                                 DAG.getConstant(1, SL, MVT::i32));
6020     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6021   }
6022   case Intrinsic::amdgcn_alignbit:
6023     return DAG.getNode(ISD::FSHR, DL, VT,
6024                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6025   case Intrinsic::amdgcn_reloc_constant: {
6026     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6027     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6028     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6029     auto RelocSymbol = cast<GlobalVariable>(
6030         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6031     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6032                                             SIInstrInfo::MO_ABS32_LO);
6033     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6034   }
6035   default:
6036     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6037             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6038       return lowerImage(Op, ImageDimIntr, DAG);
6039 
6040     return Op;
6041   }
6042 }
6043 
6044 // This function computes an appropriate offset to pass to
6045 // MachineMemOperand::setOffset() based on the offset inputs to
6046 // an intrinsic.  If any of the offsets are non-contstant or
6047 // if VIndex is non-zero then this function returns 0.  Otherwise,
6048 // it returns the sum of VOffset, SOffset, and Offset.
6049 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6050                                       SDValue SOffset,
6051                                       SDValue Offset,
6052                                       SDValue VIndex = SDValue()) {
6053 
6054   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6055       !isa<ConstantSDNode>(Offset))
6056     return 0;
6057 
6058   if (VIndex) {
6059     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6060       return 0;
6061   }
6062 
6063   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6064          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6065          cast<ConstantSDNode>(Offset)->getSExtValue();
6066 }
6067 
6068 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6069   switch (MF.getFunction().getCallingConv()) {
6070   case CallingConv::AMDGPU_PS:
6071     return 1;
6072   case CallingConv::AMDGPU_VS:
6073     return 2;
6074   case CallingConv::AMDGPU_GS:
6075     return 3;
6076   case CallingConv::AMDGPU_HS:
6077   case CallingConv::AMDGPU_LS:
6078   case CallingConv::AMDGPU_ES:
6079     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6080   case CallingConv::AMDGPU_CS:
6081   case CallingConv::AMDGPU_KERNEL:
6082   case CallingConv::C:
6083   case CallingConv::Fast:
6084   default:
6085     // Assume other calling conventions are various compute callable functions
6086     return 0;
6087   }
6088 }
6089 
6090 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6091                                                  SelectionDAG &DAG) const {
6092   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6093   SDLoc DL(Op);
6094 
6095   switch (IntrID) {
6096   case Intrinsic::amdgcn_ds_ordered_add:
6097   case Intrinsic::amdgcn_ds_ordered_swap: {
6098     MemSDNode *M = cast<MemSDNode>(Op);
6099     SDValue Chain = M->getOperand(0);
6100     SDValue M0 = M->getOperand(2);
6101     SDValue Value = M->getOperand(3);
6102     unsigned IndexOperand = M->getConstantOperandVal(7);
6103     unsigned WaveRelease = M->getConstantOperandVal(8);
6104     unsigned WaveDone = M->getConstantOperandVal(9);
6105 
6106     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6107     IndexOperand &= ~0x3f;
6108     unsigned CountDw = 0;
6109 
6110     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6111       CountDw = (IndexOperand >> 24) & 0xf;
6112       IndexOperand &= ~(0xf << 24);
6113 
6114       if (CountDw < 1 || CountDw > 4) {
6115         report_fatal_error(
6116             "ds_ordered_count: dword count must be between 1 and 4");
6117       }
6118     }
6119 
6120     if (IndexOperand)
6121       report_fatal_error("ds_ordered_count: bad index operand");
6122 
6123     if (WaveDone && !WaveRelease)
6124       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6125 
6126     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6127     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6128     unsigned Offset0 = OrderedCountIndex << 2;
6129     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6130                        (Instruction << 4);
6131 
6132     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6133       Offset1 |= (CountDw - 1) << 6;
6134 
6135     unsigned Offset = Offset0 | (Offset1 << 8);
6136 
6137     SDValue Ops[] = {
6138       Chain,
6139       Value,
6140       DAG.getTargetConstant(Offset, DL, MVT::i16),
6141       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6142     };
6143     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6144                                    M->getVTList(), Ops, M->getMemoryVT(),
6145                                    M->getMemOperand());
6146   }
6147   case Intrinsic::amdgcn_ds_fadd: {
6148     MemSDNode *M = cast<MemSDNode>(Op);
6149     unsigned Opc;
6150     switch (IntrID) {
6151     case Intrinsic::amdgcn_ds_fadd:
6152       Opc = ISD::ATOMIC_LOAD_FADD;
6153       break;
6154     }
6155 
6156     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6157                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6158                          M->getMemOperand());
6159   }
6160   case Intrinsic::amdgcn_atomic_inc:
6161   case Intrinsic::amdgcn_atomic_dec:
6162   case Intrinsic::amdgcn_ds_fmin:
6163   case Intrinsic::amdgcn_ds_fmax: {
6164     MemSDNode *M = cast<MemSDNode>(Op);
6165     unsigned Opc;
6166     switch (IntrID) {
6167     case Intrinsic::amdgcn_atomic_inc:
6168       Opc = AMDGPUISD::ATOMIC_INC;
6169       break;
6170     case Intrinsic::amdgcn_atomic_dec:
6171       Opc = AMDGPUISD::ATOMIC_DEC;
6172       break;
6173     case Intrinsic::amdgcn_ds_fmin:
6174       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6175       break;
6176     case Intrinsic::amdgcn_ds_fmax:
6177       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6178       break;
6179     default:
6180       llvm_unreachable("Unknown intrinsic!");
6181     }
6182     SDValue Ops[] = {
6183       M->getOperand(0), // Chain
6184       M->getOperand(2), // Ptr
6185       M->getOperand(3)  // Value
6186     };
6187 
6188     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6189                                    M->getMemoryVT(), M->getMemOperand());
6190   }
6191   case Intrinsic::amdgcn_buffer_load:
6192   case Intrinsic::amdgcn_buffer_load_format: {
6193     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6194     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6195     unsigned IdxEn = 1;
6196     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6197       IdxEn = Idx->getZExtValue() != 0;
6198     SDValue Ops[] = {
6199       Op.getOperand(0), // Chain
6200       Op.getOperand(2), // rsrc
6201       Op.getOperand(3), // vindex
6202       SDValue(),        // voffset -- will be set by setBufferOffsets
6203       SDValue(),        // soffset -- will be set by setBufferOffsets
6204       SDValue(),        // offset -- will be set by setBufferOffsets
6205       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6206       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6207     };
6208 
6209     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6210     // We don't know the offset if vindex is non-zero, so clear it.
6211     if (IdxEn)
6212       Offset = 0;
6213 
6214     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6215         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6216 
6217     EVT VT = Op.getValueType();
6218     EVT IntVT = VT.changeTypeToInteger();
6219     auto *M = cast<MemSDNode>(Op);
6220     M->getMemOperand()->setOffset(Offset);
6221     EVT LoadVT = Op.getValueType();
6222 
6223     if (LoadVT.getScalarType() == MVT::f16)
6224       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6225                                  M, DAG, Ops);
6226 
6227     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6228     if (LoadVT.getScalarType() == MVT::i8 ||
6229         LoadVT.getScalarType() == MVT::i16)
6230       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6231 
6232     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6233                                M->getMemOperand(), DAG);
6234   }
6235   case Intrinsic::amdgcn_raw_buffer_load:
6236   case Intrinsic::amdgcn_raw_buffer_load_format: {
6237     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6238 
6239     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6240     SDValue Ops[] = {
6241       Op.getOperand(0), // Chain
6242       Op.getOperand(2), // rsrc
6243       DAG.getConstant(0, DL, MVT::i32), // vindex
6244       Offsets.first,    // voffset
6245       Op.getOperand(4), // soffset
6246       Offsets.second,   // offset
6247       Op.getOperand(5), // cachepolicy, swizzled buffer
6248       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6249     };
6250 
6251     auto *M = cast<MemSDNode>(Op);
6252     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6253     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6254   }
6255   case Intrinsic::amdgcn_struct_buffer_load:
6256   case Intrinsic::amdgcn_struct_buffer_load_format: {
6257     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6258 
6259     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6260     SDValue Ops[] = {
6261       Op.getOperand(0), // Chain
6262       Op.getOperand(2), // rsrc
6263       Op.getOperand(3), // vindex
6264       Offsets.first,    // voffset
6265       Op.getOperand(5), // soffset
6266       Offsets.second,   // offset
6267       Op.getOperand(6), // cachepolicy, swizzled buffer
6268       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6269     };
6270 
6271     auto *M = cast<MemSDNode>(Op);
6272     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6273                                                         Ops[2]));
6274     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6275   }
6276   case Intrinsic::amdgcn_tbuffer_load: {
6277     MemSDNode *M = cast<MemSDNode>(Op);
6278     EVT LoadVT = Op.getValueType();
6279 
6280     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6281     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6282     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6283     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6284     unsigned IdxEn = 1;
6285     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6286       IdxEn = Idx->getZExtValue() != 0;
6287     SDValue Ops[] = {
6288       Op.getOperand(0),  // Chain
6289       Op.getOperand(2),  // rsrc
6290       Op.getOperand(3),  // vindex
6291       Op.getOperand(4),  // voffset
6292       Op.getOperand(5),  // soffset
6293       Op.getOperand(6),  // offset
6294       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6295       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6296       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6297     };
6298 
6299     if (LoadVT.getScalarType() == MVT::f16)
6300       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6301                                  M, DAG, Ops);
6302     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6303                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6304                                DAG);
6305   }
6306   case Intrinsic::amdgcn_raw_tbuffer_load: {
6307     MemSDNode *M = cast<MemSDNode>(Op);
6308     EVT LoadVT = Op.getValueType();
6309     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6310 
6311     SDValue Ops[] = {
6312       Op.getOperand(0),  // Chain
6313       Op.getOperand(2),  // rsrc
6314       DAG.getConstant(0, DL, MVT::i32), // vindex
6315       Offsets.first,     // voffset
6316       Op.getOperand(4),  // soffset
6317       Offsets.second,    // offset
6318       Op.getOperand(5),  // format
6319       Op.getOperand(6),  // cachepolicy, swizzled buffer
6320       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6321     };
6322 
6323     if (LoadVT.getScalarType() == MVT::f16)
6324       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6325                                  M, DAG, Ops);
6326     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6327                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6328                                DAG);
6329   }
6330   case Intrinsic::amdgcn_struct_tbuffer_load: {
6331     MemSDNode *M = cast<MemSDNode>(Op);
6332     EVT LoadVT = Op.getValueType();
6333     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6334 
6335     SDValue Ops[] = {
6336       Op.getOperand(0),  // Chain
6337       Op.getOperand(2),  // rsrc
6338       Op.getOperand(3),  // vindex
6339       Offsets.first,     // voffset
6340       Op.getOperand(5),  // soffset
6341       Offsets.second,    // offset
6342       Op.getOperand(6),  // format
6343       Op.getOperand(7),  // cachepolicy, swizzled buffer
6344       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6345     };
6346 
6347     if (LoadVT.getScalarType() == MVT::f16)
6348       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6349                                  M, DAG, Ops);
6350     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6351                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6352                                DAG);
6353   }
6354   case Intrinsic::amdgcn_buffer_atomic_swap:
6355   case Intrinsic::amdgcn_buffer_atomic_add:
6356   case Intrinsic::amdgcn_buffer_atomic_sub:
6357   case Intrinsic::amdgcn_buffer_atomic_smin:
6358   case Intrinsic::amdgcn_buffer_atomic_umin:
6359   case Intrinsic::amdgcn_buffer_atomic_smax:
6360   case Intrinsic::amdgcn_buffer_atomic_umax:
6361   case Intrinsic::amdgcn_buffer_atomic_and:
6362   case Intrinsic::amdgcn_buffer_atomic_or:
6363   case Intrinsic::amdgcn_buffer_atomic_xor: {
6364     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6365     unsigned IdxEn = 1;
6366     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6367       IdxEn = Idx->getZExtValue() != 0;
6368     SDValue Ops[] = {
6369       Op.getOperand(0), // Chain
6370       Op.getOperand(2), // vdata
6371       Op.getOperand(3), // rsrc
6372       Op.getOperand(4), // vindex
6373       SDValue(),        // voffset -- will be set by setBufferOffsets
6374       SDValue(),        // soffset -- will be set by setBufferOffsets
6375       SDValue(),        // offset -- will be set by setBufferOffsets
6376       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6377       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6378     };
6379     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6380     // We don't know the offset if vindex is non-zero, so clear it.
6381     if (IdxEn)
6382       Offset = 0;
6383     EVT VT = Op.getValueType();
6384 
6385     auto *M = cast<MemSDNode>(Op);
6386     M->getMemOperand()->setOffset(Offset);
6387     unsigned Opcode = 0;
6388 
6389     switch (IntrID) {
6390     case Intrinsic::amdgcn_buffer_atomic_swap:
6391       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6392       break;
6393     case Intrinsic::amdgcn_buffer_atomic_add:
6394       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6395       break;
6396     case Intrinsic::amdgcn_buffer_atomic_sub:
6397       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6398       break;
6399     case Intrinsic::amdgcn_buffer_atomic_smin:
6400       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6401       break;
6402     case Intrinsic::amdgcn_buffer_atomic_umin:
6403       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6404       break;
6405     case Intrinsic::amdgcn_buffer_atomic_smax:
6406       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6407       break;
6408     case Intrinsic::amdgcn_buffer_atomic_umax:
6409       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6410       break;
6411     case Intrinsic::amdgcn_buffer_atomic_and:
6412       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6413       break;
6414     case Intrinsic::amdgcn_buffer_atomic_or:
6415       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6416       break;
6417     case Intrinsic::amdgcn_buffer_atomic_xor:
6418       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6419       break;
6420     default:
6421       llvm_unreachable("unhandled atomic opcode");
6422     }
6423 
6424     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6425                                    M->getMemOperand());
6426   }
6427   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6428   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6429   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6430   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6431   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6432   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6433   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6434   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6435   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6436   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6437   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6438   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6439     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6440     SDValue Ops[] = {
6441       Op.getOperand(0), // Chain
6442       Op.getOperand(2), // vdata
6443       Op.getOperand(3), // rsrc
6444       DAG.getConstant(0, DL, MVT::i32), // vindex
6445       Offsets.first,    // voffset
6446       Op.getOperand(5), // soffset
6447       Offsets.second,   // offset
6448       Op.getOperand(6), // cachepolicy
6449       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6450     };
6451     EVT VT = Op.getValueType();
6452 
6453     auto *M = cast<MemSDNode>(Op);
6454     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6455     unsigned Opcode = 0;
6456 
6457     switch (IntrID) {
6458     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6459       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6460       break;
6461     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6462       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6463       break;
6464     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6465       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6466       break;
6467     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6468       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6469       break;
6470     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6471       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6472       break;
6473     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6474       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6475       break;
6476     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6477       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6478       break;
6479     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6480       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6481       break;
6482     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6483       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6484       break;
6485     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6486       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6487       break;
6488     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6489       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6490       break;
6491     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6492       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6493       break;
6494     default:
6495       llvm_unreachable("unhandled atomic opcode");
6496     }
6497 
6498     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6499                                    M->getMemOperand());
6500   }
6501   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6502   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6503   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6504   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6505   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6506   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6507   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6508   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6509   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6510   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6511   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6512   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6513     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6514     SDValue Ops[] = {
6515       Op.getOperand(0), // Chain
6516       Op.getOperand(2), // vdata
6517       Op.getOperand(3), // rsrc
6518       Op.getOperand(4), // vindex
6519       Offsets.first,    // voffset
6520       Op.getOperand(6), // soffset
6521       Offsets.second,   // offset
6522       Op.getOperand(7), // cachepolicy
6523       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6524     };
6525     EVT VT = Op.getValueType();
6526 
6527     auto *M = cast<MemSDNode>(Op);
6528     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6529                                                         Ops[3]));
6530     unsigned Opcode = 0;
6531 
6532     switch (IntrID) {
6533     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6534       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6535       break;
6536     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6537       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6538       break;
6539     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6540       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6541       break;
6542     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6543       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6544       break;
6545     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6546       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6547       break;
6548     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6549       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6550       break;
6551     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6552       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6553       break;
6554     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6555       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6556       break;
6557     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6558       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6559       break;
6560     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6561       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6562       break;
6563     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6564       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6565       break;
6566     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6567       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6568       break;
6569     default:
6570       llvm_unreachable("unhandled atomic opcode");
6571     }
6572 
6573     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6574                                    M->getMemOperand());
6575   }
6576   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6577     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6578     unsigned IdxEn = 1;
6579     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6580       IdxEn = Idx->getZExtValue() != 0;
6581     SDValue Ops[] = {
6582       Op.getOperand(0), // Chain
6583       Op.getOperand(2), // src
6584       Op.getOperand(3), // cmp
6585       Op.getOperand(4), // rsrc
6586       Op.getOperand(5), // vindex
6587       SDValue(),        // voffset -- will be set by setBufferOffsets
6588       SDValue(),        // soffset -- will be set by setBufferOffsets
6589       SDValue(),        // offset -- will be set by setBufferOffsets
6590       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6591       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6592     };
6593     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6594     // We don't know the offset if vindex is non-zero, so clear it.
6595     if (IdxEn)
6596       Offset = 0;
6597     EVT VT = Op.getValueType();
6598     auto *M = cast<MemSDNode>(Op);
6599     M->getMemOperand()->setOffset(Offset);
6600 
6601     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6602                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6603   }
6604   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6605     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6606     SDValue Ops[] = {
6607       Op.getOperand(0), // Chain
6608       Op.getOperand(2), // src
6609       Op.getOperand(3), // cmp
6610       Op.getOperand(4), // rsrc
6611       DAG.getConstant(0, DL, MVT::i32), // vindex
6612       Offsets.first,    // voffset
6613       Op.getOperand(6), // soffset
6614       Offsets.second,   // offset
6615       Op.getOperand(7), // cachepolicy
6616       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6617     };
6618     EVT VT = Op.getValueType();
6619     auto *M = cast<MemSDNode>(Op);
6620     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6621 
6622     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6623                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6624   }
6625   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6626     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6627     SDValue Ops[] = {
6628       Op.getOperand(0), // Chain
6629       Op.getOperand(2), // src
6630       Op.getOperand(3), // cmp
6631       Op.getOperand(4), // rsrc
6632       Op.getOperand(5), // vindex
6633       Offsets.first,    // voffset
6634       Op.getOperand(7), // soffset
6635       Offsets.second,   // offset
6636       Op.getOperand(8), // cachepolicy
6637       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6638     };
6639     EVT VT = Op.getValueType();
6640     auto *M = cast<MemSDNode>(Op);
6641     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6642                                                         Ops[4]));
6643 
6644     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6645                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6646   }
6647 
6648   default:
6649     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6650             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6651       return lowerImage(Op, ImageDimIntr, DAG);
6652 
6653     return SDValue();
6654   }
6655 }
6656 
6657 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6658 // dwordx4 if on SI.
6659 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6660                                               SDVTList VTList,
6661                                               ArrayRef<SDValue> Ops, EVT MemVT,
6662                                               MachineMemOperand *MMO,
6663                                               SelectionDAG &DAG) const {
6664   EVT VT = VTList.VTs[0];
6665   EVT WidenedVT = VT;
6666   EVT WidenedMemVT = MemVT;
6667   if (!Subtarget->hasDwordx3LoadStores() &&
6668       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6669     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6670                                  WidenedVT.getVectorElementType(), 4);
6671     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6672                                     WidenedMemVT.getVectorElementType(), 4);
6673     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6674   }
6675 
6676   assert(VTList.NumVTs == 2);
6677   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6678 
6679   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6680                                        WidenedMemVT, MMO);
6681   if (WidenedVT != VT) {
6682     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6683                                DAG.getVectorIdxConstant(0, DL));
6684     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6685   }
6686   return NewOp;
6687 }
6688 
6689 SDValue SITargetLowering::handleD16VData(SDValue VData,
6690                                          SelectionDAG &DAG) const {
6691   EVT StoreVT = VData.getValueType();
6692 
6693   // No change for f16 and legal vector D16 types.
6694   if (!StoreVT.isVector())
6695     return VData;
6696 
6697   SDLoc DL(VData);
6698   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6699 
6700   if (Subtarget->hasUnpackedD16VMem()) {
6701     // We need to unpack the packed data to store.
6702     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6703     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6704 
6705     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6706                                         StoreVT.getVectorNumElements());
6707     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6708     return DAG.UnrollVectorOp(ZExt.getNode());
6709   }
6710 
6711   assert(isTypeLegal(StoreVT));
6712   return VData;
6713 }
6714 
6715 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6716                                               SelectionDAG &DAG) const {
6717   SDLoc DL(Op);
6718   SDValue Chain = Op.getOperand(0);
6719   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6720   MachineFunction &MF = DAG.getMachineFunction();
6721 
6722   switch (IntrinsicID) {
6723   case Intrinsic::amdgcn_exp_compr: {
6724     SDValue Src0 = Op.getOperand(4);
6725     SDValue Src1 = Op.getOperand(5);
6726     // Hack around illegal type on SI by directly selecting it.
6727     if (isTypeLegal(Src0.getValueType()))
6728       return SDValue();
6729 
6730     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6731     SDValue Undef = DAG.getUNDEF(MVT::f32);
6732     const SDValue Ops[] = {
6733       Op.getOperand(2), // tgt
6734       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
6735       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
6736       Undef, // src2
6737       Undef, // src3
6738       Op.getOperand(7), // vm
6739       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6740       Op.getOperand(3), // en
6741       Op.getOperand(0) // Chain
6742     };
6743 
6744     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
6745     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
6746   }
6747   case Intrinsic::amdgcn_s_barrier: {
6748     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6749       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6750       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6751       if (WGSize <= ST.getWavefrontSize())
6752         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6753                                           Op.getOperand(0)), 0);
6754     }
6755     return SDValue();
6756   };
6757   case Intrinsic::amdgcn_tbuffer_store: {
6758     SDValue VData = Op.getOperand(2);
6759     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6760     if (IsD16)
6761       VData = handleD16VData(VData, DAG);
6762     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6763     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6764     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6765     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6766     unsigned IdxEn = 1;
6767     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6768       IdxEn = Idx->getZExtValue() != 0;
6769     SDValue Ops[] = {
6770       Chain,
6771       VData,             // vdata
6772       Op.getOperand(3),  // rsrc
6773       Op.getOperand(4),  // vindex
6774       Op.getOperand(5),  // voffset
6775       Op.getOperand(6),  // soffset
6776       Op.getOperand(7),  // offset
6777       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6778       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6779       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
6780     };
6781     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6782                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6783     MemSDNode *M = cast<MemSDNode>(Op);
6784     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6785                                    M->getMemoryVT(), M->getMemOperand());
6786   }
6787 
6788   case Intrinsic::amdgcn_struct_tbuffer_store: {
6789     SDValue VData = Op.getOperand(2);
6790     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6791     if (IsD16)
6792       VData = handleD16VData(VData, DAG);
6793     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6794     SDValue Ops[] = {
6795       Chain,
6796       VData,             // vdata
6797       Op.getOperand(3),  // rsrc
6798       Op.getOperand(4),  // vindex
6799       Offsets.first,     // voffset
6800       Op.getOperand(6),  // soffset
6801       Offsets.second,    // offset
6802       Op.getOperand(7),  // format
6803       Op.getOperand(8),  // cachepolicy, swizzled buffer
6804       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
6805     };
6806     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6807                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6808     MemSDNode *M = cast<MemSDNode>(Op);
6809     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6810                                    M->getMemoryVT(), M->getMemOperand());
6811   }
6812 
6813   case Intrinsic::amdgcn_raw_tbuffer_store: {
6814     SDValue VData = Op.getOperand(2);
6815     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6816     if (IsD16)
6817       VData = handleD16VData(VData, DAG);
6818     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6819     SDValue Ops[] = {
6820       Chain,
6821       VData,             // vdata
6822       Op.getOperand(3),  // rsrc
6823       DAG.getConstant(0, DL, MVT::i32), // vindex
6824       Offsets.first,     // voffset
6825       Op.getOperand(5),  // soffset
6826       Offsets.second,    // offset
6827       Op.getOperand(6),  // format
6828       Op.getOperand(7),  // cachepolicy, swizzled buffer
6829       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
6830     };
6831     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6832                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6833     MemSDNode *M = cast<MemSDNode>(Op);
6834     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6835                                    M->getMemoryVT(), M->getMemOperand());
6836   }
6837 
6838   case Intrinsic::amdgcn_buffer_store:
6839   case Intrinsic::amdgcn_buffer_store_format: {
6840     SDValue VData = Op.getOperand(2);
6841     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6842     if (IsD16)
6843       VData = handleD16VData(VData, DAG);
6844     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6845     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6846     unsigned IdxEn = 1;
6847     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6848       IdxEn = Idx->getZExtValue() != 0;
6849     SDValue Ops[] = {
6850       Chain,
6851       VData,
6852       Op.getOperand(3), // rsrc
6853       Op.getOperand(4), // vindex
6854       SDValue(), // voffset -- will be set by setBufferOffsets
6855       SDValue(), // soffset -- will be set by setBufferOffsets
6856       SDValue(), // offset -- will be set by setBufferOffsets
6857       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6858       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6859     };
6860     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6861     // We don't know the offset if vindex is non-zero, so clear it.
6862     if (IdxEn)
6863       Offset = 0;
6864     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6865                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6866     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6867     MemSDNode *M = cast<MemSDNode>(Op);
6868     M->getMemOperand()->setOffset(Offset);
6869 
6870     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6871     EVT VDataType = VData.getValueType().getScalarType();
6872     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6873       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6874 
6875     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6876                                    M->getMemoryVT(), M->getMemOperand());
6877   }
6878 
6879   case Intrinsic::amdgcn_raw_buffer_store:
6880   case Intrinsic::amdgcn_raw_buffer_store_format: {
6881     const bool IsFormat =
6882         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
6883 
6884     SDValue VData = Op.getOperand(2);
6885     EVT VDataVT = VData.getValueType();
6886     EVT EltType = VDataVT.getScalarType();
6887     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6888     if (IsD16)
6889       VData = handleD16VData(VData, DAG);
6890 
6891     if (!isTypeLegal(VDataVT)) {
6892       VData =
6893           DAG.getNode(ISD::BITCAST, DL,
6894                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6895     }
6896 
6897     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6898     SDValue Ops[] = {
6899       Chain,
6900       VData,
6901       Op.getOperand(3), // rsrc
6902       DAG.getConstant(0, DL, MVT::i32), // vindex
6903       Offsets.first,    // voffset
6904       Op.getOperand(5), // soffset
6905       Offsets.second,   // offset
6906       Op.getOperand(6), // cachepolicy, swizzled buffer
6907       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6908     };
6909     unsigned Opc =
6910         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
6911     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6912     MemSDNode *M = cast<MemSDNode>(Op);
6913     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6914 
6915     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6916     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6917       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
6918 
6919     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6920                                    M->getMemoryVT(), M->getMemOperand());
6921   }
6922 
6923   case Intrinsic::amdgcn_struct_buffer_store:
6924   case Intrinsic::amdgcn_struct_buffer_store_format: {
6925     const bool IsFormat =
6926         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
6927 
6928     SDValue VData = Op.getOperand(2);
6929     EVT VDataVT = VData.getValueType();
6930     EVT EltType = VDataVT.getScalarType();
6931     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6932 
6933     if (IsD16)
6934       VData = handleD16VData(VData, DAG);
6935 
6936     if (!isTypeLegal(VDataVT)) {
6937       VData =
6938           DAG.getNode(ISD::BITCAST, DL,
6939                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6940     }
6941 
6942     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6943     SDValue Ops[] = {
6944       Chain,
6945       VData,
6946       Op.getOperand(3), // rsrc
6947       Op.getOperand(4), // vindex
6948       Offsets.first,    // voffset
6949       Op.getOperand(6), // soffset
6950       Offsets.second,   // offset
6951       Op.getOperand(7), // cachepolicy, swizzled buffer
6952       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6953     };
6954     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6955                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6956     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6957     MemSDNode *M = cast<MemSDNode>(Op);
6958     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6959                                                         Ops[3]));
6960 
6961     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6962     EVT VDataType = VData.getValueType().getScalarType();
6963     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6964       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6965 
6966     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6967                                    M->getMemoryVT(), M->getMemOperand());
6968   }
6969 
6970   case Intrinsic::amdgcn_buffer_atomic_fadd: {
6971     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6972     unsigned IdxEn = 1;
6973     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6974       IdxEn = Idx->getZExtValue() != 0;
6975     SDValue Ops[] = {
6976       Chain,
6977       Op.getOperand(2), // vdata
6978       Op.getOperand(3), // rsrc
6979       Op.getOperand(4), // vindex
6980       SDValue(),        // voffset -- will be set by setBufferOffsets
6981       SDValue(),        // soffset -- will be set by setBufferOffsets
6982       SDValue(),        // offset -- will be set by setBufferOffsets
6983       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6984       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6985     };
6986     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6987     // We don't know the offset if vindex is non-zero, so clear it.
6988     if (IdxEn)
6989       Offset = 0;
6990     EVT VT = Op.getOperand(2).getValueType();
6991 
6992     auto *M = cast<MemSDNode>(Op);
6993     M->getMemOperand()->setOffset(Offset);
6994     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
6995                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
6996 
6997     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6998                                    M->getMemOperand());
6999   }
7000 
7001   case Intrinsic::amdgcn_global_atomic_fadd: {
7002     SDValue Ops[] = {
7003       Chain,
7004       Op.getOperand(2), // ptr
7005       Op.getOperand(3)  // vdata
7006     };
7007     EVT VT = Op.getOperand(3).getValueType();
7008 
7009     auto *M = cast<MemSDNode>(Op);
7010     if (VT.isVector()) {
7011       return DAG.getMemIntrinsicNode(
7012         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7013         M->getMemOperand());
7014     }
7015 
7016     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7017                          DAG.getVTList(VT, MVT::Other), Ops,
7018                          M->getMemOperand()).getValue(1);
7019   }
7020   case Intrinsic::amdgcn_end_cf:
7021     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7022                                       Op->getOperand(2), Chain), 0);
7023 
7024   default: {
7025     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7026             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7027       return lowerImage(Op, ImageDimIntr, DAG);
7028 
7029     return Op;
7030   }
7031   }
7032 }
7033 
7034 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7035 // offset (the offset that is included in bounds checking and swizzling, to be
7036 // split between the instruction's voffset and immoffset fields) and soffset
7037 // (the offset that is excluded from bounds checking and swizzling, to go in
7038 // the instruction's soffset field).  This function takes the first kind of
7039 // offset and figures out how to split it between voffset and immoffset.
7040 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7041     SDValue Offset, SelectionDAG &DAG) const {
7042   SDLoc DL(Offset);
7043   const unsigned MaxImm = 4095;
7044   SDValue N0 = Offset;
7045   ConstantSDNode *C1 = nullptr;
7046 
7047   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7048     N0 = SDValue();
7049   else if (DAG.isBaseWithConstantOffset(N0)) {
7050     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7051     N0 = N0.getOperand(0);
7052   }
7053 
7054   if (C1) {
7055     unsigned ImmOffset = C1->getZExtValue();
7056     // If the immediate value is too big for the immoffset field, put the value
7057     // and -4096 into the immoffset field so that the value that is copied/added
7058     // for the voffset field is a multiple of 4096, and it stands more chance
7059     // of being CSEd with the copy/add for another similar load/store.
7060     // However, do not do that rounding down to a multiple of 4096 if that is a
7061     // negative number, as it appears to be illegal to have a negative offset
7062     // in the vgpr, even if adding the immediate offset makes it positive.
7063     unsigned Overflow = ImmOffset & ~MaxImm;
7064     ImmOffset -= Overflow;
7065     if ((int32_t)Overflow < 0) {
7066       Overflow += ImmOffset;
7067       ImmOffset = 0;
7068     }
7069     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7070     if (Overflow) {
7071       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7072       if (!N0)
7073         N0 = OverflowVal;
7074       else {
7075         SDValue Ops[] = { N0, OverflowVal };
7076         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7077       }
7078     }
7079   }
7080   if (!N0)
7081     N0 = DAG.getConstant(0, DL, MVT::i32);
7082   if (!C1)
7083     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7084   return {N0, SDValue(C1, 0)};
7085 }
7086 
7087 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7088 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7089 // pointed to by Offsets.
7090 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7091                                         SelectionDAG &DAG, SDValue *Offsets,
7092                                         unsigned Align) const {
7093   SDLoc DL(CombinedOffset);
7094   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7095     uint32_t Imm = C->getZExtValue();
7096     uint32_t SOffset, ImmOffset;
7097     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7098       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7099       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7100       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7101       return SOffset + ImmOffset;
7102     }
7103   }
7104   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7105     SDValue N0 = CombinedOffset.getOperand(0);
7106     SDValue N1 = CombinedOffset.getOperand(1);
7107     uint32_t SOffset, ImmOffset;
7108     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7109     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7110                                                 Subtarget, Align)) {
7111       Offsets[0] = N0;
7112       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7113       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7114       return 0;
7115     }
7116   }
7117   Offsets[0] = CombinedOffset;
7118   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7119   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7120   return 0;
7121 }
7122 
7123 // Handle 8 bit and 16 bit buffer loads
7124 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7125                                                      EVT LoadVT, SDLoc DL,
7126                                                      ArrayRef<SDValue> Ops,
7127                                                      MemSDNode *M) const {
7128   EVT IntVT = LoadVT.changeTypeToInteger();
7129   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7130          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7131 
7132   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7133   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7134                                                Ops, IntVT,
7135                                                M->getMemOperand());
7136   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7137   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7138 
7139   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7140 }
7141 
7142 // Handle 8 bit and 16 bit buffer stores
7143 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7144                                                       EVT VDataType, SDLoc DL,
7145                                                       SDValue Ops[],
7146                                                       MemSDNode *M) const {
7147   if (VDataType == MVT::f16)
7148     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7149 
7150   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7151   Ops[1] = BufferStoreExt;
7152   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7153                                  AMDGPUISD::BUFFER_STORE_SHORT;
7154   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7155   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7156                                      M->getMemOperand());
7157 }
7158 
7159 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7160                                  ISD::LoadExtType ExtType, SDValue Op,
7161                                  const SDLoc &SL, EVT VT) {
7162   if (VT.bitsLT(Op.getValueType()))
7163     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7164 
7165   switch (ExtType) {
7166   case ISD::SEXTLOAD:
7167     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7168   case ISD::ZEXTLOAD:
7169     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7170   case ISD::EXTLOAD:
7171     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7172   case ISD::NON_EXTLOAD:
7173     return Op;
7174   }
7175 
7176   llvm_unreachable("invalid ext type");
7177 }
7178 
7179 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7180   SelectionDAG &DAG = DCI.DAG;
7181   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7182     return SDValue();
7183 
7184   // FIXME: Constant loads should all be marked invariant.
7185   unsigned AS = Ld->getAddressSpace();
7186   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7187       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7188       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7189     return SDValue();
7190 
7191   // Don't do this early, since it may interfere with adjacent load merging for
7192   // illegal types. We can avoid losing alignment information for exotic types
7193   // pre-legalize.
7194   EVT MemVT = Ld->getMemoryVT();
7195   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7196       MemVT.getSizeInBits() >= 32)
7197     return SDValue();
7198 
7199   SDLoc SL(Ld);
7200 
7201   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7202          "unexpected vector extload");
7203 
7204   // TODO: Drop only high part of range.
7205   SDValue Ptr = Ld->getBasePtr();
7206   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7207                                 MVT::i32, SL, Ld->getChain(), Ptr,
7208                                 Ld->getOffset(),
7209                                 Ld->getPointerInfo(), MVT::i32,
7210                                 Ld->getAlignment(),
7211                                 Ld->getMemOperand()->getFlags(),
7212                                 Ld->getAAInfo(),
7213                                 nullptr); // Drop ranges
7214 
7215   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7216   if (MemVT.isFloatingPoint()) {
7217     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7218            "unexpected fp extload");
7219     TruncVT = MemVT.changeTypeToInteger();
7220   }
7221 
7222   SDValue Cvt = NewLoad;
7223   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7224     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7225                       DAG.getValueType(TruncVT));
7226   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7227              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7228     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7229   } else {
7230     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7231   }
7232 
7233   EVT VT = Ld->getValueType(0);
7234   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7235 
7236   DCI.AddToWorklist(Cvt.getNode());
7237 
7238   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7239   // the appropriate extension from the 32-bit load.
7240   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7241   DCI.AddToWorklist(Cvt.getNode());
7242 
7243   // Handle conversion back to floating point if necessary.
7244   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7245 
7246   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7247 }
7248 
7249 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7250   SDLoc DL(Op);
7251   LoadSDNode *Load = cast<LoadSDNode>(Op);
7252   ISD::LoadExtType ExtType = Load->getExtensionType();
7253   EVT MemVT = Load->getMemoryVT();
7254 
7255   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7256     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7257       return SDValue();
7258 
7259     // FIXME: Copied from PPC
7260     // First, load into 32 bits, then truncate to 1 bit.
7261 
7262     SDValue Chain = Load->getChain();
7263     SDValue BasePtr = Load->getBasePtr();
7264     MachineMemOperand *MMO = Load->getMemOperand();
7265 
7266     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7267 
7268     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7269                                    BasePtr, RealMemVT, MMO);
7270 
7271     if (!MemVT.isVector()) {
7272       SDValue Ops[] = {
7273         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7274         NewLD.getValue(1)
7275       };
7276 
7277       return DAG.getMergeValues(Ops, DL);
7278     }
7279 
7280     SmallVector<SDValue, 3> Elts;
7281     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7282       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7283                                 DAG.getConstant(I, DL, MVT::i32));
7284 
7285       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7286     }
7287 
7288     SDValue Ops[] = {
7289       DAG.getBuildVector(MemVT, DL, Elts),
7290       NewLD.getValue(1)
7291     };
7292 
7293     return DAG.getMergeValues(Ops, DL);
7294   }
7295 
7296   if (!MemVT.isVector())
7297     return SDValue();
7298 
7299   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7300          "Custom lowering for non-i32 vectors hasn't been implemented.");
7301 
7302   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7303                                       MemVT, *Load->getMemOperand())) {
7304     SDValue Ops[2];
7305     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7306     return DAG.getMergeValues(Ops, DL);
7307   }
7308 
7309   unsigned Alignment = Load->getAlignment();
7310   unsigned AS = Load->getAddressSpace();
7311   if (Subtarget->hasLDSMisalignedBug() &&
7312       AS == AMDGPUAS::FLAT_ADDRESS &&
7313       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7314     return SplitVectorLoad(Op, DAG);
7315   }
7316 
7317   MachineFunction &MF = DAG.getMachineFunction();
7318   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7319   // If there is a possibilty that flat instruction access scratch memory
7320   // then we need to use the same legalization rules we use for private.
7321   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7322       !Subtarget->hasMultiDwordFlatScratchAddressing())
7323     AS = MFI->hasFlatScratchInit() ?
7324          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7325 
7326   unsigned NumElements = MemVT.getVectorNumElements();
7327 
7328   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7329       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7330     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7331       if (MemVT.isPow2VectorType())
7332         return SDValue();
7333       if (NumElements == 3)
7334         return WidenVectorLoad(Op, DAG);
7335       return SplitVectorLoad(Op, DAG);
7336     }
7337     // Non-uniform loads will be selected to MUBUF instructions, so they
7338     // have the same legalization requirements as global and private
7339     // loads.
7340     //
7341   }
7342 
7343   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7344       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7345       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7346     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7347         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7348         Alignment >= 4 && NumElements < 32) {
7349       if (MemVT.isPow2VectorType())
7350         return SDValue();
7351       if (NumElements == 3)
7352         return WidenVectorLoad(Op, DAG);
7353       return SplitVectorLoad(Op, DAG);
7354     }
7355     // Non-uniform loads will be selected to MUBUF instructions, so they
7356     // have the same legalization requirements as global and private
7357     // loads.
7358     //
7359   }
7360   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7361       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7362       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7363       AS == AMDGPUAS::FLAT_ADDRESS) {
7364     if (NumElements > 4)
7365       return SplitVectorLoad(Op, DAG);
7366     // v3 loads not supported on SI.
7367     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7368       return WidenVectorLoad(Op, DAG);
7369     // v3 and v4 loads are supported for private and global memory.
7370     return SDValue();
7371   }
7372   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7373     // Depending on the setting of the private_element_size field in the
7374     // resource descriptor, we can only make private accesses up to a certain
7375     // size.
7376     switch (Subtarget->getMaxPrivateElementSize()) {
7377     case 4: {
7378       SDValue Ops[2];
7379       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7380       return DAG.getMergeValues(Ops, DL);
7381     }
7382     case 8:
7383       if (NumElements > 2)
7384         return SplitVectorLoad(Op, DAG);
7385       return SDValue();
7386     case 16:
7387       // Same as global/flat
7388       if (NumElements > 4)
7389         return SplitVectorLoad(Op, DAG);
7390       // v3 loads not supported on SI.
7391       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7392         return WidenVectorLoad(Op, DAG);
7393       return SDValue();
7394     default:
7395       llvm_unreachable("unsupported private_element_size");
7396     }
7397   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7398     // Use ds_read_b128 if possible.
7399     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7400         MemVT.getStoreSize() == 16)
7401       return SDValue();
7402 
7403     if (NumElements > 2)
7404       return SplitVectorLoad(Op, DAG);
7405 
7406     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7407     // address is negative, then the instruction is incorrectly treated as
7408     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7409     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7410     // load later in the SILoadStoreOptimizer.
7411     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7412         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7413         Load->getAlignment() < 8) {
7414       return SplitVectorLoad(Op, DAG);
7415     }
7416   }
7417   return SDValue();
7418 }
7419 
7420 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7421   EVT VT = Op.getValueType();
7422   assert(VT.getSizeInBits() == 64);
7423 
7424   SDLoc DL(Op);
7425   SDValue Cond = Op.getOperand(0);
7426 
7427   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7428   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7429 
7430   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7431   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7432 
7433   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7434   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7435 
7436   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7437 
7438   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7439   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7440 
7441   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7442 
7443   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7444   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7445 }
7446 
7447 // Catch division cases where we can use shortcuts with rcp and rsq
7448 // instructions.
7449 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7450                                               SelectionDAG &DAG) const {
7451   SDLoc SL(Op);
7452   SDValue LHS = Op.getOperand(0);
7453   SDValue RHS = Op.getOperand(1);
7454   EVT VT = Op.getValueType();
7455   const SDNodeFlags Flags = Op->getFlags();
7456 
7457   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7458                             Flags.hasApproximateFuncs();
7459 
7460   // Without !fpmath accuracy information, we can't do more because we don't
7461   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7462   if (!AllowInaccurateRcp)
7463     return SDValue();
7464 
7465   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7466     if (CLHS->isExactlyValue(1.0)) {
7467       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7468       // the CI documentation has a worst case error of 1 ulp.
7469       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7470       // use it as long as we aren't trying to use denormals.
7471       //
7472       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7473 
7474       // 1.0 / sqrt(x) -> rsq(x)
7475 
7476       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7477       // error seems really high at 2^29 ULP.
7478       if (RHS.getOpcode() == ISD::FSQRT)
7479         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7480 
7481       // 1.0 / x -> rcp(x)
7482       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7483     }
7484 
7485     // Same as for 1.0, but expand the sign out of the constant.
7486     if (CLHS->isExactlyValue(-1.0)) {
7487       // -1.0 / x -> rcp (fneg x)
7488       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7489       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7490     }
7491   }
7492 
7493   // Turn into multiply by the reciprocal.
7494   // x / y -> x * (1.0 / y)
7495   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7496   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7497 }
7498 
7499 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7500                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7501   if (GlueChain->getNumValues() <= 1) {
7502     return DAG.getNode(Opcode, SL, VT, A, B);
7503   }
7504 
7505   assert(GlueChain->getNumValues() == 3);
7506 
7507   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7508   switch (Opcode) {
7509   default: llvm_unreachable("no chain equivalent for opcode");
7510   case ISD::FMUL:
7511     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7512     break;
7513   }
7514 
7515   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7516                      GlueChain.getValue(2));
7517 }
7518 
7519 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7520                            EVT VT, SDValue A, SDValue B, SDValue C,
7521                            SDValue GlueChain) {
7522   if (GlueChain->getNumValues() <= 1) {
7523     return DAG.getNode(Opcode, SL, VT, A, B, C);
7524   }
7525 
7526   assert(GlueChain->getNumValues() == 3);
7527 
7528   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7529   switch (Opcode) {
7530   default: llvm_unreachable("no chain equivalent for opcode");
7531   case ISD::FMA:
7532     Opcode = AMDGPUISD::FMA_W_CHAIN;
7533     break;
7534   }
7535 
7536   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7537                      GlueChain.getValue(2));
7538 }
7539 
7540 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7541   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7542     return FastLowered;
7543 
7544   SDLoc SL(Op);
7545   SDValue Src0 = Op.getOperand(0);
7546   SDValue Src1 = Op.getOperand(1);
7547 
7548   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7549   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7550 
7551   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7552   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7553 
7554   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7555   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7556 
7557   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7558 }
7559 
7560 // Faster 2.5 ULP division that does not support denormals.
7561 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7562   SDLoc SL(Op);
7563   SDValue LHS = Op.getOperand(1);
7564   SDValue RHS = Op.getOperand(2);
7565 
7566   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7567 
7568   const APFloat K0Val(BitsToFloat(0x6f800000));
7569   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7570 
7571   const APFloat K1Val(BitsToFloat(0x2f800000));
7572   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7573 
7574   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7575 
7576   EVT SetCCVT =
7577     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7578 
7579   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7580 
7581   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7582 
7583   // TODO: Should this propagate fast-math-flags?
7584   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7585 
7586   // rcp does not support denormals.
7587   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7588 
7589   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7590 
7591   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7592 }
7593 
7594 // Returns immediate value for setting the F32 denorm mode when using the
7595 // S_DENORM_MODE instruction.
7596 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7597                                           const SDLoc &SL, const GCNSubtarget *ST) {
7598   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7599   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7600                                 ? FP_DENORM_FLUSH_NONE
7601                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7602 
7603   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7604   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7605 }
7606 
7607 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7608   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7609     return FastLowered;
7610 
7611   SDLoc SL(Op);
7612   SDValue LHS = Op.getOperand(0);
7613   SDValue RHS = Op.getOperand(1);
7614 
7615   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7616 
7617   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7618 
7619   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7620                                           RHS, RHS, LHS);
7621   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7622                                         LHS, RHS, LHS);
7623 
7624   // Denominator is scaled to not be denormal, so using rcp is ok.
7625   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7626                                   DenominatorScaled);
7627   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7628                                      DenominatorScaled);
7629 
7630   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7631                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7632                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7633   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7634 
7635   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7636 
7637   if (!HasFP32Denormals) {
7638     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7639 
7640     SDValue EnableDenorm;
7641     if (Subtarget->hasDenormModeInst()) {
7642       const SDValue EnableDenormValue =
7643           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7644 
7645       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7646                                  DAG.getEntryNode(), EnableDenormValue);
7647     } else {
7648       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7649                                                         SL, MVT::i32);
7650       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7651                                  DAG.getEntryNode(), EnableDenormValue,
7652                                  BitField);
7653     }
7654 
7655     SDValue Ops[3] = {
7656       NegDivScale0,
7657       EnableDenorm.getValue(0),
7658       EnableDenorm.getValue(1)
7659     };
7660 
7661     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7662   }
7663 
7664   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7665                              ApproxRcp, One, NegDivScale0);
7666 
7667   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7668                              ApproxRcp, Fma0);
7669 
7670   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7671                            Fma1, Fma1);
7672 
7673   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7674                              NumeratorScaled, Mul);
7675 
7676   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7677 
7678   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7679                              NumeratorScaled, Fma3);
7680 
7681   if (!HasFP32Denormals) {
7682     SDValue DisableDenorm;
7683     if (Subtarget->hasDenormModeInst()) {
7684       const SDValue DisableDenormValue =
7685           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7686 
7687       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7688                                   Fma4.getValue(1), DisableDenormValue,
7689                                   Fma4.getValue(2));
7690     } else {
7691       const SDValue DisableDenormValue =
7692           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7693 
7694       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7695                                   Fma4.getValue(1), DisableDenormValue,
7696                                   BitField, Fma4.getValue(2));
7697     }
7698 
7699     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7700                                       DisableDenorm, DAG.getRoot());
7701     DAG.setRoot(OutputChain);
7702   }
7703 
7704   SDValue Scale = NumeratorScaled.getValue(1);
7705   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7706                              Fma4, Fma1, Fma3, Scale);
7707 
7708   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7709 }
7710 
7711 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7712   if (DAG.getTarget().Options.UnsafeFPMath)
7713     return lowerFastUnsafeFDIV(Op, DAG);
7714 
7715   SDLoc SL(Op);
7716   SDValue X = Op.getOperand(0);
7717   SDValue Y = Op.getOperand(1);
7718 
7719   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7720 
7721   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7722 
7723   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7724 
7725   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7726 
7727   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7728 
7729   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7730 
7731   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7732 
7733   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7734 
7735   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7736 
7737   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7738   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7739 
7740   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7741                              NegDivScale0, Mul, DivScale1);
7742 
7743   SDValue Scale;
7744 
7745   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7746     // Workaround a hardware bug on SI where the condition output from div_scale
7747     // is not usable.
7748 
7749     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7750 
7751     // Figure out if the scale to use for div_fmas.
7752     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7753     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7754     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7755     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7756 
7757     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7758     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7759 
7760     SDValue Scale0Hi
7761       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7762     SDValue Scale1Hi
7763       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7764 
7765     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7766     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7767     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7768   } else {
7769     Scale = DivScale1.getValue(1);
7770   }
7771 
7772   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7773                              Fma4, Fma3, Mul, Scale);
7774 
7775   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7776 }
7777 
7778 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7779   EVT VT = Op.getValueType();
7780 
7781   if (VT == MVT::f32)
7782     return LowerFDIV32(Op, DAG);
7783 
7784   if (VT == MVT::f64)
7785     return LowerFDIV64(Op, DAG);
7786 
7787   if (VT == MVT::f16)
7788     return LowerFDIV16(Op, DAG);
7789 
7790   llvm_unreachable("Unexpected type for fdiv");
7791 }
7792 
7793 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7794   SDLoc DL(Op);
7795   StoreSDNode *Store = cast<StoreSDNode>(Op);
7796   EVT VT = Store->getMemoryVT();
7797 
7798   if (VT == MVT::i1) {
7799     return DAG.getTruncStore(Store->getChain(), DL,
7800        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7801        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7802   }
7803 
7804   assert(VT.isVector() &&
7805          Store->getValue().getValueType().getScalarType() == MVT::i32);
7806 
7807   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7808                                       VT, *Store->getMemOperand())) {
7809     return expandUnalignedStore(Store, DAG);
7810   }
7811 
7812   unsigned AS = Store->getAddressSpace();
7813   if (Subtarget->hasLDSMisalignedBug() &&
7814       AS == AMDGPUAS::FLAT_ADDRESS &&
7815       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7816     return SplitVectorStore(Op, DAG);
7817   }
7818 
7819   MachineFunction &MF = DAG.getMachineFunction();
7820   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7821   // If there is a possibilty that flat instruction access scratch memory
7822   // then we need to use the same legalization rules we use for private.
7823   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7824       !Subtarget->hasMultiDwordFlatScratchAddressing())
7825     AS = MFI->hasFlatScratchInit() ?
7826          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7827 
7828   unsigned NumElements = VT.getVectorNumElements();
7829   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7830       AS == AMDGPUAS::FLAT_ADDRESS) {
7831     if (NumElements > 4)
7832       return SplitVectorStore(Op, DAG);
7833     // v3 stores not supported on SI.
7834     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7835       return SplitVectorStore(Op, DAG);
7836     return SDValue();
7837   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7838     switch (Subtarget->getMaxPrivateElementSize()) {
7839     case 4:
7840       return scalarizeVectorStore(Store, DAG);
7841     case 8:
7842       if (NumElements > 2)
7843         return SplitVectorStore(Op, DAG);
7844       return SDValue();
7845     case 16:
7846       if (NumElements > 4 || NumElements == 3)
7847         return SplitVectorStore(Op, DAG);
7848       return SDValue();
7849     default:
7850       llvm_unreachable("unsupported private_element_size");
7851     }
7852   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7853     // Use ds_write_b128 if possible.
7854     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7855         VT.getStoreSize() == 16 && NumElements != 3)
7856       return SDValue();
7857 
7858     if (NumElements > 2)
7859       return SplitVectorStore(Op, DAG);
7860 
7861     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7862     // address is negative, then the instruction is incorrectly treated as
7863     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7864     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7865     // store later in the SILoadStoreOptimizer.
7866     if (!Subtarget->hasUsableDSOffset() &&
7867         NumElements == 2 && VT.getStoreSize() == 8 &&
7868         Store->getAlignment() < 8) {
7869       return SplitVectorStore(Op, DAG);
7870     }
7871 
7872     return SDValue();
7873   } else {
7874     llvm_unreachable("unhandled address space");
7875   }
7876 }
7877 
7878 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7879   SDLoc DL(Op);
7880   EVT VT = Op.getValueType();
7881   SDValue Arg = Op.getOperand(0);
7882   SDValue TrigVal;
7883 
7884   // TODO: Should this propagate fast-math-flags?
7885 
7886   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7887 
7888   if (Subtarget->hasTrigReducedRange()) {
7889     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7890     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7891   } else {
7892     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7893   }
7894 
7895   switch (Op.getOpcode()) {
7896   case ISD::FCOS:
7897     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7898   case ISD::FSIN:
7899     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7900   default:
7901     llvm_unreachable("Wrong trig opcode");
7902   }
7903 }
7904 
7905 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7906   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7907   assert(AtomicNode->isCompareAndSwap());
7908   unsigned AS = AtomicNode->getAddressSpace();
7909 
7910   // No custom lowering required for local address space
7911   if (!isFlatGlobalAddrSpace(AS))
7912     return Op;
7913 
7914   // Non-local address space requires custom lowering for atomic compare
7915   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7916   SDLoc DL(Op);
7917   SDValue ChainIn = Op.getOperand(0);
7918   SDValue Addr = Op.getOperand(1);
7919   SDValue Old = Op.getOperand(2);
7920   SDValue New = Op.getOperand(3);
7921   EVT VT = Op.getValueType();
7922   MVT SimpleVT = VT.getSimpleVT();
7923   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7924 
7925   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
7926   SDValue Ops[] = { ChainIn, Addr, NewOld };
7927 
7928   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7929                                  Ops, VT, AtomicNode->getMemOperand());
7930 }
7931 
7932 //===----------------------------------------------------------------------===//
7933 // Custom DAG optimizations
7934 //===----------------------------------------------------------------------===//
7935 
7936 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
7937                                                      DAGCombinerInfo &DCI) const {
7938   EVT VT = N->getValueType(0);
7939   EVT ScalarVT = VT.getScalarType();
7940   if (ScalarVT != MVT::f32)
7941     return SDValue();
7942 
7943   SelectionDAG &DAG = DCI.DAG;
7944   SDLoc DL(N);
7945 
7946   SDValue Src = N->getOperand(0);
7947   EVT SrcVT = Src.getValueType();
7948 
7949   // TODO: We could try to match extracting the higher bytes, which would be
7950   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7951   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7952   // about in practice.
7953   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
7954     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7955       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7956       DCI.AddToWorklist(Cvt.getNode());
7957       return Cvt;
7958     }
7959   }
7960 
7961   return SDValue();
7962 }
7963 
7964 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7965 
7966 // This is a variant of
7967 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7968 //
7969 // The normal DAG combiner will do this, but only if the add has one use since
7970 // that would increase the number of instructions.
7971 //
7972 // This prevents us from seeing a constant offset that can be folded into a
7973 // memory instruction's addressing mode. If we know the resulting add offset of
7974 // a pointer can be folded into an addressing offset, we can replace the pointer
7975 // operand with the add of new constant offset. This eliminates one of the uses,
7976 // and may allow the remaining use to also be simplified.
7977 //
7978 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7979                                                unsigned AddrSpace,
7980                                                EVT MemVT,
7981                                                DAGCombinerInfo &DCI) const {
7982   SDValue N0 = N->getOperand(0);
7983   SDValue N1 = N->getOperand(1);
7984 
7985   // We only do this to handle cases where it's profitable when there are
7986   // multiple uses of the add, so defer to the standard combine.
7987   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
7988       N0->hasOneUse())
7989     return SDValue();
7990 
7991   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
7992   if (!CN1)
7993     return SDValue();
7994 
7995   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7996   if (!CAdd)
7997     return SDValue();
7998 
7999   // If the resulting offset is too large, we can't fold it into the addressing
8000   // mode offset.
8001   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8002   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8003 
8004   AddrMode AM;
8005   AM.HasBaseReg = true;
8006   AM.BaseOffs = Offset.getSExtValue();
8007   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8008     return SDValue();
8009 
8010   SelectionDAG &DAG = DCI.DAG;
8011   SDLoc SL(N);
8012   EVT VT = N->getValueType(0);
8013 
8014   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8015   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8016 
8017   SDNodeFlags Flags;
8018   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8019                           (N0.getOpcode() == ISD::OR ||
8020                            N0->getFlags().hasNoUnsignedWrap()));
8021 
8022   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8023 }
8024 
8025 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8026                                                   DAGCombinerInfo &DCI) const {
8027   SDValue Ptr = N->getBasePtr();
8028   SelectionDAG &DAG = DCI.DAG;
8029   SDLoc SL(N);
8030 
8031   // TODO: We could also do this for multiplies.
8032   if (Ptr.getOpcode() == ISD::SHL) {
8033     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8034                                           N->getMemoryVT(), DCI);
8035     if (NewPtr) {
8036       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8037 
8038       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8039       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8040     }
8041   }
8042 
8043   return SDValue();
8044 }
8045 
8046 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8047   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8048          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8049          (Opc == ISD::XOR && Val == 0);
8050 }
8051 
8052 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8053 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8054 // integer combine opportunities since most 64-bit operations are decomposed
8055 // this way.  TODO: We won't want this for SALU especially if it is an inline
8056 // immediate.
8057 SDValue SITargetLowering::splitBinaryBitConstantOp(
8058   DAGCombinerInfo &DCI,
8059   const SDLoc &SL,
8060   unsigned Opc, SDValue LHS,
8061   const ConstantSDNode *CRHS) const {
8062   uint64_t Val = CRHS->getZExtValue();
8063   uint32_t ValLo = Lo_32(Val);
8064   uint32_t ValHi = Hi_32(Val);
8065   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8066 
8067     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8068          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8069         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8070     // If we need to materialize a 64-bit immediate, it will be split up later
8071     // anyway. Avoid creating the harder to understand 64-bit immediate
8072     // materialization.
8073     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8074   }
8075 
8076   return SDValue();
8077 }
8078 
8079 // Returns true if argument is a boolean value which is not serialized into
8080 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8081 static bool isBoolSGPR(SDValue V) {
8082   if (V.getValueType() != MVT::i1)
8083     return false;
8084   switch (V.getOpcode()) {
8085   default: break;
8086   case ISD::SETCC:
8087   case ISD::AND:
8088   case ISD::OR:
8089   case ISD::XOR:
8090   case AMDGPUISD::FP_CLASS:
8091     return true;
8092   }
8093   return false;
8094 }
8095 
8096 // If a constant has all zeroes or all ones within each byte return it.
8097 // Otherwise return 0.
8098 static uint32_t getConstantPermuteMask(uint32_t C) {
8099   // 0xff for any zero byte in the mask
8100   uint32_t ZeroByteMask = 0;
8101   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8102   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8103   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8104   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8105   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8106   if ((NonZeroByteMask & C) != NonZeroByteMask)
8107     return 0; // Partial bytes selected.
8108   return C;
8109 }
8110 
8111 // Check if a node selects whole bytes from its operand 0 starting at a byte
8112 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8113 // or -1 if not succeeded.
8114 // Note byte select encoding:
8115 // value 0-3 selects corresponding source byte;
8116 // value 0xc selects zero;
8117 // value 0xff selects 0xff.
8118 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8119   assert(V.getValueSizeInBits() == 32);
8120 
8121   if (V.getNumOperands() != 2)
8122     return ~0;
8123 
8124   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8125   if (!N1)
8126     return ~0;
8127 
8128   uint32_t C = N1->getZExtValue();
8129 
8130   switch (V.getOpcode()) {
8131   default:
8132     break;
8133   case ISD::AND:
8134     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8135       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8136     }
8137     break;
8138 
8139   case ISD::OR:
8140     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8141       return (0x03020100 & ~ConstMask) | ConstMask;
8142     }
8143     break;
8144 
8145   case ISD::SHL:
8146     if (C % 8)
8147       return ~0;
8148 
8149     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8150 
8151   case ISD::SRL:
8152     if (C % 8)
8153       return ~0;
8154 
8155     return uint32_t(0x0c0c0c0c03020100ull >> C);
8156   }
8157 
8158   return ~0;
8159 }
8160 
8161 SDValue SITargetLowering::performAndCombine(SDNode *N,
8162                                             DAGCombinerInfo &DCI) const {
8163   if (DCI.isBeforeLegalize())
8164     return SDValue();
8165 
8166   SelectionDAG &DAG = DCI.DAG;
8167   EVT VT = N->getValueType(0);
8168   SDValue LHS = N->getOperand(0);
8169   SDValue RHS = N->getOperand(1);
8170 
8171 
8172   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8173   if (VT == MVT::i64 && CRHS) {
8174     if (SDValue Split
8175         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8176       return Split;
8177   }
8178 
8179   if (CRHS && VT == MVT::i32) {
8180     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8181     // nb = number of trailing zeroes in mask
8182     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8183     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8184     uint64_t Mask = CRHS->getZExtValue();
8185     unsigned Bits = countPopulation(Mask);
8186     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8187         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8188       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8189         unsigned Shift = CShift->getZExtValue();
8190         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8191         unsigned Offset = NB + Shift;
8192         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8193           SDLoc SL(N);
8194           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8195                                     LHS->getOperand(0),
8196                                     DAG.getConstant(Offset, SL, MVT::i32),
8197                                     DAG.getConstant(Bits, SL, MVT::i32));
8198           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8199           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8200                                     DAG.getValueType(NarrowVT));
8201           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8202                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8203           return Shl;
8204         }
8205       }
8206     }
8207 
8208     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8209     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8210         isa<ConstantSDNode>(LHS.getOperand(2))) {
8211       uint32_t Sel = getConstantPermuteMask(Mask);
8212       if (!Sel)
8213         return SDValue();
8214 
8215       // Select 0xc for all zero bytes
8216       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8217       SDLoc DL(N);
8218       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8219                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8220     }
8221   }
8222 
8223   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8224   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8225   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8226     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8227     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8228 
8229     SDValue X = LHS.getOperand(0);
8230     SDValue Y = RHS.getOperand(0);
8231     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8232       return SDValue();
8233 
8234     if (LCC == ISD::SETO) {
8235       if (X != LHS.getOperand(1))
8236         return SDValue();
8237 
8238       if (RCC == ISD::SETUNE) {
8239         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8240         if (!C1 || !C1->isInfinity() || C1->isNegative())
8241           return SDValue();
8242 
8243         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8244                               SIInstrFlags::N_SUBNORMAL |
8245                               SIInstrFlags::N_ZERO |
8246                               SIInstrFlags::P_ZERO |
8247                               SIInstrFlags::P_SUBNORMAL |
8248                               SIInstrFlags::P_NORMAL;
8249 
8250         static_assert(((~(SIInstrFlags::S_NAN |
8251                           SIInstrFlags::Q_NAN |
8252                           SIInstrFlags::N_INFINITY |
8253                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8254                       "mask not equal");
8255 
8256         SDLoc DL(N);
8257         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8258                            X, DAG.getConstant(Mask, DL, MVT::i32));
8259       }
8260     }
8261   }
8262 
8263   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8264     std::swap(LHS, RHS);
8265 
8266   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8267       RHS.hasOneUse()) {
8268     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8269     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8270     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8271     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8272     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8273         (RHS.getOperand(0) == LHS.getOperand(0) &&
8274          LHS.getOperand(0) == LHS.getOperand(1))) {
8275       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8276       unsigned NewMask = LCC == ISD::SETO ?
8277         Mask->getZExtValue() & ~OrdMask :
8278         Mask->getZExtValue() & OrdMask;
8279 
8280       SDLoc DL(N);
8281       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8282                          DAG.getConstant(NewMask, DL, MVT::i32));
8283     }
8284   }
8285 
8286   if (VT == MVT::i32 &&
8287       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8288     // and x, (sext cc from i1) => select cc, x, 0
8289     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8290       std::swap(LHS, RHS);
8291     if (isBoolSGPR(RHS.getOperand(0)))
8292       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8293                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8294   }
8295 
8296   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8297   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8298   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8299       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8300     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8301     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8302     if (LHSMask != ~0u && RHSMask != ~0u) {
8303       // Canonicalize the expression in an attempt to have fewer unique masks
8304       // and therefore fewer registers used to hold the masks.
8305       if (LHSMask > RHSMask) {
8306         std::swap(LHSMask, RHSMask);
8307         std::swap(LHS, RHS);
8308       }
8309 
8310       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8311       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8312       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8313       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8314 
8315       // Check of we need to combine values from two sources within a byte.
8316       if (!(LHSUsedLanes & RHSUsedLanes) &&
8317           // If we select high and lower word keep it for SDWA.
8318           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8319           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8320         // Each byte in each mask is either selector mask 0-3, or has higher
8321         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8322         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8323         // mask which is not 0xff wins. By anding both masks we have a correct
8324         // result except that 0x0c shall be corrected to give 0x0c only.
8325         uint32_t Mask = LHSMask & RHSMask;
8326         for (unsigned I = 0; I < 32; I += 8) {
8327           uint32_t ByteSel = 0xff << I;
8328           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8329             Mask &= (0x0c << I) & 0xffffffff;
8330         }
8331 
8332         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8333         // or 0x0c.
8334         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8335         SDLoc DL(N);
8336 
8337         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8338                            LHS.getOperand(0), RHS.getOperand(0),
8339                            DAG.getConstant(Sel, DL, MVT::i32));
8340       }
8341     }
8342   }
8343 
8344   return SDValue();
8345 }
8346 
8347 SDValue SITargetLowering::performOrCombine(SDNode *N,
8348                                            DAGCombinerInfo &DCI) const {
8349   SelectionDAG &DAG = DCI.DAG;
8350   SDValue LHS = N->getOperand(0);
8351   SDValue RHS = N->getOperand(1);
8352 
8353   EVT VT = N->getValueType(0);
8354   if (VT == MVT::i1) {
8355     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8356     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8357         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8358       SDValue Src = LHS.getOperand(0);
8359       if (Src != RHS.getOperand(0))
8360         return SDValue();
8361 
8362       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8363       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8364       if (!CLHS || !CRHS)
8365         return SDValue();
8366 
8367       // Only 10 bits are used.
8368       static const uint32_t MaxMask = 0x3ff;
8369 
8370       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8371       SDLoc DL(N);
8372       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8373                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8374     }
8375 
8376     return SDValue();
8377   }
8378 
8379   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8380   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8381       LHS.getOpcode() == AMDGPUISD::PERM &&
8382       isa<ConstantSDNode>(LHS.getOperand(2))) {
8383     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8384     if (!Sel)
8385       return SDValue();
8386 
8387     Sel |= LHS.getConstantOperandVal(2);
8388     SDLoc DL(N);
8389     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8390                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8391   }
8392 
8393   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8394   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8395   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8396       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8397     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8398     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8399     if (LHSMask != ~0u && RHSMask != ~0u) {
8400       // Canonicalize the expression in an attempt to have fewer unique masks
8401       // and therefore fewer registers used to hold the masks.
8402       if (LHSMask > RHSMask) {
8403         std::swap(LHSMask, RHSMask);
8404         std::swap(LHS, RHS);
8405       }
8406 
8407       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8408       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8409       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8410       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8411 
8412       // Check of we need to combine values from two sources within a byte.
8413       if (!(LHSUsedLanes & RHSUsedLanes) &&
8414           // If we select high and lower word keep it for SDWA.
8415           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8416           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8417         // Kill zero bytes selected by other mask. Zero value is 0xc.
8418         LHSMask &= ~RHSUsedLanes;
8419         RHSMask &= ~LHSUsedLanes;
8420         // Add 4 to each active LHS lane
8421         LHSMask |= LHSUsedLanes & 0x04040404;
8422         // Combine masks
8423         uint32_t Sel = LHSMask | RHSMask;
8424         SDLoc DL(N);
8425 
8426         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8427                            LHS.getOperand(0), RHS.getOperand(0),
8428                            DAG.getConstant(Sel, DL, MVT::i32));
8429       }
8430     }
8431   }
8432 
8433   if (VT != MVT::i64)
8434     return SDValue();
8435 
8436   // TODO: This could be a generic combine with a predicate for extracting the
8437   // high half of an integer being free.
8438 
8439   // (or i64:x, (zero_extend i32:y)) ->
8440   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8441   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8442       RHS.getOpcode() != ISD::ZERO_EXTEND)
8443     std::swap(LHS, RHS);
8444 
8445   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8446     SDValue ExtSrc = RHS.getOperand(0);
8447     EVT SrcVT = ExtSrc.getValueType();
8448     if (SrcVT == MVT::i32) {
8449       SDLoc SL(N);
8450       SDValue LowLHS, HiBits;
8451       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8452       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8453 
8454       DCI.AddToWorklist(LowOr.getNode());
8455       DCI.AddToWorklist(HiBits.getNode());
8456 
8457       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8458                                 LowOr, HiBits);
8459       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8460     }
8461   }
8462 
8463   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8464   if (CRHS) {
8465     if (SDValue Split
8466           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8467       return Split;
8468   }
8469 
8470   return SDValue();
8471 }
8472 
8473 SDValue SITargetLowering::performXorCombine(SDNode *N,
8474                                             DAGCombinerInfo &DCI) const {
8475   EVT VT = N->getValueType(0);
8476   if (VT != MVT::i64)
8477     return SDValue();
8478 
8479   SDValue LHS = N->getOperand(0);
8480   SDValue RHS = N->getOperand(1);
8481 
8482   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8483   if (CRHS) {
8484     if (SDValue Split
8485           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8486       return Split;
8487   }
8488 
8489   return SDValue();
8490 }
8491 
8492 // Instructions that will be lowered with a final instruction that zeros the
8493 // high result bits.
8494 // XXX - probably only need to list legal operations.
8495 static bool fp16SrcZerosHighBits(unsigned Opc) {
8496   switch (Opc) {
8497   case ISD::FADD:
8498   case ISD::FSUB:
8499   case ISD::FMUL:
8500   case ISD::FDIV:
8501   case ISD::FREM:
8502   case ISD::FMA:
8503   case ISD::FMAD:
8504   case ISD::FCANONICALIZE:
8505   case ISD::FP_ROUND:
8506   case ISD::UINT_TO_FP:
8507   case ISD::SINT_TO_FP:
8508   case ISD::FABS:
8509     // Fabs is lowered to a bit operation, but it's an and which will clear the
8510     // high bits anyway.
8511   case ISD::FSQRT:
8512   case ISD::FSIN:
8513   case ISD::FCOS:
8514   case ISD::FPOWI:
8515   case ISD::FPOW:
8516   case ISD::FLOG:
8517   case ISD::FLOG2:
8518   case ISD::FLOG10:
8519   case ISD::FEXP:
8520   case ISD::FEXP2:
8521   case ISD::FCEIL:
8522   case ISD::FTRUNC:
8523   case ISD::FRINT:
8524   case ISD::FNEARBYINT:
8525   case ISD::FROUND:
8526   case ISD::FFLOOR:
8527   case ISD::FMINNUM:
8528   case ISD::FMAXNUM:
8529   case AMDGPUISD::FRACT:
8530   case AMDGPUISD::CLAMP:
8531   case AMDGPUISD::COS_HW:
8532   case AMDGPUISD::SIN_HW:
8533   case AMDGPUISD::FMIN3:
8534   case AMDGPUISD::FMAX3:
8535   case AMDGPUISD::FMED3:
8536   case AMDGPUISD::FMAD_FTZ:
8537   case AMDGPUISD::RCP:
8538   case AMDGPUISD::RSQ:
8539   case AMDGPUISD::RCP_IFLAG:
8540   case AMDGPUISD::LDEXP:
8541     return true;
8542   default:
8543     // fcopysign, select and others may be lowered to 32-bit bit operations
8544     // which don't zero the high bits.
8545     return false;
8546   }
8547 }
8548 
8549 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8550                                                    DAGCombinerInfo &DCI) const {
8551   if (!Subtarget->has16BitInsts() ||
8552       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8553     return SDValue();
8554 
8555   EVT VT = N->getValueType(0);
8556   if (VT != MVT::i32)
8557     return SDValue();
8558 
8559   SDValue Src = N->getOperand(0);
8560   if (Src.getValueType() != MVT::i16)
8561     return SDValue();
8562 
8563   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8564   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8565   if (Src.getOpcode() == ISD::BITCAST) {
8566     SDValue BCSrc = Src.getOperand(0);
8567     if (BCSrc.getValueType() == MVT::f16 &&
8568         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8569       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8570   }
8571 
8572   return SDValue();
8573 }
8574 
8575 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8576                                                         DAGCombinerInfo &DCI)
8577                                                         const {
8578   SDValue Src = N->getOperand(0);
8579   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8580 
8581   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8582       VTSign->getVT() == MVT::i8) ||
8583       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8584       VTSign->getVT() == MVT::i16)) &&
8585       Src.hasOneUse()) {
8586     auto *M = cast<MemSDNode>(Src);
8587     SDValue Ops[] = {
8588       Src.getOperand(0), // Chain
8589       Src.getOperand(1), // rsrc
8590       Src.getOperand(2), // vindex
8591       Src.getOperand(3), // voffset
8592       Src.getOperand(4), // soffset
8593       Src.getOperand(5), // offset
8594       Src.getOperand(6),
8595       Src.getOperand(7)
8596     };
8597     // replace with BUFFER_LOAD_BYTE/SHORT
8598     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8599                                          Src.getOperand(0).getValueType());
8600     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8601                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8602     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8603                                                           ResList,
8604                                                           Ops, M->getMemoryVT(),
8605                                                           M->getMemOperand());
8606     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8607                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8608   }
8609   return SDValue();
8610 }
8611 
8612 SDValue SITargetLowering::performClassCombine(SDNode *N,
8613                                               DAGCombinerInfo &DCI) const {
8614   SelectionDAG &DAG = DCI.DAG;
8615   SDValue Mask = N->getOperand(1);
8616 
8617   // fp_class x, 0 -> false
8618   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8619     if (CMask->isNullValue())
8620       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8621   }
8622 
8623   if (N->getOperand(0).isUndef())
8624     return DAG.getUNDEF(MVT::i1);
8625 
8626   return SDValue();
8627 }
8628 
8629 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8630                                             DAGCombinerInfo &DCI) const {
8631   EVT VT = N->getValueType(0);
8632   SDValue N0 = N->getOperand(0);
8633 
8634   if (N0.isUndef())
8635     return N0;
8636 
8637   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8638                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8639     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8640                            N->getFlags());
8641   }
8642 
8643   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8644     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8645                            N0.getOperand(0), N->getFlags());
8646   }
8647 
8648   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8649 }
8650 
8651 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8652                                        unsigned MaxDepth) const {
8653   unsigned Opcode = Op.getOpcode();
8654   if (Opcode == ISD::FCANONICALIZE)
8655     return true;
8656 
8657   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8658     auto F = CFP->getValueAPF();
8659     if (F.isNaN() && F.isSignaling())
8660       return false;
8661     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8662   }
8663 
8664   // If source is a result of another standard FP operation it is already in
8665   // canonical form.
8666   if (MaxDepth == 0)
8667     return false;
8668 
8669   switch (Opcode) {
8670   // These will flush denorms if required.
8671   case ISD::FADD:
8672   case ISD::FSUB:
8673   case ISD::FMUL:
8674   case ISD::FCEIL:
8675   case ISD::FFLOOR:
8676   case ISD::FMA:
8677   case ISD::FMAD:
8678   case ISD::FSQRT:
8679   case ISD::FDIV:
8680   case ISD::FREM:
8681   case ISD::FP_ROUND:
8682   case ISD::FP_EXTEND:
8683   case AMDGPUISD::FMUL_LEGACY:
8684   case AMDGPUISD::FMAD_FTZ:
8685   case AMDGPUISD::RCP:
8686   case AMDGPUISD::RSQ:
8687   case AMDGPUISD::RSQ_CLAMP:
8688   case AMDGPUISD::RCP_LEGACY:
8689   case AMDGPUISD::RSQ_LEGACY:
8690   case AMDGPUISD::RCP_IFLAG:
8691   case AMDGPUISD::TRIG_PREOP:
8692   case AMDGPUISD::DIV_SCALE:
8693   case AMDGPUISD::DIV_FMAS:
8694   case AMDGPUISD::DIV_FIXUP:
8695   case AMDGPUISD::FRACT:
8696   case AMDGPUISD::LDEXP:
8697   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8698   case AMDGPUISD::CVT_F32_UBYTE0:
8699   case AMDGPUISD::CVT_F32_UBYTE1:
8700   case AMDGPUISD::CVT_F32_UBYTE2:
8701   case AMDGPUISD::CVT_F32_UBYTE3:
8702     return true;
8703 
8704   // It can/will be lowered or combined as a bit operation.
8705   // Need to check their input recursively to handle.
8706   case ISD::FNEG:
8707   case ISD::FABS:
8708   case ISD::FCOPYSIGN:
8709     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8710 
8711   case ISD::FSIN:
8712   case ISD::FCOS:
8713   case ISD::FSINCOS:
8714     return Op.getValueType().getScalarType() != MVT::f16;
8715 
8716   case ISD::FMINNUM:
8717   case ISD::FMAXNUM:
8718   case ISD::FMINNUM_IEEE:
8719   case ISD::FMAXNUM_IEEE:
8720   case AMDGPUISD::CLAMP:
8721   case AMDGPUISD::FMED3:
8722   case AMDGPUISD::FMAX3:
8723   case AMDGPUISD::FMIN3: {
8724     // FIXME: Shouldn't treat the generic operations different based these.
8725     // However, we aren't really required to flush the result from
8726     // minnum/maxnum..
8727 
8728     // snans will be quieted, so we only need to worry about denormals.
8729     if (Subtarget->supportsMinMaxDenormModes() ||
8730         denormalsEnabledForType(DAG, Op.getValueType()))
8731       return true;
8732 
8733     // Flushing may be required.
8734     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8735     // targets need to check their input recursively.
8736 
8737     // FIXME: Does this apply with clamp? It's implemented with max.
8738     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8739       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8740         return false;
8741     }
8742 
8743     return true;
8744   }
8745   case ISD::SELECT: {
8746     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8747            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8748   }
8749   case ISD::BUILD_VECTOR: {
8750     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8751       SDValue SrcOp = Op.getOperand(i);
8752       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8753         return false;
8754     }
8755 
8756     return true;
8757   }
8758   case ISD::EXTRACT_VECTOR_ELT:
8759   case ISD::EXTRACT_SUBVECTOR: {
8760     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8761   }
8762   case ISD::INSERT_VECTOR_ELT: {
8763     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8764            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8765   }
8766   case ISD::UNDEF:
8767     // Could be anything.
8768     return false;
8769 
8770   case ISD::BITCAST: {
8771     // Hack round the mess we make when legalizing extract_vector_elt
8772     SDValue Src = Op.getOperand(0);
8773     if (Src.getValueType() == MVT::i16 &&
8774         Src.getOpcode() == ISD::TRUNCATE) {
8775       SDValue TruncSrc = Src.getOperand(0);
8776       if (TruncSrc.getValueType() == MVT::i32 &&
8777           TruncSrc.getOpcode() == ISD::BITCAST &&
8778           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8779         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8780       }
8781     }
8782 
8783     return false;
8784   }
8785   case ISD::INTRINSIC_WO_CHAIN: {
8786     unsigned IntrinsicID
8787       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8788     // TODO: Handle more intrinsics
8789     switch (IntrinsicID) {
8790     case Intrinsic::amdgcn_cvt_pkrtz:
8791     case Intrinsic::amdgcn_cubeid:
8792     case Intrinsic::amdgcn_frexp_mant:
8793     case Intrinsic::amdgcn_fdot2:
8794       return true;
8795     default:
8796       break;
8797     }
8798 
8799     LLVM_FALLTHROUGH;
8800   }
8801   default:
8802     return denormalsEnabledForType(DAG, Op.getValueType()) &&
8803            DAG.isKnownNeverSNaN(Op);
8804   }
8805 
8806   llvm_unreachable("invalid operation");
8807 }
8808 
8809 // Constant fold canonicalize.
8810 SDValue SITargetLowering::getCanonicalConstantFP(
8811   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8812   // Flush denormals to 0 if not enabled.
8813   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
8814     return DAG.getConstantFP(0.0, SL, VT);
8815 
8816   if (C.isNaN()) {
8817     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8818     if (C.isSignaling()) {
8819       // Quiet a signaling NaN.
8820       // FIXME: Is this supposed to preserve payload bits?
8821       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8822     }
8823 
8824     // Make sure it is the canonical NaN bitpattern.
8825     //
8826     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8827     // immediate?
8828     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8829       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8830   }
8831 
8832   // Already canonical.
8833   return DAG.getConstantFP(C, SL, VT);
8834 }
8835 
8836 static bool vectorEltWillFoldAway(SDValue Op) {
8837   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8838 }
8839 
8840 SDValue SITargetLowering::performFCanonicalizeCombine(
8841   SDNode *N,
8842   DAGCombinerInfo &DCI) const {
8843   SelectionDAG &DAG = DCI.DAG;
8844   SDValue N0 = N->getOperand(0);
8845   EVT VT = N->getValueType(0);
8846 
8847   // fcanonicalize undef -> qnan
8848   if (N0.isUndef()) {
8849     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8850     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8851   }
8852 
8853   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8854     EVT VT = N->getValueType(0);
8855     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8856   }
8857 
8858   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8859   //                                                   (fcanonicalize k)
8860   //
8861   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8862 
8863   // TODO: This could be better with wider vectors that will be split to v2f16,
8864   // and to consider uses since there aren't that many packed operations.
8865   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8866       isTypeLegal(MVT::v2f16)) {
8867     SDLoc SL(N);
8868     SDValue NewElts[2];
8869     SDValue Lo = N0.getOperand(0);
8870     SDValue Hi = N0.getOperand(1);
8871     EVT EltVT = Lo.getValueType();
8872 
8873     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8874       for (unsigned I = 0; I != 2; ++I) {
8875         SDValue Op = N0.getOperand(I);
8876         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8877           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8878                                               CFP->getValueAPF());
8879         } else if (Op.isUndef()) {
8880           // Handled below based on what the other operand is.
8881           NewElts[I] = Op;
8882         } else {
8883           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8884         }
8885       }
8886 
8887       // If one half is undef, and one is constant, perfer a splat vector rather
8888       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8889       // cheaper to use and may be free with a packed operation.
8890       if (NewElts[0].isUndef()) {
8891         if (isa<ConstantFPSDNode>(NewElts[1]))
8892           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8893             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8894       }
8895 
8896       if (NewElts[1].isUndef()) {
8897         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8898           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8899       }
8900 
8901       return DAG.getBuildVector(VT, SL, NewElts);
8902     }
8903   }
8904 
8905   unsigned SrcOpc = N0.getOpcode();
8906 
8907   // If it's free to do so, push canonicalizes further up the source, which may
8908   // find a canonical source.
8909   //
8910   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8911   // sNaNs.
8912   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8913     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8914     if (CRHS && N0.hasOneUse()) {
8915       SDLoc SL(N);
8916       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8917                                    N0.getOperand(0));
8918       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8919       DCI.AddToWorklist(Canon0.getNode());
8920 
8921       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8922     }
8923   }
8924 
8925   return isCanonicalized(DAG, N0) ? N0 : SDValue();
8926 }
8927 
8928 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
8929   switch (Opc) {
8930   case ISD::FMAXNUM:
8931   case ISD::FMAXNUM_IEEE:
8932     return AMDGPUISD::FMAX3;
8933   case ISD::SMAX:
8934     return AMDGPUISD::SMAX3;
8935   case ISD::UMAX:
8936     return AMDGPUISD::UMAX3;
8937   case ISD::FMINNUM:
8938   case ISD::FMINNUM_IEEE:
8939     return AMDGPUISD::FMIN3;
8940   case ISD::SMIN:
8941     return AMDGPUISD::SMIN3;
8942   case ISD::UMIN:
8943     return AMDGPUISD::UMIN3;
8944   default:
8945     llvm_unreachable("Not a min/max opcode");
8946   }
8947 }
8948 
8949 SDValue SITargetLowering::performIntMed3ImmCombine(
8950   SelectionDAG &DAG, const SDLoc &SL,
8951   SDValue Op0, SDValue Op1, bool Signed) const {
8952   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8953   if (!K1)
8954     return SDValue();
8955 
8956   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8957   if (!K0)
8958     return SDValue();
8959 
8960   if (Signed) {
8961     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8962       return SDValue();
8963   } else {
8964     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8965       return SDValue();
8966   }
8967 
8968   EVT VT = K0->getValueType(0);
8969   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8970   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8971     return DAG.getNode(Med3Opc, SL, VT,
8972                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8973   }
8974 
8975   // If there isn't a 16-bit med3 operation, convert to 32-bit.
8976   MVT NVT = MVT::i32;
8977   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8978 
8979   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8980   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8981   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
8982 
8983   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8984   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
8985 }
8986 
8987 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8988   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8989     return C;
8990 
8991   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8992     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
8993       return C;
8994   }
8995 
8996   return nullptr;
8997 }
8998 
8999 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9000                                                   const SDLoc &SL,
9001                                                   SDValue Op0,
9002                                                   SDValue Op1) const {
9003   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9004   if (!K1)
9005     return SDValue();
9006 
9007   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9008   if (!K0)
9009     return SDValue();
9010 
9011   // Ordered >= (although NaN inputs should have folded away by now).
9012   if (K0->getValueAPF() > K1->getValueAPF())
9013     return SDValue();
9014 
9015   const MachineFunction &MF = DAG.getMachineFunction();
9016   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9017 
9018   // TODO: Check IEEE bit enabled?
9019   EVT VT = Op0.getValueType();
9020   if (Info->getMode().DX10Clamp) {
9021     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9022     // hardware fmed3 behavior converting to a min.
9023     // FIXME: Should this be allowing -0.0?
9024     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9025       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9026   }
9027 
9028   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9029   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9030     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9031     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9032     // then give the other result, which is different from med3 with a NaN
9033     // input.
9034     SDValue Var = Op0.getOperand(0);
9035     if (!DAG.isKnownNeverSNaN(Var))
9036       return SDValue();
9037 
9038     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9039 
9040     if ((!K0->hasOneUse() ||
9041          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9042         (!K1->hasOneUse() ||
9043          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9044       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9045                          Var, SDValue(K0, 0), SDValue(K1, 0));
9046     }
9047   }
9048 
9049   return SDValue();
9050 }
9051 
9052 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9053                                                DAGCombinerInfo &DCI) const {
9054   SelectionDAG &DAG = DCI.DAG;
9055 
9056   EVT VT = N->getValueType(0);
9057   unsigned Opc = N->getOpcode();
9058   SDValue Op0 = N->getOperand(0);
9059   SDValue Op1 = N->getOperand(1);
9060 
9061   // Only do this if the inner op has one use since this will just increases
9062   // register pressure for no benefit.
9063 
9064   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9065       !VT.isVector() &&
9066       (VT == MVT::i32 || VT == MVT::f32 ||
9067        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9068     // max(max(a, b), c) -> max3(a, b, c)
9069     // min(min(a, b), c) -> min3(a, b, c)
9070     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9071       SDLoc DL(N);
9072       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9073                          DL,
9074                          N->getValueType(0),
9075                          Op0.getOperand(0),
9076                          Op0.getOperand(1),
9077                          Op1);
9078     }
9079 
9080     // Try commuted.
9081     // max(a, max(b, c)) -> max3(a, b, c)
9082     // min(a, min(b, c)) -> min3(a, b, c)
9083     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9084       SDLoc DL(N);
9085       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9086                          DL,
9087                          N->getValueType(0),
9088                          Op0,
9089                          Op1.getOperand(0),
9090                          Op1.getOperand(1));
9091     }
9092   }
9093 
9094   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9095   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9096     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9097       return Med3;
9098   }
9099 
9100   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9101     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9102       return Med3;
9103   }
9104 
9105   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9106   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9107        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9108        (Opc == AMDGPUISD::FMIN_LEGACY &&
9109         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9110       (VT == MVT::f32 || VT == MVT::f64 ||
9111        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9112        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9113       Op0.hasOneUse()) {
9114     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9115       return Res;
9116   }
9117 
9118   return SDValue();
9119 }
9120 
9121 static bool isClampZeroToOne(SDValue A, SDValue B) {
9122   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9123     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9124       // FIXME: Should this be allowing -0.0?
9125       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9126              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9127     }
9128   }
9129 
9130   return false;
9131 }
9132 
9133 // FIXME: Should only worry about snans for version with chain.
9134 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9135                                               DAGCombinerInfo &DCI) const {
9136   EVT VT = N->getValueType(0);
9137   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9138   // NaNs. With a NaN input, the order of the operands may change the result.
9139 
9140   SelectionDAG &DAG = DCI.DAG;
9141   SDLoc SL(N);
9142 
9143   SDValue Src0 = N->getOperand(0);
9144   SDValue Src1 = N->getOperand(1);
9145   SDValue Src2 = N->getOperand(2);
9146 
9147   if (isClampZeroToOne(Src0, Src1)) {
9148     // const_a, const_b, x -> clamp is safe in all cases including signaling
9149     // nans.
9150     // FIXME: Should this be allowing -0.0?
9151     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9152   }
9153 
9154   const MachineFunction &MF = DAG.getMachineFunction();
9155   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9156 
9157   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9158   // handling no dx10-clamp?
9159   if (Info->getMode().DX10Clamp) {
9160     // If NaNs is clamped to 0, we are free to reorder the inputs.
9161 
9162     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9163       std::swap(Src0, Src1);
9164 
9165     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9166       std::swap(Src1, Src2);
9167 
9168     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9169       std::swap(Src0, Src1);
9170 
9171     if (isClampZeroToOne(Src1, Src2))
9172       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9173   }
9174 
9175   return SDValue();
9176 }
9177 
9178 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9179                                                  DAGCombinerInfo &DCI) const {
9180   SDValue Src0 = N->getOperand(0);
9181   SDValue Src1 = N->getOperand(1);
9182   if (Src0.isUndef() && Src1.isUndef())
9183     return DCI.DAG.getUNDEF(N->getValueType(0));
9184   return SDValue();
9185 }
9186 
9187 SDValue SITargetLowering::performExtractVectorEltCombine(
9188   SDNode *N, DAGCombinerInfo &DCI) const {
9189   SDValue Vec = N->getOperand(0);
9190   SelectionDAG &DAG = DCI.DAG;
9191 
9192   EVT VecVT = Vec.getValueType();
9193   EVT EltVT = VecVT.getVectorElementType();
9194 
9195   if ((Vec.getOpcode() == ISD::FNEG ||
9196        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9197     SDLoc SL(N);
9198     EVT EltVT = N->getValueType(0);
9199     SDValue Idx = N->getOperand(1);
9200     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9201                               Vec.getOperand(0), Idx);
9202     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9203   }
9204 
9205   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9206   //    =>
9207   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9208   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9209   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9210   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9211     SDLoc SL(N);
9212     EVT EltVT = N->getValueType(0);
9213     SDValue Idx = N->getOperand(1);
9214     unsigned Opc = Vec.getOpcode();
9215 
9216     switch(Opc) {
9217     default:
9218       break;
9219       // TODO: Support other binary operations.
9220     case ISD::FADD:
9221     case ISD::FSUB:
9222     case ISD::FMUL:
9223     case ISD::ADD:
9224     case ISD::UMIN:
9225     case ISD::UMAX:
9226     case ISD::SMIN:
9227     case ISD::SMAX:
9228     case ISD::FMAXNUM:
9229     case ISD::FMINNUM:
9230     case ISD::FMAXNUM_IEEE:
9231     case ISD::FMINNUM_IEEE: {
9232       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9233                                  Vec.getOperand(0), Idx);
9234       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9235                                  Vec.getOperand(1), Idx);
9236 
9237       DCI.AddToWorklist(Elt0.getNode());
9238       DCI.AddToWorklist(Elt1.getNode());
9239       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9240     }
9241     }
9242   }
9243 
9244   unsigned VecSize = VecVT.getSizeInBits();
9245   unsigned EltSize = EltVT.getSizeInBits();
9246 
9247   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9248   // This elminates non-constant index and subsequent movrel or scratch access.
9249   // Sub-dword vectors of size 2 dword or less have better implementation.
9250   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9251   // instructions.
9252   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9253       !isa<ConstantSDNode>(N->getOperand(1))) {
9254     SDLoc SL(N);
9255     SDValue Idx = N->getOperand(1);
9256     SDValue V;
9257     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9258       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9259       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9260       if (I == 0)
9261         V = Elt;
9262       else
9263         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9264     }
9265     return V;
9266   }
9267 
9268   if (!DCI.isBeforeLegalize())
9269     return SDValue();
9270 
9271   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9272   // elements. This exposes more load reduction opportunities by replacing
9273   // multiple small extract_vector_elements with a single 32-bit extract.
9274   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9275   if (isa<MemSDNode>(Vec) &&
9276       EltSize <= 16 &&
9277       EltVT.isByteSized() &&
9278       VecSize > 32 &&
9279       VecSize % 32 == 0 &&
9280       Idx) {
9281     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9282 
9283     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9284     unsigned EltIdx = BitIndex / 32;
9285     unsigned LeftoverBitIdx = BitIndex % 32;
9286     SDLoc SL(N);
9287 
9288     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9289     DCI.AddToWorklist(Cast.getNode());
9290 
9291     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9292                               DAG.getConstant(EltIdx, SL, MVT::i32));
9293     DCI.AddToWorklist(Elt.getNode());
9294     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9295                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9296     DCI.AddToWorklist(Srl.getNode());
9297 
9298     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9299     DCI.AddToWorklist(Trunc.getNode());
9300     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9301   }
9302 
9303   return SDValue();
9304 }
9305 
9306 SDValue
9307 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9308                                                 DAGCombinerInfo &DCI) const {
9309   SDValue Vec = N->getOperand(0);
9310   SDValue Idx = N->getOperand(2);
9311   EVT VecVT = Vec.getValueType();
9312   EVT EltVT = VecVT.getVectorElementType();
9313   unsigned VecSize = VecVT.getSizeInBits();
9314   unsigned EltSize = EltVT.getSizeInBits();
9315 
9316   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9317   // => BUILD_VECTOR n x select (e, const-idx)
9318   // This elminates non-constant index and subsequent movrel or scratch access.
9319   // Sub-dword vectors of size 2 dword or less have better implementation.
9320   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9321   // instructions.
9322   if (isa<ConstantSDNode>(Idx) ||
9323       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9324     return SDValue();
9325 
9326   SelectionDAG &DAG = DCI.DAG;
9327   SDLoc SL(N);
9328   SDValue Ins = N->getOperand(1);
9329   EVT IdxVT = Idx.getValueType();
9330 
9331   SmallVector<SDValue, 16> Ops;
9332   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9333     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9334     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9335     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9336     Ops.push_back(V);
9337   }
9338 
9339   return DAG.getBuildVector(VecVT, SL, Ops);
9340 }
9341 
9342 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9343                                           const SDNode *N0,
9344                                           const SDNode *N1) const {
9345   EVT VT = N0->getValueType(0);
9346 
9347   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9348   // support denormals ever.
9349   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9350        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9351         getSubtarget()->hasMadF16())) &&
9352        isOperationLegal(ISD::FMAD, VT))
9353     return ISD::FMAD;
9354 
9355   const TargetOptions &Options = DAG.getTarget().Options;
9356   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9357        (N0->getFlags().hasAllowContract() &&
9358         N1->getFlags().hasAllowContract())) &&
9359       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9360     return ISD::FMA;
9361   }
9362 
9363   return 0;
9364 }
9365 
9366 // For a reassociatable opcode perform:
9367 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9368 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9369                                                SelectionDAG &DAG) const {
9370   EVT VT = N->getValueType(0);
9371   if (VT != MVT::i32 && VT != MVT::i64)
9372     return SDValue();
9373 
9374   unsigned Opc = N->getOpcode();
9375   SDValue Op0 = N->getOperand(0);
9376   SDValue Op1 = N->getOperand(1);
9377 
9378   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9379     return SDValue();
9380 
9381   if (Op0->isDivergent())
9382     std::swap(Op0, Op1);
9383 
9384   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9385     return SDValue();
9386 
9387   SDValue Op2 = Op1.getOperand(1);
9388   Op1 = Op1.getOperand(0);
9389   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9390     return SDValue();
9391 
9392   if (Op1->isDivergent())
9393     std::swap(Op1, Op2);
9394 
9395   // If either operand is constant this will conflict with
9396   // DAGCombiner::ReassociateOps().
9397   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9398       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9399     return SDValue();
9400 
9401   SDLoc SL(N);
9402   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9403   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9404 }
9405 
9406 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9407                            EVT VT,
9408                            SDValue N0, SDValue N1, SDValue N2,
9409                            bool Signed) {
9410   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9411   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9412   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9413   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9414 }
9415 
9416 SDValue SITargetLowering::performAddCombine(SDNode *N,
9417                                             DAGCombinerInfo &DCI) const {
9418   SelectionDAG &DAG = DCI.DAG;
9419   EVT VT = N->getValueType(0);
9420   SDLoc SL(N);
9421   SDValue LHS = N->getOperand(0);
9422   SDValue RHS = N->getOperand(1);
9423 
9424   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9425       && Subtarget->hasMad64_32() &&
9426       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9427       VT.getScalarSizeInBits() <= 64) {
9428     if (LHS.getOpcode() != ISD::MUL)
9429       std::swap(LHS, RHS);
9430 
9431     SDValue MulLHS = LHS.getOperand(0);
9432     SDValue MulRHS = LHS.getOperand(1);
9433     SDValue AddRHS = RHS;
9434 
9435     // TODO: Maybe restrict if SGPR inputs.
9436     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9437         numBitsUnsigned(MulRHS, DAG) <= 32) {
9438       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9439       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9440       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9441       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9442     }
9443 
9444     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9445       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9446       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9447       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9448       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9449     }
9450 
9451     return SDValue();
9452   }
9453 
9454   if (SDValue V = reassociateScalarOps(N, DAG)) {
9455     return V;
9456   }
9457 
9458   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9459     return SDValue();
9460 
9461   // add x, zext (setcc) => addcarry x, 0, setcc
9462   // add x, sext (setcc) => subcarry x, 0, setcc
9463   unsigned Opc = LHS.getOpcode();
9464   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9465       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9466     std::swap(RHS, LHS);
9467 
9468   Opc = RHS.getOpcode();
9469   switch (Opc) {
9470   default: break;
9471   case ISD::ZERO_EXTEND:
9472   case ISD::SIGN_EXTEND:
9473   case ISD::ANY_EXTEND: {
9474     auto Cond = RHS.getOperand(0);
9475     // If this won't be a real VOPC output, we would still need to insert an
9476     // extra instruction anyway.
9477     if (!isBoolSGPR(Cond))
9478       break;
9479     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9480     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9481     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9482     return DAG.getNode(Opc, SL, VTList, Args);
9483   }
9484   case ISD::ADDCARRY: {
9485     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9486     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9487     if (!C || C->getZExtValue() != 0) break;
9488     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9489     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9490   }
9491   }
9492   return SDValue();
9493 }
9494 
9495 SDValue SITargetLowering::performSubCombine(SDNode *N,
9496                                             DAGCombinerInfo &DCI) const {
9497   SelectionDAG &DAG = DCI.DAG;
9498   EVT VT = N->getValueType(0);
9499 
9500   if (VT != MVT::i32)
9501     return SDValue();
9502 
9503   SDLoc SL(N);
9504   SDValue LHS = N->getOperand(0);
9505   SDValue RHS = N->getOperand(1);
9506 
9507   // sub x, zext (setcc) => subcarry x, 0, setcc
9508   // sub x, sext (setcc) => addcarry x, 0, setcc
9509   unsigned Opc = RHS.getOpcode();
9510   switch (Opc) {
9511   default: break;
9512   case ISD::ZERO_EXTEND:
9513   case ISD::SIGN_EXTEND:
9514   case ISD::ANY_EXTEND: {
9515     auto Cond = RHS.getOperand(0);
9516     // If this won't be a real VOPC output, we would still need to insert an
9517     // extra instruction anyway.
9518     if (!isBoolSGPR(Cond))
9519       break;
9520     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9521     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9522     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9523     return DAG.getNode(Opc, SL, VTList, Args);
9524   }
9525   }
9526 
9527   if (LHS.getOpcode() == ISD::SUBCARRY) {
9528     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9529     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9530     if (!C || !C->isNullValue())
9531       return SDValue();
9532     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9533     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9534   }
9535   return SDValue();
9536 }
9537 
9538 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9539   DAGCombinerInfo &DCI) const {
9540 
9541   if (N->getValueType(0) != MVT::i32)
9542     return SDValue();
9543 
9544   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9545   if (!C || C->getZExtValue() != 0)
9546     return SDValue();
9547 
9548   SelectionDAG &DAG = DCI.DAG;
9549   SDValue LHS = N->getOperand(0);
9550 
9551   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9552   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9553   unsigned LHSOpc = LHS.getOpcode();
9554   unsigned Opc = N->getOpcode();
9555   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9556       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9557     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9558     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9559   }
9560   return SDValue();
9561 }
9562 
9563 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9564                                              DAGCombinerInfo &DCI) const {
9565   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9566     return SDValue();
9567 
9568   SelectionDAG &DAG = DCI.DAG;
9569   EVT VT = N->getValueType(0);
9570 
9571   SDLoc SL(N);
9572   SDValue LHS = N->getOperand(0);
9573   SDValue RHS = N->getOperand(1);
9574 
9575   // These should really be instruction patterns, but writing patterns with
9576   // source modiifiers is a pain.
9577 
9578   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9579   if (LHS.getOpcode() == ISD::FADD) {
9580     SDValue A = LHS.getOperand(0);
9581     if (A == LHS.getOperand(1)) {
9582       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9583       if (FusedOp != 0) {
9584         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9585         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9586       }
9587     }
9588   }
9589 
9590   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9591   if (RHS.getOpcode() == ISD::FADD) {
9592     SDValue A = RHS.getOperand(0);
9593     if (A == RHS.getOperand(1)) {
9594       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9595       if (FusedOp != 0) {
9596         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9597         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9598       }
9599     }
9600   }
9601 
9602   return SDValue();
9603 }
9604 
9605 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9606                                              DAGCombinerInfo &DCI) const {
9607   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9608     return SDValue();
9609 
9610   SelectionDAG &DAG = DCI.DAG;
9611   SDLoc SL(N);
9612   EVT VT = N->getValueType(0);
9613   assert(!VT.isVector());
9614 
9615   // Try to get the fneg to fold into the source modifier. This undoes generic
9616   // DAG combines and folds them into the mad.
9617   //
9618   // Only do this if we are not trying to support denormals. v_mad_f32 does
9619   // not support denormals ever.
9620   SDValue LHS = N->getOperand(0);
9621   SDValue RHS = N->getOperand(1);
9622   if (LHS.getOpcode() == ISD::FADD) {
9623     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9624     SDValue A = LHS.getOperand(0);
9625     if (A == LHS.getOperand(1)) {
9626       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9627       if (FusedOp != 0){
9628         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9629         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9630 
9631         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9632       }
9633     }
9634   }
9635 
9636   if (RHS.getOpcode() == ISD::FADD) {
9637     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9638 
9639     SDValue A = RHS.getOperand(0);
9640     if (A == RHS.getOperand(1)) {
9641       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9642       if (FusedOp != 0){
9643         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9644         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9645       }
9646     }
9647   }
9648 
9649   return SDValue();
9650 }
9651 
9652 SDValue SITargetLowering::performFMACombine(SDNode *N,
9653                                             DAGCombinerInfo &DCI) const {
9654   SelectionDAG &DAG = DCI.DAG;
9655   EVT VT = N->getValueType(0);
9656   SDLoc SL(N);
9657 
9658   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9659     return SDValue();
9660 
9661   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9662   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9663   SDValue Op1 = N->getOperand(0);
9664   SDValue Op2 = N->getOperand(1);
9665   SDValue FMA = N->getOperand(2);
9666 
9667   if (FMA.getOpcode() != ISD::FMA ||
9668       Op1.getOpcode() != ISD::FP_EXTEND ||
9669       Op2.getOpcode() != ISD::FP_EXTEND)
9670     return SDValue();
9671 
9672   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9673   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9674   // is sufficient to allow generaing fdot2.
9675   const TargetOptions &Options = DAG.getTarget().Options;
9676   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9677       (N->getFlags().hasAllowContract() &&
9678        FMA->getFlags().hasAllowContract())) {
9679     Op1 = Op1.getOperand(0);
9680     Op2 = Op2.getOperand(0);
9681     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9682         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9683       return SDValue();
9684 
9685     SDValue Vec1 = Op1.getOperand(0);
9686     SDValue Idx1 = Op1.getOperand(1);
9687     SDValue Vec2 = Op2.getOperand(0);
9688 
9689     SDValue FMAOp1 = FMA.getOperand(0);
9690     SDValue FMAOp2 = FMA.getOperand(1);
9691     SDValue FMAAcc = FMA.getOperand(2);
9692 
9693     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9694         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9695       return SDValue();
9696 
9697     FMAOp1 = FMAOp1.getOperand(0);
9698     FMAOp2 = FMAOp2.getOperand(0);
9699     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9700         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9701       return SDValue();
9702 
9703     SDValue Vec3 = FMAOp1.getOperand(0);
9704     SDValue Vec4 = FMAOp2.getOperand(0);
9705     SDValue Idx2 = FMAOp1.getOperand(1);
9706 
9707     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9708         // Idx1 and Idx2 cannot be the same.
9709         Idx1 == Idx2)
9710       return SDValue();
9711 
9712     if (Vec1 == Vec2 || Vec3 == Vec4)
9713       return SDValue();
9714 
9715     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9716       return SDValue();
9717 
9718     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9719         (Vec1 == Vec4 && Vec2 == Vec3)) {
9720       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9721                          DAG.getTargetConstant(0, SL, MVT::i1));
9722     }
9723   }
9724   return SDValue();
9725 }
9726 
9727 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9728                                               DAGCombinerInfo &DCI) const {
9729   SelectionDAG &DAG = DCI.DAG;
9730   SDLoc SL(N);
9731 
9732   SDValue LHS = N->getOperand(0);
9733   SDValue RHS = N->getOperand(1);
9734   EVT VT = LHS.getValueType();
9735   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9736 
9737   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9738   if (!CRHS) {
9739     CRHS = dyn_cast<ConstantSDNode>(LHS);
9740     if (CRHS) {
9741       std::swap(LHS, RHS);
9742       CC = getSetCCSwappedOperands(CC);
9743     }
9744   }
9745 
9746   if (CRHS) {
9747     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9748         isBoolSGPR(LHS.getOperand(0))) {
9749       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9750       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9751       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9752       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9753       if ((CRHS->isAllOnesValue() &&
9754            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9755           (CRHS->isNullValue() &&
9756            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9757         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9758                            DAG.getConstant(-1, SL, MVT::i1));
9759       if ((CRHS->isAllOnesValue() &&
9760            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9761           (CRHS->isNullValue() &&
9762            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9763         return LHS.getOperand(0);
9764     }
9765 
9766     uint64_t CRHSVal = CRHS->getZExtValue();
9767     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9768         LHS.getOpcode() == ISD::SELECT &&
9769         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9770         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9771         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9772         isBoolSGPR(LHS.getOperand(0))) {
9773       // Given CT != FT:
9774       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9775       // setcc (select cc, CT, CF), CF, ne => cc
9776       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9777       // setcc (select cc, CT, CF), CT, eq => cc
9778       uint64_t CT = LHS.getConstantOperandVal(1);
9779       uint64_t CF = LHS.getConstantOperandVal(2);
9780 
9781       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9782           (CT == CRHSVal && CC == ISD::SETNE))
9783         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9784                            DAG.getConstant(-1, SL, MVT::i1));
9785       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9786           (CT == CRHSVal && CC == ISD::SETEQ))
9787         return LHS.getOperand(0);
9788     }
9789   }
9790 
9791   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9792                                            VT != MVT::f16))
9793     return SDValue();
9794 
9795   // Match isinf/isfinite pattern
9796   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9797   // (fcmp one (fabs x), inf) -> (fp_class x,
9798   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9799   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9800     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9801     if (!CRHS)
9802       return SDValue();
9803 
9804     const APFloat &APF = CRHS->getValueAPF();
9805     if (APF.isInfinity() && !APF.isNegative()) {
9806       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9807                                  SIInstrFlags::N_INFINITY;
9808       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9809                                     SIInstrFlags::P_ZERO |
9810                                     SIInstrFlags::N_NORMAL |
9811                                     SIInstrFlags::P_NORMAL |
9812                                     SIInstrFlags::N_SUBNORMAL |
9813                                     SIInstrFlags::P_SUBNORMAL;
9814       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9815       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9816                          DAG.getConstant(Mask, SL, MVT::i32));
9817     }
9818   }
9819 
9820   return SDValue();
9821 }
9822 
9823 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9824                                                      DAGCombinerInfo &DCI) const {
9825   SelectionDAG &DAG = DCI.DAG;
9826   SDLoc SL(N);
9827   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9828 
9829   SDValue Src = N->getOperand(0);
9830   SDValue Shift = N->getOperand(0);
9831   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
9832     Shift = Shift.getOperand(0);
9833 
9834   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
9835     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
9836     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
9837     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9838     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9839     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
9840     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
9841       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
9842                                  SDLoc(Shift.getOperand(0)), MVT::i32);
9843 
9844       unsigned ShiftOffset = 8 * Offset;
9845       if (Shift.getOpcode() == ISD::SHL)
9846         ShiftOffset -= C->getZExtValue();
9847       else
9848         ShiftOffset += C->getZExtValue();
9849 
9850       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
9851         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
9852                            MVT::f32, Shift);
9853       }
9854     }
9855   }
9856 
9857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9858   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9859   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
9860     // We simplified Src. If this node is not dead, visit it again so it is
9861     // folded properly.
9862     if (N->getOpcode() != ISD::DELETED_NODE)
9863       DCI.AddToWorklist(N);
9864     return SDValue(N, 0);
9865   }
9866 
9867   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
9868   if (SDValue DemandedSrc =
9869           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
9870     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
9871 
9872   return SDValue();
9873 }
9874 
9875 SDValue SITargetLowering::performClampCombine(SDNode *N,
9876                                               DAGCombinerInfo &DCI) const {
9877   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9878   if (!CSrc)
9879     return SDValue();
9880 
9881   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9882   const APFloat &F = CSrc->getValueAPF();
9883   APFloat Zero = APFloat::getZero(F.getSemantics());
9884   if (F < Zero ||
9885       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9886     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9887   }
9888 
9889   APFloat One(F.getSemantics(), "1.0");
9890   if (F > One)
9891     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9892 
9893   return SDValue(CSrc, 0);
9894 }
9895 
9896 
9897 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9898                                             DAGCombinerInfo &DCI) const {
9899   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9900     return SDValue();
9901   switch (N->getOpcode()) {
9902   default:
9903     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9904   case ISD::ADD:
9905     return performAddCombine(N, DCI);
9906   case ISD::SUB:
9907     return performSubCombine(N, DCI);
9908   case ISD::ADDCARRY:
9909   case ISD::SUBCARRY:
9910     return performAddCarrySubCarryCombine(N, DCI);
9911   case ISD::FADD:
9912     return performFAddCombine(N, DCI);
9913   case ISD::FSUB:
9914     return performFSubCombine(N, DCI);
9915   case ISD::SETCC:
9916     return performSetCCCombine(N, DCI);
9917   case ISD::FMAXNUM:
9918   case ISD::FMINNUM:
9919   case ISD::FMAXNUM_IEEE:
9920   case ISD::FMINNUM_IEEE:
9921   case ISD::SMAX:
9922   case ISD::SMIN:
9923   case ISD::UMAX:
9924   case ISD::UMIN:
9925   case AMDGPUISD::FMIN_LEGACY:
9926   case AMDGPUISD::FMAX_LEGACY:
9927     return performMinMaxCombine(N, DCI);
9928   case ISD::FMA:
9929     return performFMACombine(N, DCI);
9930   case ISD::LOAD: {
9931     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9932       return Widended;
9933     LLVM_FALLTHROUGH;
9934   }
9935   case ISD::STORE:
9936   case ISD::ATOMIC_LOAD:
9937   case ISD::ATOMIC_STORE:
9938   case ISD::ATOMIC_CMP_SWAP:
9939   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9940   case ISD::ATOMIC_SWAP:
9941   case ISD::ATOMIC_LOAD_ADD:
9942   case ISD::ATOMIC_LOAD_SUB:
9943   case ISD::ATOMIC_LOAD_AND:
9944   case ISD::ATOMIC_LOAD_OR:
9945   case ISD::ATOMIC_LOAD_XOR:
9946   case ISD::ATOMIC_LOAD_NAND:
9947   case ISD::ATOMIC_LOAD_MIN:
9948   case ISD::ATOMIC_LOAD_MAX:
9949   case ISD::ATOMIC_LOAD_UMIN:
9950   case ISD::ATOMIC_LOAD_UMAX:
9951   case ISD::ATOMIC_LOAD_FADD:
9952   case AMDGPUISD::ATOMIC_INC:
9953   case AMDGPUISD::ATOMIC_DEC:
9954   case AMDGPUISD::ATOMIC_LOAD_FMIN:
9955   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
9956     if (DCI.isBeforeLegalize())
9957       break;
9958     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
9959   case ISD::AND:
9960     return performAndCombine(N, DCI);
9961   case ISD::OR:
9962     return performOrCombine(N, DCI);
9963   case ISD::XOR:
9964     return performXorCombine(N, DCI);
9965   case ISD::ZERO_EXTEND:
9966     return performZeroExtendCombine(N, DCI);
9967   case ISD::SIGN_EXTEND_INREG:
9968     return performSignExtendInRegCombine(N , DCI);
9969   case AMDGPUISD::FP_CLASS:
9970     return performClassCombine(N, DCI);
9971   case ISD::FCANONICALIZE:
9972     return performFCanonicalizeCombine(N, DCI);
9973   case AMDGPUISD::RCP:
9974     return performRcpCombine(N, DCI);
9975   case AMDGPUISD::FRACT:
9976   case AMDGPUISD::RSQ:
9977   case AMDGPUISD::RCP_LEGACY:
9978   case AMDGPUISD::RSQ_LEGACY:
9979   case AMDGPUISD::RCP_IFLAG:
9980   case AMDGPUISD::RSQ_CLAMP:
9981   case AMDGPUISD::LDEXP: {
9982     SDValue Src = N->getOperand(0);
9983     if (Src.isUndef())
9984       return Src;
9985     break;
9986   }
9987   case ISD::SINT_TO_FP:
9988   case ISD::UINT_TO_FP:
9989     return performUCharToFloatCombine(N, DCI);
9990   case AMDGPUISD::CVT_F32_UBYTE0:
9991   case AMDGPUISD::CVT_F32_UBYTE1:
9992   case AMDGPUISD::CVT_F32_UBYTE2:
9993   case AMDGPUISD::CVT_F32_UBYTE3:
9994     return performCvtF32UByteNCombine(N, DCI);
9995   case AMDGPUISD::FMED3:
9996     return performFMed3Combine(N, DCI);
9997   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9998     return performCvtPkRTZCombine(N, DCI);
9999   case AMDGPUISD::CLAMP:
10000     return performClampCombine(N, DCI);
10001   case ISD::SCALAR_TO_VECTOR: {
10002     SelectionDAG &DAG = DCI.DAG;
10003     EVT VT = N->getValueType(0);
10004 
10005     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10006     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10007       SDLoc SL(N);
10008       SDValue Src = N->getOperand(0);
10009       EVT EltVT = Src.getValueType();
10010       if (EltVT == MVT::f16)
10011         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10012 
10013       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10014       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10015     }
10016 
10017     break;
10018   }
10019   case ISD::EXTRACT_VECTOR_ELT:
10020     return performExtractVectorEltCombine(N, DCI);
10021   case ISD::INSERT_VECTOR_ELT:
10022     return performInsertVectorEltCombine(N, DCI);
10023   }
10024   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10025 }
10026 
10027 /// Helper function for adjustWritemask
10028 static unsigned SubIdx2Lane(unsigned Idx) {
10029   switch (Idx) {
10030   default: return 0;
10031   case AMDGPU::sub0: return 0;
10032   case AMDGPU::sub1: return 1;
10033   case AMDGPU::sub2: return 2;
10034   case AMDGPU::sub3: return 3;
10035   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10036   }
10037 }
10038 
10039 /// Adjust the writemask of MIMG instructions
10040 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10041                                           SelectionDAG &DAG) const {
10042   unsigned Opcode = Node->getMachineOpcode();
10043 
10044   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10045   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10046   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10047     return Node; // not implemented for D16
10048 
10049   SDNode *Users[5] = { nullptr };
10050   unsigned Lane = 0;
10051   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10052   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10053   unsigned NewDmask = 0;
10054   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10055   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10056   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10057                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10058   unsigned TFCLane = 0;
10059   bool HasChain = Node->getNumValues() > 1;
10060 
10061   if (OldDmask == 0) {
10062     // These are folded out, but on the chance it happens don't assert.
10063     return Node;
10064   }
10065 
10066   unsigned OldBitsSet = countPopulation(OldDmask);
10067   // Work out which is the TFE/LWE lane if that is enabled.
10068   if (UsesTFC) {
10069     TFCLane = OldBitsSet;
10070   }
10071 
10072   // Try to figure out the used register components
10073   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10074        I != E; ++I) {
10075 
10076     // Don't look at users of the chain.
10077     if (I.getUse().getResNo() != 0)
10078       continue;
10079 
10080     // Abort if we can't understand the usage
10081     if (!I->isMachineOpcode() ||
10082         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10083       return Node;
10084 
10085     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10086     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10087     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10088     // set, etc.
10089     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10090 
10091     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10092     if (UsesTFC && Lane == TFCLane) {
10093       Users[Lane] = *I;
10094     } else {
10095       // Set which texture component corresponds to the lane.
10096       unsigned Comp;
10097       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10098         Comp = countTrailingZeros(Dmask);
10099         Dmask &= ~(1 << Comp);
10100       }
10101 
10102       // Abort if we have more than one user per component.
10103       if (Users[Lane])
10104         return Node;
10105 
10106       Users[Lane] = *I;
10107       NewDmask |= 1 << Comp;
10108     }
10109   }
10110 
10111   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10112   bool NoChannels = !NewDmask;
10113   if (NoChannels) {
10114     if (!UsesTFC) {
10115       // No uses of the result and not using TFC. Then do nothing.
10116       return Node;
10117     }
10118     // If the original dmask has one channel - then nothing to do
10119     if (OldBitsSet == 1)
10120       return Node;
10121     // Use an arbitrary dmask - required for the instruction to work
10122     NewDmask = 1;
10123   }
10124   // Abort if there's no change
10125   if (NewDmask == OldDmask)
10126     return Node;
10127 
10128   unsigned BitsSet = countPopulation(NewDmask);
10129 
10130   // Check for TFE or LWE - increase the number of channels by one to account
10131   // for the extra return value
10132   // This will need adjustment for D16 if this is also included in
10133   // adjustWriteMask (this function) but at present D16 are excluded.
10134   unsigned NewChannels = BitsSet + UsesTFC;
10135 
10136   int NewOpcode =
10137       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10138   assert(NewOpcode != -1 &&
10139          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10140          "failed to find equivalent MIMG op");
10141 
10142   // Adjust the writemask in the node
10143   SmallVector<SDValue, 12> Ops;
10144   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10145   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10146   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10147 
10148   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10149 
10150   MVT ResultVT = NewChannels == 1 ?
10151     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10152                            NewChannels == 5 ? 8 : NewChannels);
10153   SDVTList NewVTList = HasChain ?
10154     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10155 
10156 
10157   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10158                                               NewVTList, Ops);
10159 
10160   if (HasChain) {
10161     // Update chain.
10162     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10163     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10164   }
10165 
10166   if (NewChannels == 1) {
10167     assert(Node->hasNUsesOfValue(1, 0));
10168     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10169                                       SDLoc(Node), Users[Lane]->getValueType(0),
10170                                       SDValue(NewNode, 0));
10171     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10172     return nullptr;
10173   }
10174 
10175   // Update the users of the node with the new indices
10176   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10177     SDNode *User = Users[i];
10178     if (!User) {
10179       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10180       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10181       if (i || !NoChannels)
10182         continue;
10183     } else {
10184       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10185       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10186     }
10187 
10188     switch (Idx) {
10189     default: break;
10190     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10191     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10192     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10193     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10194     }
10195   }
10196 
10197   DAG.RemoveDeadNode(Node);
10198   return nullptr;
10199 }
10200 
10201 static bool isFrameIndexOp(SDValue Op) {
10202   if (Op.getOpcode() == ISD::AssertZext)
10203     Op = Op.getOperand(0);
10204 
10205   return isa<FrameIndexSDNode>(Op);
10206 }
10207 
10208 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10209 /// with frame index operands.
10210 /// LLVM assumes that inputs are to these instructions are registers.
10211 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10212                                                         SelectionDAG &DAG) const {
10213   if (Node->getOpcode() == ISD::CopyToReg) {
10214     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10215     SDValue SrcVal = Node->getOperand(2);
10216 
10217     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10218     // to try understanding copies to physical registers.
10219     if (SrcVal.getValueType() == MVT::i1 &&
10220         Register::isPhysicalRegister(DestReg->getReg())) {
10221       SDLoc SL(Node);
10222       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10223       SDValue VReg = DAG.getRegister(
10224         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10225 
10226       SDNode *Glued = Node->getGluedNode();
10227       SDValue ToVReg
10228         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10229                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10230       SDValue ToResultReg
10231         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10232                            VReg, ToVReg.getValue(1));
10233       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10234       DAG.RemoveDeadNode(Node);
10235       return ToResultReg.getNode();
10236     }
10237   }
10238 
10239   SmallVector<SDValue, 8> Ops;
10240   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10241     if (!isFrameIndexOp(Node->getOperand(i))) {
10242       Ops.push_back(Node->getOperand(i));
10243       continue;
10244     }
10245 
10246     SDLoc DL(Node);
10247     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10248                                      Node->getOperand(i).getValueType(),
10249                                      Node->getOperand(i)), 0));
10250   }
10251 
10252   return DAG.UpdateNodeOperands(Node, Ops);
10253 }
10254 
10255 /// Fold the instructions after selecting them.
10256 /// Returns null if users were already updated.
10257 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10258                                           SelectionDAG &DAG) const {
10259   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10260   unsigned Opcode = Node->getMachineOpcode();
10261 
10262   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10263       !TII->isGather4(Opcode)) {
10264     return adjustWritemask(Node, DAG);
10265   }
10266 
10267   if (Opcode == AMDGPU::INSERT_SUBREG ||
10268       Opcode == AMDGPU::REG_SEQUENCE) {
10269     legalizeTargetIndependentNode(Node, DAG);
10270     return Node;
10271   }
10272 
10273   switch (Opcode) {
10274   case AMDGPU::V_DIV_SCALE_F32:
10275   case AMDGPU::V_DIV_SCALE_F64: {
10276     // Satisfy the operand register constraint when one of the inputs is
10277     // undefined. Ordinarily each undef value will have its own implicit_def of
10278     // a vreg, so force these to use a single register.
10279     SDValue Src0 = Node->getOperand(0);
10280     SDValue Src1 = Node->getOperand(1);
10281     SDValue Src2 = Node->getOperand(2);
10282 
10283     if ((Src0.isMachineOpcode() &&
10284          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10285         (Src0 == Src1 || Src0 == Src2))
10286       break;
10287 
10288     MVT VT = Src0.getValueType().getSimpleVT();
10289     const TargetRegisterClass *RC =
10290         getRegClassFor(VT, Src0.getNode()->isDivergent());
10291 
10292     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10293     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10294 
10295     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10296                                       UndefReg, Src0, SDValue());
10297 
10298     // src0 must be the same register as src1 or src2, even if the value is
10299     // undefined, so make sure we don't violate this constraint.
10300     if (Src0.isMachineOpcode() &&
10301         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10302       if (Src1.isMachineOpcode() &&
10303           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10304         Src0 = Src1;
10305       else if (Src2.isMachineOpcode() &&
10306                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10307         Src0 = Src2;
10308       else {
10309         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10310         Src0 = UndefReg;
10311         Src1 = UndefReg;
10312       }
10313     } else
10314       break;
10315 
10316     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10317     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10318       Ops.push_back(Node->getOperand(I));
10319 
10320     Ops.push_back(ImpDef.getValue(1));
10321     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10322   }
10323   default:
10324     break;
10325   }
10326 
10327   return Node;
10328 }
10329 
10330 /// Assign the register class depending on the number of
10331 /// bits set in the writemask
10332 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10333                                                      SDNode *Node) const {
10334   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10335 
10336   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10337 
10338   if (TII->isVOP3(MI.getOpcode())) {
10339     // Make sure constant bus requirements are respected.
10340     TII->legalizeOperandsVOP3(MRI, MI);
10341 
10342     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10343     // This saves a chain-copy of registers and better ballance register
10344     // use between vgpr and agpr as agpr tuples tend to be big.
10345     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10346       unsigned Opc = MI.getOpcode();
10347       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10348       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10349                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10350         if (I == -1)
10351           break;
10352         MachineOperand &Op = MI.getOperand(I);
10353         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10354              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10355             !Register::isVirtualRegister(Op.getReg()) ||
10356             !TRI->isAGPR(MRI, Op.getReg()))
10357           continue;
10358         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10359         if (!Src || !Src->isCopy() ||
10360             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10361           continue;
10362         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10363         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10364         // All uses of agpr64 and agpr32 can also accept vgpr except for
10365         // v_accvgpr_read, but we do not produce agpr reads during selection,
10366         // so no use checks are needed.
10367         MRI.setRegClass(Op.getReg(), NewRC);
10368       }
10369     }
10370 
10371     return;
10372   }
10373 
10374   // Replace unused atomics with the no return version.
10375   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10376   if (NoRetAtomicOp != -1) {
10377     if (!Node->hasAnyUseOfValue(0)) {
10378       MI.setDesc(TII->get(NoRetAtomicOp));
10379       MI.RemoveOperand(0);
10380       return;
10381     }
10382 
10383     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10384     // instruction, because the return type of these instructions is a vec2 of
10385     // the memory type, so it can be tied to the input operand.
10386     // This means these instructions always have a use, so we need to add a
10387     // special case to check if the atomic has only one extract_subreg use,
10388     // which itself has no uses.
10389     if ((Node->hasNUsesOfValue(1, 0) &&
10390          Node->use_begin()->isMachineOpcode() &&
10391          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10392          !Node->use_begin()->hasAnyUseOfValue(0))) {
10393       Register Def = MI.getOperand(0).getReg();
10394 
10395       // Change this into a noret atomic.
10396       MI.setDesc(TII->get(NoRetAtomicOp));
10397       MI.RemoveOperand(0);
10398 
10399       // If we only remove the def operand from the atomic instruction, the
10400       // extract_subreg will be left with a use of a vreg without a def.
10401       // So we need to insert an implicit_def to avoid machine verifier
10402       // errors.
10403       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10404               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10405     }
10406     return;
10407   }
10408 }
10409 
10410 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10411                               uint64_t Val) {
10412   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10413   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10414 }
10415 
10416 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10417                                                 const SDLoc &DL,
10418                                                 SDValue Ptr) const {
10419   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10420 
10421   // Build the half of the subregister with the constants before building the
10422   // full 128-bit register. If we are building multiple resource descriptors,
10423   // this will allow CSEing of the 2-component register.
10424   const SDValue Ops0[] = {
10425     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10426     buildSMovImm32(DAG, DL, 0),
10427     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10428     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10429     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10430   };
10431 
10432   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10433                                                 MVT::v2i32, Ops0), 0);
10434 
10435   // Combine the constants and the pointer.
10436   const SDValue Ops1[] = {
10437     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10438     Ptr,
10439     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10440     SubRegHi,
10441     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10442   };
10443 
10444   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10445 }
10446 
10447 /// Return a resource descriptor with the 'Add TID' bit enabled
10448 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10449 ///        of the resource descriptor) to create an offset, which is added to
10450 ///        the resource pointer.
10451 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10452                                            SDValue Ptr, uint32_t RsrcDword1,
10453                                            uint64_t RsrcDword2And3) const {
10454   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10455   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10456   if (RsrcDword1) {
10457     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10458                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10459                     0);
10460   }
10461 
10462   SDValue DataLo = buildSMovImm32(DAG, DL,
10463                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10464   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10465 
10466   const SDValue Ops[] = {
10467     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10468     PtrLo,
10469     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10470     PtrHi,
10471     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10472     DataLo,
10473     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10474     DataHi,
10475     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10476   };
10477 
10478   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10479 }
10480 
10481 //===----------------------------------------------------------------------===//
10482 //                         SI Inline Assembly Support
10483 //===----------------------------------------------------------------------===//
10484 
10485 std::pair<unsigned, const TargetRegisterClass *>
10486 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10487                                                StringRef Constraint,
10488                                                MVT VT) const {
10489   const TargetRegisterClass *RC = nullptr;
10490   if (Constraint.size() == 1) {
10491     switch (Constraint[0]) {
10492     default:
10493       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10494     case 's':
10495     case 'r':
10496       switch (VT.getSizeInBits()) {
10497       default:
10498         return std::make_pair(0U, nullptr);
10499       case 32:
10500       case 16:
10501         RC = &AMDGPU::SReg_32RegClass;
10502         break;
10503       case 64:
10504         RC = &AMDGPU::SGPR_64RegClass;
10505         break;
10506       case 96:
10507         RC = &AMDGPU::SReg_96RegClass;
10508         break;
10509       case 128:
10510         RC = &AMDGPU::SGPR_128RegClass;
10511         break;
10512       case 160:
10513         RC = &AMDGPU::SReg_160RegClass;
10514         break;
10515       case 256:
10516         RC = &AMDGPU::SReg_256RegClass;
10517         break;
10518       case 512:
10519         RC = &AMDGPU::SReg_512RegClass;
10520         break;
10521       }
10522       break;
10523     case 'v':
10524       switch (VT.getSizeInBits()) {
10525       default:
10526         return std::make_pair(0U, nullptr);
10527       case 32:
10528       case 16:
10529         RC = &AMDGPU::VGPR_32RegClass;
10530         break;
10531       case 64:
10532         RC = &AMDGPU::VReg_64RegClass;
10533         break;
10534       case 96:
10535         RC = &AMDGPU::VReg_96RegClass;
10536         break;
10537       case 128:
10538         RC = &AMDGPU::VReg_128RegClass;
10539         break;
10540       case 160:
10541         RC = &AMDGPU::VReg_160RegClass;
10542         break;
10543       case 256:
10544         RC = &AMDGPU::VReg_256RegClass;
10545         break;
10546       case 512:
10547         RC = &AMDGPU::VReg_512RegClass;
10548         break;
10549       }
10550       break;
10551     case 'a':
10552       if (!Subtarget->hasMAIInsts())
10553         break;
10554       switch (VT.getSizeInBits()) {
10555       default:
10556         return std::make_pair(0U, nullptr);
10557       case 32:
10558       case 16:
10559         RC = &AMDGPU::AGPR_32RegClass;
10560         break;
10561       case 64:
10562         RC = &AMDGPU::AReg_64RegClass;
10563         break;
10564       case 128:
10565         RC = &AMDGPU::AReg_128RegClass;
10566         break;
10567       case 512:
10568         RC = &AMDGPU::AReg_512RegClass;
10569         break;
10570       case 1024:
10571         RC = &AMDGPU::AReg_1024RegClass;
10572         // v32 types are not legal but we support them here.
10573         return std::make_pair(0U, RC);
10574       }
10575       break;
10576     }
10577     // We actually support i128, i16 and f16 as inline parameters
10578     // even if they are not reported as legal
10579     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10580                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10581       return std::make_pair(0U, RC);
10582   }
10583 
10584   if (Constraint.size() > 1) {
10585     if (Constraint[1] == 'v') {
10586       RC = &AMDGPU::VGPR_32RegClass;
10587     } else if (Constraint[1] == 's') {
10588       RC = &AMDGPU::SGPR_32RegClass;
10589     } else if (Constraint[1] == 'a') {
10590       RC = &AMDGPU::AGPR_32RegClass;
10591     }
10592 
10593     if (RC) {
10594       uint32_t Idx;
10595       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10596       if (!Failed && Idx < RC->getNumRegs())
10597         return std::make_pair(RC->getRegister(Idx), RC);
10598     }
10599   }
10600 
10601   // FIXME: Returns VS_32 for physical SGPR constraints
10602   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10603 }
10604 
10605 SITargetLowering::ConstraintType
10606 SITargetLowering::getConstraintType(StringRef Constraint) const {
10607   if (Constraint.size() == 1) {
10608     switch (Constraint[0]) {
10609     default: break;
10610     case 's':
10611     case 'v':
10612     case 'a':
10613       return C_RegisterClass;
10614     }
10615   }
10616   return TargetLowering::getConstraintType(Constraint);
10617 }
10618 
10619 // Figure out which registers should be reserved for stack access. Only after
10620 // the function is legalized do we know all of the non-spill stack objects or if
10621 // calls are present.
10622 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10623   MachineRegisterInfo &MRI = MF.getRegInfo();
10624   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10625   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10626   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10627 
10628   if (Info->isEntryFunction()) {
10629     // Callable functions have fixed registers used for stack access.
10630     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10631   }
10632 
10633   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10634                              Info->getStackPtrOffsetReg()));
10635   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10636     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10637 
10638   // We need to worry about replacing the default register with itself in case
10639   // of MIR testcases missing the MFI.
10640   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10641     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10642 
10643   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10644     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10645 
10646   Info->limitOccupancy(MF);
10647 
10648   if (ST.isWave32() && !MF.empty()) {
10649     // Add VCC_HI def because many instructions marked as imp-use VCC where
10650     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10651     // having a use of undef.
10652 
10653     const SIInstrInfo *TII = ST.getInstrInfo();
10654     DebugLoc DL;
10655 
10656     MachineBasicBlock &MBB = MF.front();
10657     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10658     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10659 
10660     for (auto &MBB : MF) {
10661       for (auto &MI : MBB) {
10662         TII->fixImplicitOperands(MI);
10663       }
10664     }
10665   }
10666 
10667   TargetLoweringBase::finalizeLowering(MF);
10668 }
10669 
10670 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10671                                                      KnownBits &Known,
10672                                                      const APInt &DemandedElts,
10673                                                      const SelectionDAG &DAG,
10674                                                      unsigned Depth) const {
10675   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10676                                                 DAG, Depth);
10677 
10678   // Set the high bits to zero based on the maximum allowed scratch size per
10679   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10680   // calculation won't overflow, so assume the sign bit is never set.
10681   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10682 }
10683 
10684 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10685   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10686   const Align CacheLineAlign = Align(64);
10687 
10688   // Pre-GFX10 target did not benefit from loop alignment
10689   if (!ML || DisableLoopAlignment ||
10690       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10691       getSubtarget()->hasInstFwdPrefetchBug())
10692     return PrefAlign;
10693 
10694   // On GFX10 I$ is 4 x 64 bytes cache lines.
10695   // By default prefetcher keeps one cache line behind and reads two ahead.
10696   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10697   // behind and one ahead.
10698   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10699   // If loop fits 64 bytes it always spans no more than two cache lines and
10700   // does not need an alignment.
10701   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10702   // Else if loop is less or equal 192 bytes we need two lines behind.
10703 
10704   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10705   const MachineBasicBlock *Header = ML->getHeader();
10706   if (Header->getAlignment() != PrefAlign)
10707     return Header->getAlignment(); // Already processed.
10708 
10709   unsigned LoopSize = 0;
10710   for (const MachineBasicBlock *MBB : ML->blocks()) {
10711     // If inner loop block is aligned assume in average half of the alignment
10712     // size to be added as nops.
10713     if (MBB != Header)
10714       LoopSize += MBB->getAlignment().value() / 2;
10715 
10716     for (const MachineInstr &MI : *MBB) {
10717       LoopSize += TII->getInstSizeInBytes(MI);
10718       if (LoopSize > 192)
10719         return PrefAlign;
10720     }
10721   }
10722 
10723   if (LoopSize <= 64)
10724     return PrefAlign;
10725 
10726   if (LoopSize <= 128)
10727     return CacheLineAlign;
10728 
10729   // If any of parent loops is surrounded by prefetch instructions do not
10730   // insert new for inner loop, which would reset parent's settings.
10731   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10732     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10733       auto I = Exit->getFirstNonDebugInstr();
10734       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10735         return CacheLineAlign;
10736     }
10737   }
10738 
10739   MachineBasicBlock *Pre = ML->getLoopPreheader();
10740   MachineBasicBlock *Exit = ML->getExitBlock();
10741 
10742   if (Pre && Exit) {
10743     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10744             TII->get(AMDGPU::S_INST_PREFETCH))
10745       .addImm(1); // prefetch 2 lines behind PC
10746 
10747     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10748             TII->get(AMDGPU::S_INST_PREFETCH))
10749       .addImm(2); // prefetch 1 line behind PC
10750   }
10751 
10752   return CacheLineAlign;
10753 }
10754 
10755 LLVM_ATTRIBUTE_UNUSED
10756 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10757   assert(N->getOpcode() == ISD::CopyFromReg);
10758   do {
10759     // Follow the chain until we find an INLINEASM node.
10760     N = N->getOperand(0).getNode();
10761     if (N->getOpcode() == ISD::INLINEASM ||
10762         N->getOpcode() == ISD::INLINEASM_BR)
10763       return true;
10764   } while (N->getOpcode() == ISD::CopyFromReg);
10765   return false;
10766 }
10767 
10768 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10769   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10770 {
10771   switch (N->getOpcode()) {
10772     case ISD::CopyFromReg:
10773     {
10774       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10775       const MachineFunction * MF = FLI->MF;
10776       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10777       const MachineRegisterInfo &MRI = MF->getRegInfo();
10778       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10779       unsigned Reg = R->getReg();
10780       if (Register::isPhysicalRegister(Reg))
10781         return !TRI.isSGPRReg(MRI, Reg);
10782 
10783       if (MRI.isLiveIn(Reg)) {
10784         // workitem.id.x workitem.id.y workitem.id.z
10785         // Any VGPR formal argument is also considered divergent
10786         if (!TRI.isSGPRReg(MRI, Reg))
10787           return true;
10788         // Formal arguments of non-entry functions
10789         // are conservatively considered divergent
10790         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10791           return true;
10792         return false;
10793       }
10794       const Value *V = FLI->getValueFromVirtualReg(Reg);
10795       if (V)
10796         return KDA->isDivergent(V);
10797       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10798       return !TRI.isSGPRReg(MRI, Reg);
10799     }
10800     break;
10801     case ISD::LOAD: {
10802       const LoadSDNode *L = cast<LoadSDNode>(N);
10803       unsigned AS = L->getAddressSpace();
10804       // A flat load may access private memory.
10805       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10806     } break;
10807     case ISD::CALLSEQ_END:
10808     return true;
10809     break;
10810     case ISD::INTRINSIC_WO_CHAIN:
10811     {
10812 
10813     }
10814       return AMDGPU::isIntrinsicSourceOfDivergence(
10815       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10816     case ISD::INTRINSIC_W_CHAIN:
10817       return AMDGPU::isIntrinsicSourceOfDivergence(
10818       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10819   }
10820   return false;
10821 }
10822 
10823 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
10824                                                EVT VT) const {
10825   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10826   case MVT::f32:
10827     return hasFP32Denormals(DAG.getMachineFunction());
10828   case MVT::f64:
10829   case MVT::f16:
10830     return hasFP64FP16Denormals(DAG.getMachineFunction());
10831   default:
10832     return false;
10833   }
10834 }
10835 
10836 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10837                                                     const SelectionDAG &DAG,
10838                                                     bool SNaN,
10839                                                     unsigned Depth) const {
10840   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10841     const MachineFunction &MF = DAG.getMachineFunction();
10842     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10843 
10844     if (Info->getMode().DX10Clamp)
10845       return true; // Clamped to 0.
10846     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10847   }
10848 
10849   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10850                                                             SNaN, Depth);
10851 }
10852 
10853 TargetLowering::AtomicExpansionKind
10854 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10855   switch (RMW->getOperation()) {
10856   case AtomicRMWInst::FAdd: {
10857     Type *Ty = RMW->getType();
10858 
10859     // We don't have a way to support 16-bit atomics now, so just leave them
10860     // as-is.
10861     if (Ty->isHalfTy())
10862       return AtomicExpansionKind::None;
10863 
10864     if (!Ty->isFloatTy())
10865       return AtomicExpansionKind::CmpXChg;
10866 
10867     // TODO: Do have these for flat. Older targets also had them for buffers.
10868     unsigned AS = RMW->getPointerAddressSpace();
10869 
10870     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
10871       return RMW->use_empty() ? AtomicExpansionKind::None :
10872                                 AtomicExpansionKind::CmpXChg;
10873     }
10874 
10875     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10876       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10877   }
10878   default:
10879     break;
10880   }
10881 
10882   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10883 }
10884 
10885 const TargetRegisterClass *
10886 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
10887   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
10888   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10889   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
10890     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
10891                                                : &AMDGPU::SReg_32RegClass;
10892   if (!TRI->isSGPRClass(RC) && !isDivergent)
10893     return TRI->getEquivalentSGPRClass(RC);
10894   else if (TRI->isSGPRClass(RC) && isDivergent)
10895     return TRI->getEquivalentVGPRClass(RC);
10896 
10897   return RC;
10898 }
10899 
10900 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
10901                       unsigned WaveSize) {
10902   // FIXME: We asssume we never cast the mask results of a control flow
10903   // intrinsic.
10904   // Early exit if the type won't be consistent as a compile time hack.
10905   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
10906   if (!IT || IT->getBitWidth() != WaveSize)
10907     return false;
10908 
10909   if (!isa<Instruction>(V))
10910     return false;
10911   if (!Visited.insert(V).second)
10912     return false;
10913   bool Result = false;
10914   for (auto U : V->users()) {
10915     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
10916       if (V == U->getOperand(1)) {
10917         switch (Intrinsic->getIntrinsicID()) {
10918         default:
10919           Result = false;
10920           break;
10921         case Intrinsic::amdgcn_if_break:
10922         case Intrinsic::amdgcn_if:
10923         case Intrinsic::amdgcn_else:
10924           Result = true;
10925           break;
10926         }
10927       }
10928       if (V == U->getOperand(0)) {
10929         switch (Intrinsic->getIntrinsicID()) {
10930         default:
10931           Result = false;
10932           break;
10933         case Intrinsic::amdgcn_end_cf:
10934         case Intrinsic::amdgcn_loop:
10935           Result = true;
10936           break;
10937         }
10938       }
10939     } else {
10940       Result = hasCFUser(U, Visited, WaveSize);
10941     }
10942     if (Result)
10943       break;
10944   }
10945   return Result;
10946 }
10947 
10948 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
10949                                                const Value *V) const {
10950   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
10951     switch (Intrinsic->getIntrinsicID()) {
10952     default:
10953       return false;
10954     case Intrinsic::amdgcn_if_break:
10955       return true;
10956     }
10957   }
10958   if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) {
10959     if (const IntrinsicInst *Intrinsic =
10960             dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) {
10961       switch (Intrinsic->getIntrinsicID()) {
10962       default:
10963         return false;
10964       case Intrinsic::amdgcn_if:
10965       case Intrinsic::amdgcn_else: {
10966         ArrayRef<unsigned> Indices = ExtValue->getIndices();
10967         if (Indices.size() == 1 && Indices[0] == 1) {
10968           return true;
10969         }
10970       }
10971       }
10972     }
10973   }
10974   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
10975     if (isa<InlineAsm>(CI->getCalledValue())) {
10976       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
10977       ImmutableCallSite CS(CI);
10978       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
10979           MF.getDataLayout(), Subtarget->getRegisterInfo(), CS);
10980       for (auto &TC : TargetConstraints) {
10981         if (TC.Type == InlineAsm::isOutput) {
10982           ComputeConstraintToUse(TC, SDValue());
10983           unsigned AssignedReg;
10984           const TargetRegisterClass *RC;
10985           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
10986               SIRI, TC.ConstraintCode, TC.ConstraintVT);
10987           if (RC) {
10988             MachineRegisterInfo &MRI = MF.getRegInfo();
10989             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
10990               return true;
10991             else if (SIRI->isSGPRClass(RC))
10992               return true;
10993           }
10994         }
10995       }
10996     }
10997   }
10998   SmallPtrSet<const Value *, 16> Visited;
10999   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11000 }
11001