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 "SIDefines.h"
24 #include "SIInstrInfo.h"
25 #include "SIMachineFunctionInfo.h"
26 #include "SIRegisterInfo.h"
27 #include "MCTargetDesc/AMDGPUMCTargetDesc.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/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/CallingConvLower.h"
40 #include "llvm/CodeGen/DAGCombine.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineModuleInfo.h"
49 #include "llvm/CodeGen/MachineOperand.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetCallingConv.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/IR/Constants.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/DebugLoc.h"
59 #include "llvm/IR/DerivedTypes.h"
60 #include "llvm/IR/DiagnosticInfo.h"
61 #include "llvm/IR/Function.h"
62 #include "llvm/IR/GlobalValue.h"
63 #include "llvm/IR/InstrTypes.h"
64 #include "llvm/IR/Instruction.h"
65 #include "llvm/IR/Instructions.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/Type.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/CodeGen.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/KnownBits.h"
74 #include "llvm/Support/MachineValueType.h"
75 #include "llvm/Support/MathExtras.h"
76 #include "llvm/Target/TargetOptions.h"
77 #include <cassert>
78 #include <cmath>
79 #include <cstdint>
80 #include <iterator>
81 #include <tuple>
82 #include <utility>
83 #include <vector>
84 
85 using namespace llvm;
86 
87 #define DEBUG_TYPE "si-lower"
88 
89 STATISTIC(NumTailCalls, "Number of tail calls");
90 
91 static cl::opt<bool> EnableVGPRIndexMode(
92   "amdgpu-vgpr-index-mode",
93   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
94   cl::init(false));
95 
96 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
97   "amdgpu-frame-index-zero-bits",
98   cl::desc("High bits of frame index assumed to be zero"),
99   cl::init(5),
100   cl::ReallyHidden);
101 
102 static cl::opt<bool> DisableLoopAlignment(
103   "amdgpu-disable-loop-alignment",
104   cl::desc("Do not align and prefetch loops"),
105   cl::init(false));
106 
107 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
108   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
109   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
110     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
111       return AMDGPU::SGPR0 + Reg;
112     }
113   }
114   llvm_unreachable("Cannot allocate sgpr");
115 }
116 
117 SITargetLowering::SITargetLowering(const TargetMachine &TM,
118                                    const GCNSubtarget &STI)
119     : AMDGPUTargetLowering(TM, STI),
120       Subtarget(&STI) {
121   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
122   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
123 
124   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
125   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
126 
127   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
128   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
129   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
130 
131   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
132   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
133 
134   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
135   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
136 
137   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
138   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
139 
140   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
141   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
142 
143   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
144   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
145 
146   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
147   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
148 
149   if (Subtarget->has16BitInsts()) {
150     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
151     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
152 
153     // Unless there are also VOP3P operations, not operations are really legal.
154     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
155     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
156     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
157     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
158   }
159 
160   computeRegisterProperties(Subtarget->getRegisterInfo());
161 
162   // We need to custom lower vector stores from local memory
163   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
164   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
165   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
166   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
167   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
168   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
169   setOperationAction(ISD::LOAD, MVT::i1, Custom);
170   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
171 
172   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
174   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
175   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
176   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
177   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
178   setOperationAction(ISD::STORE, MVT::i1, Custom);
179   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
180 
181   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
182   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
183   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
184   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
185   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
186   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
187   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
188   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
189   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
190   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
191 
192   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
193   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
194 
195   setOperationAction(ISD::SELECT, MVT::i1, Promote);
196   setOperationAction(ISD::SELECT, MVT::i64, Custom);
197   setOperationAction(ISD::SELECT, MVT::f64, Promote);
198   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
199 
200   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
201   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
202   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
203   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
204   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
205 
206   setOperationAction(ISD::SETCC, MVT::i1, Promote);
207   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
208   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
209   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
210 
211   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
212   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
213 
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
218   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
219   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
220   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
221 
222   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
223   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
224   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
225   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
226   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
227   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
228   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
229 
230   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
231   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
232   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
233   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
234   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
235   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
236 
237   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
238   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
239   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
240   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
241   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
242   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
243 
244   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
245   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
246   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
247   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
248   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
249   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
250 
251   setOperationAction(ISD::UADDO, MVT::i32, Legal);
252   setOperationAction(ISD::USUBO, MVT::i32, Legal);
253 
254   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
255   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
256 
257   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
258   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
259   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
260 
261 #if 0
262   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
263   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
264 #endif
265 
266   // We only support LOAD/STORE and vector manipulation ops for vectors
267   // with > 4 elements.
268   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
269         MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, MVT::v32i32 }) {
270     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
271       switch (Op) {
272       case ISD::LOAD:
273       case ISD::STORE:
274       case ISD::BUILD_VECTOR:
275       case ISD::BITCAST:
276       case ISD::EXTRACT_VECTOR_ELT:
277       case ISD::INSERT_VECTOR_ELT:
278       case ISD::INSERT_SUBVECTOR:
279       case ISD::EXTRACT_SUBVECTOR:
280       case ISD::SCALAR_TO_VECTOR:
281         break;
282       case ISD::CONCAT_VECTORS:
283         setOperationAction(Op, VT, Custom);
284         break;
285       default:
286         setOperationAction(Op, VT, Expand);
287         break;
288       }
289     }
290   }
291 
292   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
293 
294   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
295   // is expanded to avoid having two separate loops in case the index is a VGPR.
296 
297   // Most operations are naturally 32-bit vector operations. We only support
298   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
299   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
300     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
301     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
302 
303     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
304     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
305 
306     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
307     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
308 
309     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
310     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
311   }
312 
313   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
314   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
315   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
316   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
317 
318   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
319   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
320 
321   // Avoid stack access for these.
322   // TODO: Generalize to more vector types.
323   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
324   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
325   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
326   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
327 
328   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
329   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
330   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
331   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
332   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
333 
334   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
335   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
336   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
337 
338   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
339   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
340   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
341   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
342 
343   // Deal with vec3 vector operations when widened to vec4.
344   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Expand);
345   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Expand);
346   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Expand);
347   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Expand);
348 
349   // Deal with vec5 vector operations when widened to vec8.
350   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Expand);
351   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Expand);
352   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Expand);
353   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Expand);
354 
355   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
356   // and output demarshalling
357   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
358   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
359 
360   // We can't return success/failure, only the old value,
361   // let LLVM add the comparison
362   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
363   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
364 
365   if (Subtarget->hasFlatAddressSpace()) {
366     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
367     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
368   }
369 
370   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
371   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
372 
373   // On SI this is s_memtime and s_memrealtime on VI.
374   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
375   setOperationAction(ISD::TRAP, MVT::Other, Custom);
376   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
377 
378   if (Subtarget->has16BitInsts()) {
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 according to some sources.
385   if (!Subtarget->hasFP32Denormals())
386     setOperationAction(ISD::FMAD, MVT::f32, Legal);
387 
388   if (!Subtarget->hasBFI()) {
389     // fcopysign can be done in a single instruction with BFI.
390     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
391     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
392   }
393 
394   if (!Subtarget->hasBCNT(32))
395     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
396 
397   if (!Subtarget->hasBCNT(64))
398     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
399 
400   if (Subtarget->hasFFBH())
401     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
402 
403   if (Subtarget->hasFFBL())
404     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
405 
406   // We only really have 32-bit BFE instructions (and 16-bit on VI).
407   //
408   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
409   // effort to match them now. We want this to be false for i64 cases when the
410   // extraction isn't restricted to the upper or lower half. Ideally we would
411   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
412   // span the midpoint are probably relatively rare, so don't worry about them
413   // for now.
414   if (Subtarget->hasBFE())
415     setHasExtractBitsInsn(true);
416 
417   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
418   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
419   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
420   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
421 
422 
423   // These are really only legal for ieee_mode functions. We should be avoiding
424   // them for functions that don't have ieee_mode enabled, so just say they are
425   // legal.
426   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
427   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
428   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
429   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
430 
431 
432   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
433     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
434     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
435     setOperationAction(ISD::FRINT, MVT::f64, Legal);
436   } else {
437     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
438     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
439     setOperationAction(ISD::FRINT, MVT::f64, Custom);
440     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
441   }
442 
443   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
444 
445   setOperationAction(ISD::FSIN, MVT::f32, Custom);
446   setOperationAction(ISD::FCOS, MVT::f32, Custom);
447   setOperationAction(ISD::FDIV, MVT::f32, Custom);
448   setOperationAction(ISD::FDIV, MVT::f64, Custom);
449 
450   if (Subtarget->has16BitInsts()) {
451     setOperationAction(ISD::Constant, MVT::i16, Legal);
452 
453     setOperationAction(ISD::SMIN, MVT::i16, Legal);
454     setOperationAction(ISD::SMAX, MVT::i16, Legal);
455 
456     setOperationAction(ISD::UMIN, MVT::i16, Legal);
457     setOperationAction(ISD::UMAX, MVT::i16, Legal);
458 
459     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
460     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
461 
462     setOperationAction(ISD::ROTR, MVT::i16, Promote);
463     setOperationAction(ISD::ROTL, MVT::i16, Promote);
464 
465     setOperationAction(ISD::SDIV, MVT::i16, Promote);
466     setOperationAction(ISD::UDIV, MVT::i16, Promote);
467     setOperationAction(ISD::SREM, MVT::i16, Promote);
468     setOperationAction(ISD::UREM, MVT::i16, Promote);
469 
470     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
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     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
495     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
496 
497     // F16 - Constant Actions.
498     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
499 
500     // F16 - Load/Store Actions.
501     setOperationAction(ISD::LOAD, MVT::f16, Promote);
502     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
503     setOperationAction(ISD::STORE, MVT::f16, Promote);
504     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
505 
506     // F16 - VOP1 Actions.
507     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
508     setOperationAction(ISD::FCOS, MVT::f16, Promote);
509     setOperationAction(ISD::FSIN, MVT::f16, Promote);
510     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
511     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
512     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
513     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
514     setOperationAction(ISD::FROUND, MVT::f16, Custom);
515 
516     // F16 - VOP2 Actions.
517     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
518     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
519 
520     setOperationAction(ISD::FDIV, MVT::f16, Custom);
521 
522     // F16 - VOP3 Actions.
523     setOperationAction(ISD::FMA, MVT::f16, Legal);
524     if (!Subtarget->hasFP16Denormals() && STI.hasMadF16())
525       setOperationAction(ISD::FMAD, MVT::f16, Legal);
526 
527     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
528       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
529         switch (Op) {
530         case ISD::LOAD:
531         case ISD::STORE:
532         case ISD::BUILD_VECTOR:
533         case ISD::BITCAST:
534         case ISD::EXTRACT_VECTOR_ELT:
535         case ISD::INSERT_VECTOR_ELT:
536         case ISD::INSERT_SUBVECTOR:
537         case ISD::EXTRACT_SUBVECTOR:
538         case ISD::SCALAR_TO_VECTOR:
539           break;
540         case ISD::CONCAT_VECTORS:
541           setOperationAction(Op, VT, Custom);
542           break;
543         default:
544           setOperationAction(Op, VT, Expand);
545           break;
546         }
547       }
548     }
549 
550     // XXX - Do these do anything? Vector constants turn into build_vector.
551     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
552     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
553 
554     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
555     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
556 
557     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
558     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
559     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
560     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
561 
562     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
563     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
564     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
565     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
566 
567     setOperationAction(ISD::AND, MVT::v2i16, Promote);
568     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
569     setOperationAction(ISD::OR, MVT::v2i16, Promote);
570     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
571     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
572     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
573 
574     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
575     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
576     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
577     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
578 
579     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
580     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
581     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
582     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
583 
584     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
585     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
586     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
587     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
588 
589     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
590     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
591     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
592 
593     if (!Subtarget->hasVOP3PInsts()) {
594       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
595       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
596     }
597 
598     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
599     // This isn't really legal, but this avoids the legalizer unrolling it (and
600     // allows matching fneg (fabs x) patterns)
601     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
602 
603     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
604     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
605     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
606     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
607 
608     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
609     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
610 
611     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
612     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
613   }
614 
615   if (Subtarget->hasVOP3PInsts()) {
616     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
617     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
618     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
619     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
620     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
621     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
622     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
623     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
624     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
625     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
626 
627     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
628     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
629     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
630 
631     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
632     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
633 
634     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
635 
636     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
637     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
638 
639     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
640     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
641     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
642     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
643     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
644     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
645 
646     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
647     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
648     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
649     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
650 
651     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
652     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
653 
654     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
655     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
656 
657     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
658     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
659     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
660 
661     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
662     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
663     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
664   }
665 
666   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
667   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
668 
669   if (Subtarget->has16BitInsts()) {
670     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
671     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
672     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
673     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
674   } else {
675     // Legalization hack.
676     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
677     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
678 
679     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
680     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
681   }
682 
683   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
684     setOperationAction(ISD::SELECT, VT, Custom);
685   }
686 
687   setTargetDAGCombine(ISD::ADD);
688   setTargetDAGCombine(ISD::ADDCARRY);
689   setTargetDAGCombine(ISD::SUB);
690   setTargetDAGCombine(ISD::SUBCARRY);
691   setTargetDAGCombine(ISD::FADD);
692   setTargetDAGCombine(ISD::FSUB);
693   setTargetDAGCombine(ISD::FMINNUM);
694   setTargetDAGCombine(ISD::FMAXNUM);
695   setTargetDAGCombine(ISD::FMINNUM_IEEE);
696   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
697   setTargetDAGCombine(ISD::FMA);
698   setTargetDAGCombine(ISD::SMIN);
699   setTargetDAGCombine(ISD::SMAX);
700   setTargetDAGCombine(ISD::UMIN);
701   setTargetDAGCombine(ISD::UMAX);
702   setTargetDAGCombine(ISD::SETCC);
703   setTargetDAGCombine(ISD::AND);
704   setTargetDAGCombine(ISD::OR);
705   setTargetDAGCombine(ISD::XOR);
706   setTargetDAGCombine(ISD::SINT_TO_FP);
707   setTargetDAGCombine(ISD::UINT_TO_FP);
708   setTargetDAGCombine(ISD::FCANONICALIZE);
709   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
710   setTargetDAGCombine(ISD::ZERO_EXTEND);
711   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
712   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
713   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
714 
715   // All memory operations. Some folding on the pointer operand is done to help
716   // matching the constant offsets in the addressing modes.
717   setTargetDAGCombine(ISD::LOAD);
718   setTargetDAGCombine(ISD::STORE);
719   setTargetDAGCombine(ISD::ATOMIC_LOAD);
720   setTargetDAGCombine(ISD::ATOMIC_STORE);
721   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
722   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
723   setTargetDAGCombine(ISD::ATOMIC_SWAP);
724   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
725   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
726   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
727   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
728   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
729   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
730   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
731   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
732   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
733   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
734   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
735 
736   setSchedulingPreference(Sched::RegPressure);
737 }
738 
739 const GCNSubtarget *SITargetLowering::getSubtarget() const {
740   return Subtarget;
741 }
742 
743 //===----------------------------------------------------------------------===//
744 // TargetLowering queries
745 //===----------------------------------------------------------------------===//
746 
747 // v_mad_mix* support a conversion from f16 to f32.
748 //
749 // There is only one special case when denormals are enabled we don't currently,
750 // where this is OK to use.
751 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
752                                            EVT DestVT, EVT SrcVT) const {
753   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
754           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
755          DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
756          SrcVT.getScalarType() == MVT::f16;
757 }
758 
759 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
760   // SI has some legal vector types, but no legal vector operations. Say no
761   // shuffles are legal in order to prefer scalarizing some vector operations.
762   return false;
763 }
764 
765 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
766                                                     CallingConv::ID CC,
767                                                     EVT VT) const {
768   // TODO: Consider splitting all arguments into 32-bit pieces.
769   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
770     EVT ScalarVT = VT.getScalarType();
771     unsigned Size = ScalarVT.getSizeInBits();
772     if (Size == 32)
773       return ScalarVT.getSimpleVT();
774 
775     if (Size == 64)
776       return MVT::i32;
777 
778     if (Size == 16 && Subtarget->has16BitInsts())
779       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
780   }
781 
782   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
783 }
784 
785 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
786                                                          CallingConv::ID CC,
787                                                          EVT VT) const {
788   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
789     unsigned NumElts = VT.getVectorNumElements();
790     EVT ScalarVT = VT.getScalarType();
791     unsigned Size = ScalarVT.getSizeInBits();
792 
793     if (Size == 32)
794       return NumElts;
795 
796     if (Size == 64)
797       return 2 * NumElts;
798 
799     if (Size == 16 && Subtarget->has16BitInsts())
800       return (VT.getVectorNumElements() + 1) / 2;
801   }
802 
803   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
804 }
805 
806 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
807   LLVMContext &Context, CallingConv::ID CC,
808   EVT VT, EVT &IntermediateVT,
809   unsigned &NumIntermediates, MVT &RegisterVT) const {
810   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
811     unsigned NumElts = VT.getVectorNumElements();
812     EVT ScalarVT = VT.getScalarType();
813     unsigned Size = ScalarVT.getSizeInBits();
814     if (Size == 32) {
815       RegisterVT = ScalarVT.getSimpleVT();
816       IntermediateVT = RegisterVT;
817       NumIntermediates = NumElts;
818       return NumIntermediates;
819     }
820 
821     if (Size == 64) {
822       RegisterVT = MVT::i32;
823       IntermediateVT = RegisterVT;
824       NumIntermediates = 2 * NumElts;
825       return NumIntermediates;
826     }
827 
828     // FIXME: We should fix the ABI to be the same on targets without 16-bit
829     // support, but unless we can properly handle 3-vectors, it will be still be
830     // inconsistent.
831     if (Size == 16 && Subtarget->has16BitInsts()) {
832       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
833       IntermediateVT = RegisterVT;
834       NumIntermediates = (NumElts + 1) / 2;
835       return NumIntermediates;
836     }
837   }
838 
839   return TargetLowering::getVectorTypeBreakdownForCallingConv(
840     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
841 }
842 
843 static MVT memVTFromAggregate(Type *Ty) {
844   // Only limited forms of aggregate type currently expected.
845   assert(Ty->isStructTy() && "Expected struct type");
846 
847 
848   Type *ElementType = nullptr;
849   unsigned NumElts;
850   if (Ty->getContainedType(0)->isVectorTy()) {
851     VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
852     ElementType = VecComponent->getElementType();
853     NumElts = VecComponent->getNumElements();
854   } else {
855     ElementType = Ty->getContainedType(0);
856     NumElts = 1;
857   }
858 
859   assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
860 
861   // Calculate the size of the memVT type from the aggregate
862   unsigned Pow2Elts = 0;
863   unsigned ElementSize;
864   switch (ElementType->getTypeID()) {
865     default:
866       llvm_unreachable("Unknown type!");
867     case Type::IntegerTyID:
868       ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
869       break;
870     case Type::HalfTyID:
871       ElementSize = 16;
872       break;
873     case Type::FloatTyID:
874       ElementSize = 32;
875       break;
876   }
877   unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
878   Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
879 
880   return MVT::getVectorVT(MVT::getVT(ElementType, false),
881                           Pow2Elts);
882 }
883 
884 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
885                                           const CallInst &CI,
886                                           MachineFunction &MF,
887                                           unsigned IntrID) const {
888   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
889           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
890     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
891                                                   (Intrinsic::ID)IntrID);
892     if (Attr.hasFnAttribute(Attribute::ReadNone))
893       return false;
894 
895     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
896 
897     if (RsrcIntr->IsImage) {
898       Info.ptrVal = MFI->getImagePSV(
899         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
900         CI.getArgOperand(RsrcIntr->RsrcArg));
901       Info.align = 0;
902     } else {
903       Info.ptrVal = MFI->getBufferPSV(
904         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
905         CI.getArgOperand(RsrcIntr->RsrcArg));
906     }
907 
908     Info.flags = MachineMemOperand::MODereferenceable;
909     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
910       Info.opc = ISD::INTRINSIC_W_CHAIN;
911       Info.memVT = MVT::getVT(CI.getType(), true);
912       if (Info.memVT == MVT::Other) {
913         // Some intrinsics return an aggregate type - special case to work out
914         // the correct memVT
915         Info.memVT = memVTFromAggregate(CI.getType());
916       }
917       Info.flags |= MachineMemOperand::MOLoad;
918     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
919       Info.opc = ISD::INTRINSIC_VOID;
920       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
921       Info.flags |= MachineMemOperand::MOStore;
922     } else {
923       // Atomic
924       Info.opc = ISD::INTRINSIC_W_CHAIN;
925       Info.memVT = MVT::getVT(CI.getType());
926       Info.flags = MachineMemOperand::MOLoad |
927                    MachineMemOperand::MOStore |
928                    MachineMemOperand::MODereferenceable;
929 
930       // XXX - Should this be volatile without known ordering?
931       Info.flags |= MachineMemOperand::MOVolatile;
932     }
933     return true;
934   }
935 
936   switch (IntrID) {
937   case Intrinsic::amdgcn_atomic_inc:
938   case Intrinsic::amdgcn_atomic_dec:
939   case Intrinsic::amdgcn_ds_ordered_add:
940   case Intrinsic::amdgcn_ds_ordered_swap:
941   case Intrinsic::amdgcn_ds_fadd:
942   case Intrinsic::amdgcn_ds_fmin:
943   case Intrinsic::amdgcn_ds_fmax: {
944     Info.opc = ISD::INTRINSIC_W_CHAIN;
945     Info.memVT = MVT::getVT(CI.getType());
946     Info.ptrVal = CI.getOperand(0);
947     Info.align = 0;
948     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
949 
950     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
951     if (!Vol->isZero())
952       Info.flags |= MachineMemOperand::MOVolatile;
953 
954     return true;
955   }
956   case Intrinsic::amdgcn_ds_append:
957   case Intrinsic::amdgcn_ds_consume: {
958     Info.opc = ISD::INTRINSIC_W_CHAIN;
959     Info.memVT = MVT::getVT(CI.getType());
960     Info.ptrVal = CI.getOperand(0);
961     Info.align = 0;
962     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
963 
964     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
965     if (!Vol->isZero())
966       Info.flags |= MachineMemOperand::MOVolatile;
967 
968     return true;
969   }
970   default:
971     return false;
972   }
973 }
974 
975 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
976                                             SmallVectorImpl<Value*> &Ops,
977                                             Type *&AccessTy) const {
978   switch (II->getIntrinsicID()) {
979   case Intrinsic::amdgcn_atomic_inc:
980   case Intrinsic::amdgcn_atomic_dec:
981   case Intrinsic::amdgcn_ds_ordered_add:
982   case Intrinsic::amdgcn_ds_ordered_swap:
983   case Intrinsic::amdgcn_ds_fadd:
984   case Intrinsic::amdgcn_ds_fmin:
985   case Intrinsic::amdgcn_ds_fmax: {
986     Value *Ptr = II->getArgOperand(0);
987     AccessTy = II->getType();
988     Ops.push_back(Ptr);
989     return true;
990   }
991   default:
992     return false;
993   }
994 }
995 
996 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
997   if (!Subtarget->hasFlatInstOffsets()) {
998     // Flat instructions do not have offsets, and only have the register
999     // address.
1000     return AM.BaseOffs == 0 && AM.Scale == 0;
1001   }
1002 
1003   // GFX9 added a 13-bit signed offset. When using regular flat instructions,
1004   // the sign bit is ignored and is treated as a 12-bit unsigned offset.
1005 
1006   // GFX10 shrinked signed offset to 12 bits. When using regular flat
1007   // instructions, the sign bit is also ignored and is treated as 11-bit
1008   // unsigned offset.
1009 
1010   if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
1011     return isUInt<11>(AM.BaseOffs) && AM.Scale == 0;
1012 
1013   // Just r + i
1014   return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
1015 }
1016 
1017 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1018   if (Subtarget->hasFlatGlobalInsts())
1019     return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
1020 
1021   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1022       // Assume the we will use FLAT for all global memory accesses
1023       // on VI.
1024       // FIXME: This assumption is currently wrong.  On VI we still use
1025       // MUBUF instructions for the r + i addressing mode.  As currently
1026       // implemented, the MUBUF instructions only work on buffer < 4GB.
1027       // It may be possible to support > 4GB buffers with MUBUF instructions,
1028       // by setting the stride value in the resource descriptor which would
1029       // increase the size limit to (stride * 4GB).  However, this is risky,
1030       // because it has never been validated.
1031     return isLegalFlatAddressingMode(AM);
1032   }
1033 
1034   return isLegalMUBUFAddressingMode(AM);
1035 }
1036 
1037 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1038   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1039   // additionally can do r + r + i with addr64. 32-bit has more addressing
1040   // mode options. Depending on the resource constant, it can also do
1041   // (i64 r0) + (i32 r1) * (i14 i).
1042   //
1043   // Private arrays end up using a scratch buffer most of the time, so also
1044   // assume those use MUBUF instructions. Scratch loads / stores are currently
1045   // implemented as mubuf instructions with offen bit set, so slightly
1046   // different than the normal addr64.
1047   if (!isUInt<12>(AM.BaseOffs))
1048     return false;
1049 
1050   // FIXME: Since we can split immediate into soffset and immediate offset,
1051   // would it make sense to allow any immediate?
1052 
1053   switch (AM.Scale) {
1054   case 0: // r + i or just i, depending on HasBaseReg.
1055     return true;
1056   case 1:
1057     return true; // We have r + r or r + i.
1058   case 2:
1059     if (AM.HasBaseReg) {
1060       // Reject 2 * r + r.
1061       return false;
1062     }
1063 
1064     // Allow 2 * r as r + r
1065     // Or  2 * r + i is allowed as r + r + i.
1066     return true;
1067   default: // Don't allow n * r
1068     return false;
1069   }
1070 }
1071 
1072 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1073                                              const AddrMode &AM, Type *Ty,
1074                                              unsigned AS, Instruction *I) const {
1075   // No global is ever allowed as a base.
1076   if (AM.BaseGV)
1077     return false;
1078 
1079   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1080     return isLegalGlobalAddressingMode(AM);
1081 
1082   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1083       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1084       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1085     // If the offset isn't a multiple of 4, it probably isn't going to be
1086     // correctly aligned.
1087     // FIXME: Can we get the real alignment here?
1088     if (AM.BaseOffs % 4 != 0)
1089       return isLegalMUBUFAddressingMode(AM);
1090 
1091     // There are no SMRD extloads, so if we have to do a small type access we
1092     // will use a MUBUF load.
1093     // FIXME?: We also need to do this if unaligned, but we don't know the
1094     // alignment here.
1095     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1096       return isLegalGlobalAddressingMode(AM);
1097 
1098     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1099       // SMRD instructions have an 8-bit, dword offset on SI.
1100       if (!isUInt<8>(AM.BaseOffs / 4))
1101         return false;
1102     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1103       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1104       // in 8-bits, it can use a smaller encoding.
1105       if (!isUInt<32>(AM.BaseOffs / 4))
1106         return false;
1107     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1108       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1109       if (!isUInt<20>(AM.BaseOffs))
1110         return false;
1111     } else
1112       llvm_unreachable("unhandled generation");
1113 
1114     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1115       return true;
1116 
1117     if (AM.Scale == 1 && AM.HasBaseReg)
1118       return true;
1119 
1120     return false;
1121 
1122   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1123     return isLegalMUBUFAddressingMode(AM);
1124   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1125              AS == AMDGPUAS::REGION_ADDRESS) {
1126     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1127     // field.
1128     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1129     // an 8-bit dword offset but we don't know the alignment here.
1130     if (!isUInt<16>(AM.BaseOffs))
1131       return false;
1132 
1133     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1134       return true;
1135 
1136     if (AM.Scale == 1 && AM.HasBaseReg)
1137       return true;
1138 
1139     return false;
1140   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1141              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1142     // For an unknown address space, this usually means that this is for some
1143     // reason being used for pure arithmetic, and not based on some addressing
1144     // computation. We don't have instructions that compute pointers with any
1145     // addressing modes, so treat them as having no offset like flat
1146     // instructions.
1147     return isLegalFlatAddressingMode(AM);
1148   } else {
1149     llvm_unreachable("unhandled address space");
1150   }
1151 }
1152 
1153 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1154                                         const SelectionDAG &DAG) const {
1155   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1156     return (MemVT.getSizeInBits() <= 4 * 32);
1157   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1158     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1159     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1160   } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
1161     return (MemVT.getSizeInBits() <= 2 * 32);
1162   }
1163   return true;
1164 }
1165 
1166 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1167                                                       unsigned AddrSpace,
1168                                                       unsigned Align,
1169                                                       bool *IsFast) const {
1170   if (IsFast)
1171     *IsFast = false;
1172 
1173   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1174   // which isn't a simple VT.
1175   // Until MVT is extended to handle this, simply check for the size and
1176   // rely on the condition below: allow accesses if the size is a multiple of 4.
1177   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1178                            VT.getStoreSize() > 16)) {
1179     return false;
1180   }
1181 
1182   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1183       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1184     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1185     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1186     // with adjacent offsets.
1187     bool AlignedBy4 = (Align % 4 == 0);
1188     if (IsFast)
1189       *IsFast = AlignedBy4;
1190 
1191     return AlignedBy4;
1192   }
1193 
1194   // FIXME: We have to be conservative here and assume that flat operations
1195   // will access scratch.  If we had access to the IR function, then we
1196   // could determine if any private memory was used in the function.
1197   if (!Subtarget->hasUnalignedScratchAccess() &&
1198       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1199        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1200     bool AlignedBy4 = Align >= 4;
1201     if (IsFast)
1202       *IsFast = AlignedBy4;
1203 
1204     return AlignedBy4;
1205   }
1206 
1207   if (Subtarget->hasUnalignedBufferAccess()) {
1208     // If we have an uniform constant load, it still requires using a slow
1209     // buffer instruction if unaligned.
1210     if (IsFast) {
1211       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1212                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1213         (Align % 4 == 0) : true;
1214     }
1215 
1216     return true;
1217   }
1218 
1219   // Smaller than dword value must be aligned.
1220   if (VT.bitsLT(MVT::i32))
1221     return false;
1222 
1223   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1224   // byte-address are ignored, thus forcing Dword alignment.
1225   // This applies to private, global, and constant memory.
1226   if (IsFast)
1227     *IsFast = true;
1228 
1229   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1230 }
1231 
1232 EVT SITargetLowering::getOptimalMemOpType(
1233     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
1234     bool ZeroMemset, bool MemcpyStrSrc,
1235     const AttributeList &FuncAttributes) const {
1236   // FIXME: Should account for address space here.
1237 
1238   // The default fallback uses the private pointer size as a guess for a type to
1239   // use. Make sure we switch these to 64-bit accesses.
1240 
1241   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1242     return MVT::v4i32;
1243 
1244   if (Size >= 8 && DstAlign >= 4)
1245     return MVT::v2i32;
1246 
1247   // Use the default.
1248   return MVT::Other;
1249 }
1250 
1251 static bool isFlatGlobalAddrSpace(unsigned AS) {
1252   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
1253          AS == AMDGPUAS::FLAT_ADDRESS ||
1254          AS == AMDGPUAS::CONSTANT_ADDRESS ||
1255          AS > AMDGPUAS::MAX_AMDGPU_ADDRESS;
1256 }
1257 
1258 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1259                                            unsigned DestAS) const {
1260   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1261 }
1262 
1263 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1264   const MemSDNode *MemNode = cast<MemSDNode>(N);
1265   const Value *Ptr = MemNode->getMemOperand()->getValue();
1266   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1267   return I && I->getMetadata("amdgpu.noclobber");
1268 }
1269 
1270 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
1271                                             unsigned DestAS) const {
1272   // Flat -> private/local is a simple truncate.
1273   // Flat -> global is no-op
1274   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1275     return true;
1276 
1277   return isNoopAddrSpaceCast(SrcAS, DestAS);
1278 }
1279 
1280 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1281   const MemSDNode *MemNode = cast<MemSDNode>(N);
1282 
1283   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1284 }
1285 
1286 TargetLoweringBase::LegalizeTypeAction
1287 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1288   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1289     return TypeSplitVector;
1290 
1291   return TargetLoweringBase::getPreferredVectorAction(VT);
1292 }
1293 
1294 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1295                                                          Type *Ty) const {
1296   // FIXME: Could be smarter if called for vector constants.
1297   return true;
1298 }
1299 
1300 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1301   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1302     switch (Op) {
1303     case ISD::LOAD:
1304     case ISD::STORE:
1305 
1306     // These operations are done with 32-bit instructions anyway.
1307     case ISD::AND:
1308     case ISD::OR:
1309     case ISD::XOR:
1310     case ISD::SELECT:
1311       // TODO: Extensions?
1312       return true;
1313     default:
1314       return false;
1315     }
1316   }
1317 
1318   // SimplifySetCC uses this function to determine whether or not it should
1319   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1320   if (VT == MVT::i1 && Op == ISD::SETCC)
1321     return false;
1322 
1323   return TargetLowering::isTypeDesirableForOp(Op, VT);
1324 }
1325 
1326 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1327                                                    const SDLoc &SL,
1328                                                    SDValue Chain,
1329                                                    uint64_t Offset) const {
1330   const DataLayout &DL = DAG.getDataLayout();
1331   MachineFunction &MF = DAG.getMachineFunction();
1332   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1333 
1334   const ArgDescriptor *InputPtrReg;
1335   const TargetRegisterClass *RC;
1336 
1337   std::tie(InputPtrReg, RC)
1338     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1339 
1340   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1341   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1342   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1343     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1344 
1345   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1346 }
1347 
1348 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1349                                             const SDLoc &SL) const {
1350   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1351                                                FIRST_IMPLICIT);
1352   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1353 }
1354 
1355 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1356                                          const SDLoc &SL, SDValue Val,
1357                                          bool Signed,
1358                                          const ISD::InputArg *Arg) const {
1359   // First, if it is a widened vector, narrow it.
1360   if (VT.isVector() &&
1361       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1362     EVT NarrowedVT =
1363         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1364                          VT.getVectorNumElements());
1365     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1366                       DAG.getConstant(0, SL, MVT::i32));
1367   }
1368 
1369   // Then convert the vector elements or scalar value.
1370   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1371       VT.bitsLT(MemVT)) {
1372     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1373     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1374   }
1375 
1376   if (MemVT.isFloatingPoint())
1377     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1378   else if (Signed)
1379     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1380   else
1381     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1382 
1383   return Val;
1384 }
1385 
1386 SDValue SITargetLowering::lowerKernargMemParameter(
1387   SelectionDAG &DAG, EVT VT, EVT MemVT,
1388   const SDLoc &SL, SDValue Chain,
1389   uint64_t Offset, unsigned Align, bool Signed,
1390   const ISD::InputArg *Arg) const {
1391   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1392   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
1393   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1394 
1395   // Try to avoid using an extload by loading earlier than the argument address,
1396   // and extracting the relevant bits. The load should hopefully be merged with
1397   // the previous argument.
1398   if (MemVT.getStoreSize() < 4 && Align < 4) {
1399     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1400     int64_t AlignDownOffset = alignDown(Offset, 4);
1401     int64_t OffsetDiff = Offset - AlignDownOffset;
1402 
1403     EVT IntVT = MemVT.changeTypeToInteger();
1404 
1405     // TODO: If we passed in the base kernel offset we could have a better
1406     // alignment than 4, but we don't really need it.
1407     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1408     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1409                                MachineMemOperand::MODereferenceable |
1410                                MachineMemOperand::MOInvariant);
1411 
1412     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1413     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1414 
1415     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1416     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1417     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1418 
1419 
1420     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1421   }
1422 
1423   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1424   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1425                              MachineMemOperand::MODereferenceable |
1426                              MachineMemOperand::MOInvariant);
1427 
1428   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1429   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1430 }
1431 
1432 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1433                                               const SDLoc &SL, SDValue Chain,
1434                                               const ISD::InputArg &Arg) const {
1435   MachineFunction &MF = DAG.getMachineFunction();
1436   MachineFrameInfo &MFI = MF.getFrameInfo();
1437 
1438   if (Arg.Flags.isByVal()) {
1439     unsigned Size = Arg.Flags.getByValSize();
1440     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1441     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1442   }
1443 
1444   unsigned ArgOffset = VA.getLocMemOffset();
1445   unsigned ArgSize = VA.getValVT().getStoreSize();
1446 
1447   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1448 
1449   // Create load nodes to retrieve arguments from the stack.
1450   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1451   SDValue ArgValue;
1452 
1453   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1454   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1455   MVT MemVT = VA.getValVT();
1456 
1457   switch (VA.getLocInfo()) {
1458   default:
1459     break;
1460   case CCValAssign::BCvt:
1461     MemVT = VA.getLocVT();
1462     break;
1463   case CCValAssign::SExt:
1464     ExtType = ISD::SEXTLOAD;
1465     break;
1466   case CCValAssign::ZExt:
1467     ExtType = ISD::ZEXTLOAD;
1468     break;
1469   case CCValAssign::AExt:
1470     ExtType = ISD::EXTLOAD;
1471     break;
1472   }
1473 
1474   ArgValue = DAG.getExtLoad(
1475     ExtType, SL, VA.getLocVT(), Chain, FIN,
1476     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1477     MemVT);
1478   return ArgValue;
1479 }
1480 
1481 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1482   const SIMachineFunctionInfo &MFI,
1483   EVT VT,
1484   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1485   const ArgDescriptor *Reg;
1486   const TargetRegisterClass *RC;
1487 
1488   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1489   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1490 }
1491 
1492 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1493                                    CallingConv::ID CallConv,
1494                                    ArrayRef<ISD::InputArg> Ins,
1495                                    BitVector &Skipped,
1496                                    FunctionType *FType,
1497                                    SIMachineFunctionInfo *Info) {
1498   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1499     const ISD::InputArg *Arg = &Ins[I];
1500 
1501     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1502            "vector type argument should have been split");
1503 
1504     // First check if it's a PS input addr.
1505     if (CallConv == CallingConv::AMDGPU_PS &&
1506         !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) {
1507 
1508       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1509 
1510       // Inconveniently only the first part of the split is marked as isSplit,
1511       // so skip to the end. We only want to increment PSInputNum once for the
1512       // entire split argument.
1513       if (Arg->Flags.isSplit()) {
1514         while (!Arg->Flags.isSplitEnd()) {
1515           assert(!Arg->VT.isVector() &&
1516                  "unexpected vector split in ps argument type");
1517           if (!SkipArg)
1518             Splits.push_back(*Arg);
1519           Arg = &Ins[++I];
1520         }
1521       }
1522 
1523       if (SkipArg) {
1524         // We can safely skip PS inputs.
1525         Skipped.set(Arg->getOrigArgIndex());
1526         ++PSInputNum;
1527         continue;
1528       }
1529 
1530       Info->markPSInputAllocated(PSInputNum);
1531       if (Arg->Used)
1532         Info->markPSInputEnabled(PSInputNum);
1533 
1534       ++PSInputNum;
1535     }
1536 
1537     Splits.push_back(*Arg);
1538   }
1539 }
1540 
1541 // Allocate special inputs passed in VGPRs.
1542 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1543                                            MachineFunction &MF,
1544                                            const SIRegisterInfo &TRI,
1545                                            SIMachineFunctionInfo &Info) {
1546   if (Info.hasWorkItemIDX()) {
1547     unsigned Reg = AMDGPU::VGPR0;
1548     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1549 
1550     CCInfo.AllocateReg(Reg);
1551     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1552   }
1553 
1554   if (Info.hasWorkItemIDY()) {
1555     unsigned Reg = AMDGPU::VGPR1;
1556     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1557 
1558     CCInfo.AllocateReg(Reg);
1559     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1560   }
1561 
1562   if (Info.hasWorkItemIDZ()) {
1563     unsigned Reg = AMDGPU::VGPR2;
1564     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1565 
1566     CCInfo.AllocateReg(Reg);
1567     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1568   }
1569 }
1570 
1571 // Try to allocate a VGPR at the end of the argument list, or if no argument
1572 // VGPRs are left allocating a stack slot.
1573 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1574   ArrayRef<MCPhysReg> ArgVGPRs
1575     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1576   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1577   if (RegIdx == ArgVGPRs.size()) {
1578     // Spill to stack required.
1579     int64_t Offset = CCInfo.AllocateStack(4, 4);
1580 
1581     return ArgDescriptor::createStack(Offset);
1582   }
1583 
1584   unsigned Reg = ArgVGPRs[RegIdx];
1585   Reg = CCInfo.AllocateReg(Reg);
1586   assert(Reg != AMDGPU::NoRegister);
1587 
1588   MachineFunction &MF = CCInfo.getMachineFunction();
1589   MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1590   return ArgDescriptor::createRegister(Reg);
1591 }
1592 
1593 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1594                                              const TargetRegisterClass *RC,
1595                                              unsigned NumArgRegs) {
1596   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1597   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1598   if (RegIdx == ArgSGPRs.size())
1599     report_fatal_error("ran out of SGPRs for arguments");
1600 
1601   unsigned Reg = ArgSGPRs[RegIdx];
1602   Reg = CCInfo.AllocateReg(Reg);
1603   assert(Reg != AMDGPU::NoRegister);
1604 
1605   MachineFunction &MF = CCInfo.getMachineFunction();
1606   MF.addLiveIn(Reg, RC);
1607   return ArgDescriptor::createRegister(Reg);
1608 }
1609 
1610 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1611   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1612 }
1613 
1614 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1615   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1616 }
1617 
1618 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1619                                       MachineFunction &MF,
1620                                       const SIRegisterInfo &TRI,
1621                                       SIMachineFunctionInfo &Info) {
1622   if (Info.hasWorkItemIDX())
1623     Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1624 
1625   if (Info.hasWorkItemIDY())
1626     Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1627 
1628   if (Info.hasWorkItemIDZ())
1629     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1630 }
1631 
1632 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1633                                       MachineFunction &MF,
1634                                       const SIRegisterInfo &TRI,
1635                                       SIMachineFunctionInfo &Info) {
1636   auto &ArgInfo = Info.getArgInfo();
1637 
1638   // TODO: Unify handling with private memory pointers.
1639 
1640   if (Info.hasDispatchPtr())
1641     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1642 
1643   if (Info.hasQueuePtr())
1644     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1645 
1646   if (Info.hasKernargSegmentPtr())
1647     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1648 
1649   if (Info.hasDispatchID())
1650     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1651 
1652   // flat_scratch_init is not applicable for non-kernel functions.
1653 
1654   if (Info.hasWorkGroupIDX())
1655     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1656 
1657   if (Info.hasWorkGroupIDY())
1658     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1659 
1660   if (Info.hasWorkGroupIDZ())
1661     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1662 
1663   if (Info.hasImplicitArgPtr())
1664     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1665 }
1666 
1667 // Allocate special inputs passed in user SGPRs.
1668 static void allocateHSAUserSGPRs(CCState &CCInfo,
1669                                  MachineFunction &MF,
1670                                  const SIRegisterInfo &TRI,
1671                                  SIMachineFunctionInfo &Info) {
1672   if (Info.hasImplicitBufferPtr()) {
1673     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1674     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1675     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1676   }
1677 
1678   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1679   if (Info.hasPrivateSegmentBuffer()) {
1680     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1681     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1682     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1683   }
1684 
1685   if (Info.hasDispatchPtr()) {
1686     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1687     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1688     CCInfo.AllocateReg(DispatchPtrReg);
1689   }
1690 
1691   if (Info.hasQueuePtr()) {
1692     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1693     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1694     CCInfo.AllocateReg(QueuePtrReg);
1695   }
1696 
1697   if (Info.hasKernargSegmentPtr()) {
1698     unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1699     MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1700     CCInfo.AllocateReg(InputPtrReg);
1701   }
1702 
1703   if (Info.hasDispatchID()) {
1704     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1705     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1706     CCInfo.AllocateReg(DispatchIDReg);
1707   }
1708 
1709   if (Info.hasFlatScratchInit()) {
1710     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1711     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1712     CCInfo.AllocateReg(FlatScratchInitReg);
1713   }
1714 
1715   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1716   // these from the dispatch pointer.
1717 }
1718 
1719 // Allocate special input registers that are initialized per-wave.
1720 static void allocateSystemSGPRs(CCState &CCInfo,
1721                                 MachineFunction &MF,
1722                                 SIMachineFunctionInfo &Info,
1723                                 CallingConv::ID CallConv,
1724                                 bool IsShader) {
1725   if (Info.hasWorkGroupIDX()) {
1726     unsigned Reg = Info.addWorkGroupIDX();
1727     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1728     CCInfo.AllocateReg(Reg);
1729   }
1730 
1731   if (Info.hasWorkGroupIDY()) {
1732     unsigned Reg = Info.addWorkGroupIDY();
1733     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1734     CCInfo.AllocateReg(Reg);
1735   }
1736 
1737   if (Info.hasWorkGroupIDZ()) {
1738     unsigned Reg = Info.addWorkGroupIDZ();
1739     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1740     CCInfo.AllocateReg(Reg);
1741   }
1742 
1743   if (Info.hasWorkGroupInfo()) {
1744     unsigned Reg = Info.addWorkGroupInfo();
1745     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1746     CCInfo.AllocateReg(Reg);
1747   }
1748 
1749   if (Info.hasPrivateSegmentWaveByteOffset()) {
1750     // Scratch wave offset passed in system SGPR.
1751     unsigned PrivateSegmentWaveByteOffsetReg;
1752 
1753     if (IsShader) {
1754       PrivateSegmentWaveByteOffsetReg =
1755         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1756 
1757       // This is true if the scratch wave byte offset doesn't have a fixed
1758       // location.
1759       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1760         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1761         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1762       }
1763     } else
1764       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1765 
1766     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1767     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1768   }
1769 }
1770 
1771 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1772                                      MachineFunction &MF,
1773                                      const SIRegisterInfo &TRI,
1774                                      SIMachineFunctionInfo &Info) {
1775   // Now that we've figured out where the scratch register inputs are, see if
1776   // should reserve the arguments and use them directly.
1777   MachineFrameInfo &MFI = MF.getFrameInfo();
1778   bool HasStackObjects = MFI.hasStackObjects();
1779 
1780   // Record that we know we have non-spill stack objects so we don't need to
1781   // check all stack objects later.
1782   if (HasStackObjects)
1783     Info.setHasNonSpillStackObjects(true);
1784 
1785   // Everything live out of a block is spilled with fast regalloc, so it's
1786   // almost certain that spilling will be required.
1787   if (TM.getOptLevel() == CodeGenOpt::None)
1788     HasStackObjects = true;
1789 
1790   // For now assume stack access is needed in any callee functions, so we need
1791   // the scratch registers to pass in.
1792   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1793 
1794   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1795   if (ST.isAmdHsaOrMesa(MF.getFunction())) {
1796     if (RequiresStackAccess) {
1797       // If we have stack objects, we unquestionably need the private buffer
1798       // resource. For the Code Object V2 ABI, this will be the first 4 user
1799       // SGPR inputs. We can reserve those and use them directly.
1800 
1801       unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1802         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1803       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1804 
1805       if (MFI.hasCalls()) {
1806         // If we have calls, we need to keep the frame register in a register
1807         // that won't be clobbered by a call, so ensure it is copied somewhere.
1808 
1809         // This is not a problem for the scratch wave offset, because the same
1810         // registers are reserved in all functions.
1811 
1812         // FIXME: Nothing is really ensuring this is a call preserved register,
1813         // it's just selected from the end so it happens to be.
1814         unsigned ReservedOffsetReg
1815           = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1816         Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1817       } else {
1818         unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1819           AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1820         Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1821       }
1822     } else {
1823       unsigned ReservedBufferReg
1824         = TRI.reservedPrivateSegmentBufferReg(MF);
1825       unsigned ReservedOffsetReg
1826         = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1827 
1828       // We tentatively reserve the last registers (skipping the last two
1829       // which may contain VCC). After register allocation, we'll replace
1830       // these with the ones immediately after those which were really
1831       // allocated. In the prologue copies will be inserted from the argument
1832       // to these reserved registers.
1833       Info.setScratchRSrcReg(ReservedBufferReg);
1834       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1835     }
1836   } else {
1837     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1838 
1839     // Without HSA, relocations are used for the scratch pointer and the
1840     // buffer resource setup is always inserted in the prologue. Scratch wave
1841     // offset is still in an input SGPR.
1842     Info.setScratchRSrcReg(ReservedBufferReg);
1843 
1844     if (HasStackObjects && !MFI.hasCalls()) {
1845       unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1846         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1847       Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1848     } else {
1849       unsigned ReservedOffsetReg
1850         = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1851       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1852     }
1853   }
1854 }
1855 
1856 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1857   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1858   return !Info->isEntryFunction();
1859 }
1860 
1861 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1862 
1863 }
1864 
1865 void SITargetLowering::insertCopiesSplitCSR(
1866   MachineBasicBlock *Entry,
1867   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1868   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1869 
1870   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1871   if (!IStart)
1872     return;
1873 
1874   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1875   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1876   MachineBasicBlock::iterator MBBI = Entry->begin();
1877   for (const MCPhysReg *I = IStart; *I; ++I) {
1878     const TargetRegisterClass *RC = nullptr;
1879     if (AMDGPU::SReg_64RegClass.contains(*I))
1880       RC = &AMDGPU::SGPR_64RegClass;
1881     else if (AMDGPU::SReg_32RegClass.contains(*I))
1882       RC = &AMDGPU::SGPR_32RegClass;
1883     else
1884       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1885 
1886     unsigned NewVR = MRI->createVirtualRegister(RC);
1887     // Create copy from CSR to a virtual register.
1888     Entry->addLiveIn(*I);
1889     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1890       .addReg(*I);
1891 
1892     // Insert the copy-back instructions right before the terminator.
1893     for (auto *Exit : Exits)
1894       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1895               TII->get(TargetOpcode::COPY), *I)
1896         .addReg(NewVR);
1897   }
1898 }
1899 
1900 SDValue SITargetLowering::LowerFormalArguments(
1901     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1902     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1903     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1904   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1905 
1906   MachineFunction &MF = DAG.getMachineFunction();
1907   const Function &Fn = MF.getFunction();
1908   FunctionType *FType = MF.getFunction().getFunctionType();
1909   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1910 
1911   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1912     DiagnosticInfoUnsupported NoGraphicsHSA(
1913         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1914     DAG.getContext()->diagnose(NoGraphicsHSA);
1915     return DAG.getEntryNode();
1916   }
1917 
1918   SmallVector<ISD::InputArg, 16> Splits;
1919   SmallVector<CCValAssign, 16> ArgLocs;
1920   BitVector Skipped(Ins.size());
1921   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1922                  *DAG.getContext());
1923 
1924   bool IsShader = AMDGPU::isShader(CallConv);
1925   bool IsKernel = AMDGPU::isKernel(CallConv);
1926   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1927 
1928   if (!IsEntryFunc) {
1929     // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1930     // this when allocating argument fixed offsets.
1931     CCInfo.AllocateStack(4, 4);
1932   }
1933 
1934   if (IsShader) {
1935     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1936 
1937     // At least one interpolation mode must be enabled or else the GPU will
1938     // hang.
1939     //
1940     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1941     // set PSInputAddr, the user wants to enable some bits after the compilation
1942     // based on run-time states. Since we can't know what the final PSInputEna
1943     // will look like, so we shouldn't do anything here and the user should take
1944     // responsibility for the correct programming.
1945     //
1946     // Otherwise, the following restrictions apply:
1947     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1948     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1949     //   enabled too.
1950     if (CallConv == CallingConv::AMDGPU_PS) {
1951       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1952            ((Info->getPSInputAddr() & 0xF) == 0 &&
1953             Info->isPSInputAllocated(11))) {
1954         CCInfo.AllocateReg(AMDGPU::VGPR0);
1955         CCInfo.AllocateReg(AMDGPU::VGPR1);
1956         Info->markPSInputAllocated(0);
1957         Info->markPSInputEnabled(0);
1958       }
1959       if (Subtarget->isAmdPalOS()) {
1960         // For isAmdPalOS, the user does not enable some bits after compilation
1961         // based on run-time states; the register values being generated here are
1962         // the final ones set in hardware. Therefore we need to apply the
1963         // workaround to PSInputAddr and PSInputEnable together.  (The case where
1964         // a bit is set in PSInputAddr but not PSInputEnable is where the
1965         // frontend set up an input arg for a particular interpolation mode, but
1966         // nothing uses that input arg. Really we should have an earlier pass
1967         // that removes such an arg.)
1968         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1969         if ((PsInputBits & 0x7F) == 0 ||
1970             ((PsInputBits & 0xF) == 0 &&
1971              (PsInputBits >> 11 & 1)))
1972           Info->markPSInputEnabled(
1973               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1974       }
1975     }
1976 
1977     assert(!Info->hasDispatchPtr() &&
1978            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1979            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1980            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1981            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1982            !Info->hasWorkItemIDZ());
1983   } else if (IsKernel) {
1984     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1985   } else {
1986     Splits.append(Ins.begin(), Ins.end());
1987   }
1988 
1989   if (IsEntryFunc) {
1990     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1991     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1992   }
1993 
1994   if (IsKernel) {
1995     analyzeFormalArgumentsCompute(CCInfo, Ins);
1996   } else {
1997     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1998     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1999   }
2000 
2001   SmallVector<SDValue, 16> Chains;
2002 
2003   // FIXME: This is the minimum kernel argument alignment. We should improve
2004   // this to the maximum alignment of the arguments.
2005   //
2006   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2007   // kern arg offset.
2008   const unsigned KernelArgBaseAlign = 16;
2009 
2010    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2011     const ISD::InputArg &Arg = Ins[i];
2012     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2013       InVals.push_back(DAG.getUNDEF(Arg.VT));
2014       continue;
2015     }
2016 
2017     CCValAssign &VA = ArgLocs[ArgIdx++];
2018     MVT VT = VA.getLocVT();
2019 
2020     if (IsEntryFunc && VA.isMemLoc()) {
2021       VT = Ins[i].VT;
2022       EVT MemVT = VA.getLocVT();
2023 
2024       const uint64_t Offset = VA.getLocMemOffset();
2025       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2026 
2027       SDValue Arg = lowerKernargMemParameter(
2028         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2029       Chains.push_back(Arg.getValue(1));
2030 
2031       auto *ParamTy =
2032         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2033       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2034           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2035                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2036         // On SI local pointers are just offsets into LDS, so they are always
2037         // less than 16-bits.  On CI and newer they could potentially be
2038         // real pointers, so we can't guarantee their size.
2039         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2040                           DAG.getValueType(MVT::i16));
2041       }
2042 
2043       InVals.push_back(Arg);
2044       continue;
2045     } else if (!IsEntryFunc && VA.isMemLoc()) {
2046       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2047       InVals.push_back(Val);
2048       if (!Arg.Flags.isByVal())
2049         Chains.push_back(Val.getValue(1));
2050       continue;
2051     }
2052 
2053     assert(VA.isRegLoc() && "Parameter must be in a register!");
2054 
2055     unsigned Reg = VA.getLocReg();
2056     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2057     EVT ValVT = VA.getValVT();
2058 
2059     Reg = MF.addLiveIn(Reg, RC);
2060     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2061 
2062     if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
2063       // The return object should be reasonably addressable.
2064 
2065       // FIXME: This helps when the return is a real sret. If it is a
2066       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2067       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2068       unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
2069       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2070         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2071     }
2072 
2073     // If this is an 8 or 16-bit value, it is really passed promoted
2074     // to 32 bits. Insert an assert[sz]ext to capture this, then
2075     // truncate to the right size.
2076     switch (VA.getLocInfo()) {
2077     case CCValAssign::Full:
2078       break;
2079     case CCValAssign::BCvt:
2080       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2081       break;
2082     case CCValAssign::SExt:
2083       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2084                         DAG.getValueType(ValVT));
2085       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2086       break;
2087     case CCValAssign::ZExt:
2088       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2089                         DAG.getValueType(ValVT));
2090       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2091       break;
2092     case CCValAssign::AExt:
2093       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2094       break;
2095     default:
2096       llvm_unreachable("Unknown loc info!");
2097     }
2098 
2099     InVals.push_back(Val);
2100   }
2101 
2102   if (!IsEntryFunc) {
2103     // Special inputs come after user arguments.
2104     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2105   }
2106 
2107   // Start adding system SGPRs.
2108   if (IsEntryFunc) {
2109     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2110   } else {
2111     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2112     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2113     CCInfo.AllocateReg(Info->getFrameOffsetReg());
2114     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2115   }
2116 
2117   auto &ArgUsageInfo =
2118     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2119   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2120 
2121   unsigned StackArgSize = CCInfo.getNextStackOffset();
2122   Info->setBytesInStackArgArea(StackArgSize);
2123 
2124   return Chains.empty() ? Chain :
2125     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2126 }
2127 
2128 // TODO: If return values can't fit in registers, we should return as many as
2129 // possible in registers before passing on stack.
2130 bool SITargetLowering::CanLowerReturn(
2131   CallingConv::ID CallConv,
2132   MachineFunction &MF, bool IsVarArg,
2133   const SmallVectorImpl<ISD::OutputArg> &Outs,
2134   LLVMContext &Context) const {
2135   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2136   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2137   // for shaders. Vector types should be explicitly handled by CC.
2138   if (AMDGPU::isEntryFunctionCC(CallConv))
2139     return true;
2140 
2141   SmallVector<CCValAssign, 16> RVLocs;
2142   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2143   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2144 }
2145 
2146 SDValue
2147 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2148                               bool isVarArg,
2149                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2150                               const SmallVectorImpl<SDValue> &OutVals,
2151                               const SDLoc &DL, SelectionDAG &DAG) const {
2152   MachineFunction &MF = DAG.getMachineFunction();
2153   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2154 
2155   if (AMDGPU::isKernel(CallConv)) {
2156     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2157                                              OutVals, DL, DAG);
2158   }
2159 
2160   bool IsShader = AMDGPU::isShader(CallConv);
2161 
2162   Info->setIfReturnsVoid(Outs.empty());
2163   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2164 
2165   // CCValAssign - represent the assignment of the return value to a location.
2166   SmallVector<CCValAssign, 48> RVLocs;
2167   SmallVector<ISD::OutputArg, 48> Splits;
2168 
2169   // CCState - Info about the registers and stack slots.
2170   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2171                  *DAG.getContext());
2172 
2173   // Analyze outgoing return values.
2174   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2175 
2176   SDValue Flag;
2177   SmallVector<SDValue, 48> RetOps;
2178   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2179 
2180   // Add return address for callable functions.
2181   if (!Info->isEntryFunction()) {
2182     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2183     SDValue ReturnAddrReg = CreateLiveInRegister(
2184       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2185 
2186     // FIXME: Should be able to use a vreg here, but need a way to prevent it
2187     // from being allcoated to a CSR.
2188 
2189     SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2190                                                 MVT::i64);
2191 
2192     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2193     Flag = Chain.getValue(1);
2194 
2195     RetOps.push_back(PhysReturnAddrReg);
2196   }
2197 
2198   // Copy the result values into the output registers.
2199   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2200        ++I, ++RealRVLocIdx) {
2201     CCValAssign &VA = RVLocs[I];
2202     assert(VA.isRegLoc() && "Can only return in registers!");
2203     // TODO: Partially return in registers if return values don't fit.
2204     SDValue Arg = OutVals[RealRVLocIdx];
2205 
2206     // Copied from other backends.
2207     switch (VA.getLocInfo()) {
2208     case CCValAssign::Full:
2209       break;
2210     case CCValAssign::BCvt:
2211       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2212       break;
2213     case CCValAssign::SExt:
2214       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2215       break;
2216     case CCValAssign::ZExt:
2217       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2218       break;
2219     case CCValAssign::AExt:
2220       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2221       break;
2222     default:
2223       llvm_unreachable("Unknown loc info!");
2224     }
2225 
2226     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2227     Flag = Chain.getValue(1);
2228     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2229   }
2230 
2231   // FIXME: Does sret work properly?
2232   if (!Info->isEntryFunction()) {
2233     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2234     const MCPhysReg *I =
2235       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2236     if (I) {
2237       for (; *I; ++I) {
2238         if (AMDGPU::SReg_64RegClass.contains(*I))
2239           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2240         else if (AMDGPU::SReg_32RegClass.contains(*I))
2241           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2242         else
2243           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2244       }
2245     }
2246   }
2247 
2248   // Update chain and glue.
2249   RetOps[0] = Chain;
2250   if (Flag.getNode())
2251     RetOps.push_back(Flag);
2252 
2253   unsigned Opc = AMDGPUISD::ENDPGM;
2254   if (!IsWaveEnd)
2255     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2256   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2257 }
2258 
2259 SDValue SITargetLowering::LowerCallResult(
2260     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2261     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2262     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2263     SDValue ThisVal) const {
2264   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2265 
2266   // Assign locations to each value returned by this call.
2267   SmallVector<CCValAssign, 16> RVLocs;
2268   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2269                  *DAG.getContext());
2270   CCInfo.AnalyzeCallResult(Ins, RetCC);
2271 
2272   // Copy all of the result registers out of their specified physreg.
2273   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2274     CCValAssign VA = RVLocs[i];
2275     SDValue Val;
2276 
2277     if (VA.isRegLoc()) {
2278       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2279       Chain = Val.getValue(1);
2280       InFlag = Val.getValue(2);
2281     } else if (VA.isMemLoc()) {
2282       report_fatal_error("TODO: return values in memory");
2283     } else
2284       llvm_unreachable("unknown argument location type");
2285 
2286     switch (VA.getLocInfo()) {
2287     case CCValAssign::Full:
2288       break;
2289     case CCValAssign::BCvt:
2290       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2291       break;
2292     case CCValAssign::ZExt:
2293       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2294                         DAG.getValueType(VA.getValVT()));
2295       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2296       break;
2297     case CCValAssign::SExt:
2298       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2299                         DAG.getValueType(VA.getValVT()));
2300       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2301       break;
2302     case CCValAssign::AExt:
2303       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2304       break;
2305     default:
2306       llvm_unreachable("Unknown loc info!");
2307     }
2308 
2309     InVals.push_back(Val);
2310   }
2311 
2312   return Chain;
2313 }
2314 
2315 // Add code to pass special inputs required depending on used features separate
2316 // from the explicit user arguments present in the IR.
2317 void SITargetLowering::passSpecialInputs(
2318     CallLoweringInfo &CLI,
2319     CCState &CCInfo,
2320     const SIMachineFunctionInfo &Info,
2321     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2322     SmallVectorImpl<SDValue> &MemOpChains,
2323     SDValue Chain) const {
2324   // If we don't have a call site, this was a call inserted by
2325   // legalization. These can never use special inputs.
2326   if (!CLI.CS)
2327     return;
2328 
2329   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2330   assert(CalleeFunc);
2331 
2332   SelectionDAG &DAG = CLI.DAG;
2333   const SDLoc &DL = CLI.DL;
2334 
2335   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2336 
2337   auto &ArgUsageInfo =
2338     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2339   const AMDGPUFunctionArgInfo &CalleeArgInfo
2340     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2341 
2342   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2343 
2344   // TODO: Unify with private memory register handling. This is complicated by
2345   // the fact that at least in kernels, the input argument is not necessarily
2346   // in the same location as the input.
2347   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2348     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2349     AMDGPUFunctionArgInfo::QUEUE_PTR,
2350     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2351     AMDGPUFunctionArgInfo::DISPATCH_ID,
2352     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2353     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2354     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2355     AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2356     AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2357     AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2358     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2359   };
2360 
2361   for (auto InputID : InputRegs) {
2362     const ArgDescriptor *OutgoingArg;
2363     const TargetRegisterClass *ArgRC;
2364 
2365     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2366     if (!OutgoingArg)
2367       continue;
2368 
2369     const ArgDescriptor *IncomingArg;
2370     const TargetRegisterClass *IncomingArgRC;
2371     std::tie(IncomingArg, IncomingArgRC)
2372       = CallerArgInfo.getPreloadedValue(InputID);
2373     assert(IncomingArgRC == ArgRC);
2374 
2375     // All special arguments are ints for now.
2376     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2377     SDValue InputReg;
2378 
2379     if (IncomingArg) {
2380       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2381     } else {
2382       // The implicit arg ptr is special because it doesn't have a corresponding
2383       // input for kernels, and is computed from the kernarg segment pointer.
2384       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2385       InputReg = getImplicitArgPtr(DAG, DL);
2386     }
2387 
2388     if (OutgoingArg->isRegister()) {
2389       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2390     } else {
2391       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2392       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2393                                               SpecialArgOffset);
2394       MemOpChains.push_back(ArgStore);
2395     }
2396   }
2397 }
2398 
2399 static bool canGuaranteeTCO(CallingConv::ID CC) {
2400   return CC == CallingConv::Fast;
2401 }
2402 
2403 /// Return true if we might ever do TCO for calls with this calling convention.
2404 static bool mayTailCallThisCC(CallingConv::ID CC) {
2405   switch (CC) {
2406   case CallingConv::C:
2407     return true;
2408   default:
2409     return canGuaranteeTCO(CC);
2410   }
2411 }
2412 
2413 bool SITargetLowering::isEligibleForTailCallOptimization(
2414     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2415     const SmallVectorImpl<ISD::OutputArg> &Outs,
2416     const SmallVectorImpl<SDValue> &OutVals,
2417     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2418   if (!mayTailCallThisCC(CalleeCC))
2419     return false;
2420 
2421   MachineFunction &MF = DAG.getMachineFunction();
2422   const Function &CallerF = MF.getFunction();
2423   CallingConv::ID CallerCC = CallerF.getCallingConv();
2424   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2425   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2426 
2427   // Kernels aren't callable, and don't have a live in return address so it
2428   // doesn't make sense to do a tail call with entry functions.
2429   if (!CallerPreserved)
2430     return false;
2431 
2432   bool CCMatch = CallerCC == CalleeCC;
2433 
2434   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2435     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2436       return true;
2437     return false;
2438   }
2439 
2440   // TODO: Can we handle var args?
2441   if (IsVarArg)
2442     return false;
2443 
2444   for (const Argument &Arg : CallerF.args()) {
2445     if (Arg.hasByValAttr())
2446       return false;
2447   }
2448 
2449   LLVMContext &Ctx = *DAG.getContext();
2450 
2451   // Check that the call results are passed in the same way.
2452   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2453                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2454                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2455     return false;
2456 
2457   // The callee has to preserve all registers the caller needs to preserve.
2458   if (!CCMatch) {
2459     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2460     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2461       return false;
2462   }
2463 
2464   // Nothing more to check if the callee is taking no arguments.
2465   if (Outs.empty())
2466     return true;
2467 
2468   SmallVector<CCValAssign, 16> ArgLocs;
2469   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2470 
2471   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2472 
2473   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2474   // If the stack arguments for this call do not fit into our own save area then
2475   // the call cannot be made tail.
2476   // TODO: Is this really necessary?
2477   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2478     return false;
2479 
2480   const MachineRegisterInfo &MRI = MF.getRegInfo();
2481   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2482 }
2483 
2484 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2485   if (!CI->isTailCall())
2486     return false;
2487 
2488   const Function *ParentFn = CI->getParent()->getParent();
2489   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2490     return false;
2491 
2492   auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2493   return (Attr.getValueAsString() != "true");
2494 }
2495 
2496 // The wave scratch offset register is used as the global base pointer.
2497 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2498                                     SmallVectorImpl<SDValue> &InVals) const {
2499   SelectionDAG &DAG = CLI.DAG;
2500   const SDLoc &DL = CLI.DL;
2501   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2502   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2503   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2504   SDValue Chain = CLI.Chain;
2505   SDValue Callee = CLI.Callee;
2506   bool &IsTailCall = CLI.IsTailCall;
2507   CallingConv::ID CallConv = CLI.CallConv;
2508   bool IsVarArg = CLI.IsVarArg;
2509   bool IsSibCall = false;
2510   bool IsThisReturn = false;
2511   MachineFunction &MF = DAG.getMachineFunction();
2512 
2513   if (IsVarArg) {
2514     return lowerUnhandledCall(CLI, InVals,
2515                               "unsupported call to variadic function ");
2516   }
2517 
2518   if (!CLI.CS.getInstruction())
2519     report_fatal_error("unsupported libcall legalization");
2520 
2521   if (!CLI.CS.getCalledFunction()) {
2522     return lowerUnhandledCall(CLI, InVals,
2523                               "unsupported indirect call to function ");
2524   }
2525 
2526   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2527     return lowerUnhandledCall(CLI, InVals,
2528                               "unsupported required tail call to function ");
2529   }
2530 
2531   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2532     // Note the issue is with the CC of the calling function, not of the call
2533     // itself.
2534     return lowerUnhandledCall(CLI, InVals,
2535                           "unsupported call from graphics shader of function ");
2536   }
2537 
2538   // The first 4 bytes are reserved for the callee's emergency stack slot.
2539   if (IsTailCall) {
2540     IsTailCall = isEligibleForTailCallOptimization(
2541       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2542     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2543       report_fatal_error("failed to perform tail call elimination on a call "
2544                          "site marked musttail");
2545     }
2546 
2547     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2548 
2549     // A sibling call is one where we're under the usual C ABI and not planning
2550     // to change that but can still do a tail call:
2551     if (!TailCallOpt && IsTailCall)
2552       IsSibCall = true;
2553 
2554     if (IsTailCall)
2555       ++NumTailCalls;
2556   }
2557 
2558   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2559 
2560   // Analyze operands of the call, assigning locations to each operand.
2561   SmallVector<CCValAssign, 16> ArgLocs;
2562   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2563   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2564 
2565   // The first 4 bytes are reserved for the callee's emergency stack slot.
2566   CCInfo.AllocateStack(4, 4);
2567 
2568   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2569 
2570   // Get a count of how many bytes are to be pushed on the stack.
2571   unsigned NumBytes = CCInfo.getNextStackOffset();
2572 
2573   if (IsSibCall) {
2574     // Since we're not changing the ABI to make this a tail call, the memory
2575     // operands are already available in the caller's incoming argument space.
2576     NumBytes = 0;
2577   }
2578 
2579   // FPDiff is the byte offset of the call's argument area from the callee's.
2580   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2581   // by this amount for a tail call. In a sibling call it must be 0 because the
2582   // caller will deallocate the entire stack and the callee still expects its
2583   // arguments to begin at SP+0. Completely unused for non-tail calls.
2584   int32_t FPDiff = 0;
2585   MachineFrameInfo &MFI = MF.getFrameInfo();
2586   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2587 
2588   SDValue CallerSavedFP;
2589 
2590   // Adjust the stack pointer for the new arguments...
2591   // These operations are automatically eliminated by the prolog/epilog pass
2592   if (!IsSibCall) {
2593     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2594 
2595     SmallVector<SDValue, 4> CopyFromChains;
2596 
2597     unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2598 
2599     // In the HSA case, this should be an identity copy.
2600     SDValue ScratchRSrcReg
2601       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2602     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2603     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2604 
2605     // TODO: Don't hardcode these registers and get from the callee function.
2606     SDValue ScratchWaveOffsetReg
2607       = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2608     RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2609     CopyFromChains.push_back(ScratchWaveOffsetReg.getValue(1));
2610 
2611     if (!Info->isEntryFunction()) {
2612       // Avoid clobbering this function's FP value. In the current convention
2613       // callee will overwrite this, so do save/restore around the call site.
2614       CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2615                                          Info->getFrameOffsetReg(), MVT::i32);
2616       CopyFromChains.push_back(CallerSavedFP.getValue(1));
2617     }
2618 
2619     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2620   }
2621 
2622   SmallVector<SDValue, 8> MemOpChains;
2623   MVT PtrVT = MVT::i32;
2624 
2625   // Walk the register/memloc assignments, inserting copies/loads.
2626   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2627        ++i, ++realArgIdx) {
2628     CCValAssign &VA = ArgLocs[i];
2629     SDValue Arg = OutVals[realArgIdx];
2630 
2631     // Promote the value if needed.
2632     switch (VA.getLocInfo()) {
2633     case CCValAssign::Full:
2634       break;
2635     case CCValAssign::BCvt:
2636       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2637       break;
2638     case CCValAssign::ZExt:
2639       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2640       break;
2641     case CCValAssign::SExt:
2642       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2643       break;
2644     case CCValAssign::AExt:
2645       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2646       break;
2647     case CCValAssign::FPExt:
2648       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2649       break;
2650     default:
2651       llvm_unreachable("Unknown loc info!");
2652     }
2653 
2654     if (VA.isRegLoc()) {
2655       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2656     } else {
2657       assert(VA.isMemLoc());
2658 
2659       SDValue DstAddr;
2660       MachinePointerInfo DstInfo;
2661 
2662       unsigned LocMemOffset = VA.getLocMemOffset();
2663       int32_t Offset = LocMemOffset;
2664 
2665       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2666       unsigned Align = 0;
2667 
2668       if (IsTailCall) {
2669         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2670         unsigned OpSize = Flags.isByVal() ?
2671           Flags.getByValSize() : VA.getValVT().getStoreSize();
2672 
2673         // FIXME: We can have better than the minimum byval required alignment.
2674         Align = Flags.isByVal() ? Flags.getByValAlign() :
2675           MinAlign(Subtarget->getStackAlignment(), Offset);
2676 
2677         Offset = Offset + FPDiff;
2678         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2679 
2680         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2681         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2682 
2683         // Make sure any stack arguments overlapping with where we're storing
2684         // are loaded before this eventual operation. Otherwise they'll be
2685         // clobbered.
2686 
2687         // FIXME: Why is this really necessary? This seems to just result in a
2688         // lot of code to copy the stack and write them back to the same
2689         // locations, which are supposed to be immutable?
2690         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2691       } else {
2692         DstAddr = PtrOff;
2693         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2694         Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset);
2695       }
2696 
2697       if (Outs[i].Flags.isByVal()) {
2698         SDValue SizeNode =
2699             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2700         SDValue Cpy = DAG.getMemcpy(
2701             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2702             /*isVol = */ false, /*AlwaysInline = */ true,
2703             /*isTailCall = */ false, DstInfo,
2704             MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2705                 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
2706 
2707         MemOpChains.push_back(Cpy);
2708       } else {
2709         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align);
2710         MemOpChains.push_back(Store);
2711       }
2712     }
2713   }
2714 
2715   // Copy special input registers after user input arguments.
2716   passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2717 
2718   if (!MemOpChains.empty())
2719     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2720 
2721   // Build a sequence of copy-to-reg nodes chained together with token chain
2722   // and flag operands which copy the outgoing args into the appropriate regs.
2723   SDValue InFlag;
2724   for (auto &RegToPass : RegsToPass) {
2725     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2726                              RegToPass.second, InFlag);
2727     InFlag = Chain.getValue(1);
2728   }
2729 
2730 
2731   SDValue PhysReturnAddrReg;
2732   if (IsTailCall) {
2733     // Since the return is being combined with the call, we need to pass on the
2734     // return address.
2735 
2736     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2737     SDValue ReturnAddrReg = CreateLiveInRegister(
2738       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2739 
2740     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2741                                         MVT::i64);
2742     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2743     InFlag = Chain.getValue(1);
2744   }
2745 
2746   // We don't usually want to end the call-sequence here because we would tidy
2747   // the frame up *after* the call, however in the ABI-changing tail-call case
2748   // we've carefully laid out the parameters so that when sp is reset they'll be
2749   // in the correct location.
2750   if (IsTailCall && !IsSibCall) {
2751     Chain = DAG.getCALLSEQ_END(Chain,
2752                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2753                                DAG.getTargetConstant(0, DL, MVT::i32),
2754                                InFlag, DL);
2755     InFlag = Chain.getValue(1);
2756   }
2757 
2758   std::vector<SDValue> Ops;
2759   Ops.push_back(Chain);
2760   Ops.push_back(Callee);
2761   // Add a redundant copy of the callee global which will not be legalized, as
2762   // we need direct access to the callee later.
2763   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2764   const GlobalValue *GV = GSD->getGlobal();
2765   Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2766 
2767   if (IsTailCall) {
2768     // Each tail call may have to adjust the stack by a different amount, so
2769     // this information must travel along with the operation for eventual
2770     // consumption by emitEpilogue.
2771     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2772 
2773     Ops.push_back(PhysReturnAddrReg);
2774   }
2775 
2776   // Add argument registers to the end of the list so that they are known live
2777   // into the call.
2778   for (auto &RegToPass : RegsToPass) {
2779     Ops.push_back(DAG.getRegister(RegToPass.first,
2780                                   RegToPass.second.getValueType()));
2781   }
2782 
2783   // Add a register mask operand representing the call-preserved registers.
2784 
2785   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2786   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2787   assert(Mask && "Missing call preserved mask for calling convention");
2788   Ops.push_back(DAG.getRegisterMask(Mask));
2789 
2790   if (InFlag.getNode())
2791     Ops.push_back(InFlag);
2792 
2793   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2794 
2795   // If we're doing a tall call, use a TC_RETURN here rather than an
2796   // actual call instruction.
2797   if (IsTailCall) {
2798     MFI.setHasTailCall();
2799     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2800   }
2801 
2802   // Returns a chain and a flag for retval copy to use.
2803   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2804   Chain = Call.getValue(0);
2805   InFlag = Call.getValue(1);
2806 
2807   if (CallerSavedFP) {
2808     SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2809     Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2810     InFlag = Chain.getValue(1);
2811   }
2812 
2813   uint64_t CalleePopBytes = NumBytes;
2814   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2815                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2816                              InFlag, DL);
2817   if (!Ins.empty())
2818     InFlag = Chain.getValue(1);
2819 
2820   // Handle result values, copying them out of physregs into vregs that we
2821   // return.
2822   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2823                          InVals, IsThisReturn,
2824                          IsThisReturn ? OutVals[0] : SDValue());
2825 }
2826 
2827 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2828                                              SelectionDAG &DAG) const {
2829   unsigned Reg = StringSwitch<unsigned>(RegName)
2830     .Case("m0", AMDGPU::M0)
2831     .Case("exec", AMDGPU::EXEC)
2832     .Case("exec_lo", AMDGPU::EXEC_LO)
2833     .Case("exec_hi", AMDGPU::EXEC_HI)
2834     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2835     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2836     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2837     .Default(AMDGPU::NoRegister);
2838 
2839   if (Reg == AMDGPU::NoRegister) {
2840     report_fatal_error(Twine("invalid register name \""
2841                              + StringRef(RegName)  + "\"."));
2842 
2843   }
2844 
2845   if ((Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS ||
2846        Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) &&
2847        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2848     report_fatal_error(Twine("invalid register \""
2849                              + StringRef(RegName)  + "\" for subtarget."));
2850   }
2851 
2852   switch (Reg) {
2853   case AMDGPU::M0:
2854   case AMDGPU::EXEC_LO:
2855   case AMDGPU::EXEC_HI:
2856   case AMDGPU::FLAT_SCR_LO:
2857   case AMDGPU::FLAT_SCR_HI:
2858     if (VT.getSizeInBits() == 32)
2859       return Reg;
2860     break;
2861   case AMDGPU::EXEC:
2862   case AMDGPU::FLAT_SCR:
2863     if (VT.getSizeInBits() == 64)
2864       return Reg;
2865     break;
2866   default:
2867     llvm_unreachable("missing register type checking");
2868   }
2869 
2870   report_fatal_error(Twine("invalid type for register \""
2871                            + StringRef(RegName) + "\"."));
2872 }
2873 
2874 // If kill is not the last instruction, split the block so kill is always a
2875 // proper terminator.
2876 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2877                                                     MachineBasicBlock *BB) const {
2878   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2879 
2880   MachineBasicBlock::iterator SplitPoint(&MI);
2881   ++SplitPoint;
2882 
2883   if (SplitPoint == BB->end()) {
2884     // Don't bother with a new block.
2885     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2886     return BB;
2887   }
2888 
2889   MachineFunction *MF = BB->getParent();
2890   MachineBasicBlock *SplitBB
2891     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2892 
2893   MF->insert(++MachineFunction::iterator(BB), SplitBB);
2894   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2895 
2896   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2897   BB->addSuccessor(SplitBB);
2898 
2899   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2900   return SplitBB;
2901 }
2902 
2903 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2904 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2905 // will only do one iteration. In the worst case, this will loop 64 times.
2906 //
2907 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2908 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2909   const SIInstrInfo *TII,
2910   MachineRegisterInfo &MRI,
2911   MachineBasicBlock &OrigBB,
2912   MachineBasicBlock &LoopBB,
2913   const DebugLoc &DL,
2914   const MachineOperand &IdxReg,
2915   unsigned InitReg,
2916   unsigned ResultReg,
2917   unsigned PhiReg,
2918   unsigned InitSaveExecReg,
2919   int Offset,
2920   bool UseGPRIdxMode,
2921   bool IsIndirectSrc) {
2922   MachineBasicBlock::iterator I = LoopBB.begin();
2923 
2924   unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2925   unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2926   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2927   unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2928 
2929   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2930     .addReg(InitReg)
2931     .addMBB(&OrigBB)
2932     .addReg(ResultReg)
2933     .addMBB(&LoopBB);
2934 
2935   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2936     .addReg(InitSaveExecReg)
2937     .addMBB(&OrigBB)
2938     .addReg(NewExec)
2939     .addMBB(&LoopBB);
2940 
2941   // Read the next variant <- also loop target.
2942   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2943     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2944 
2945   // Compare the just read M0 value to all possible Idx values.
2946   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2947     .addReg(CurrentIdxReg)
2948     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2949 
2950   // Update EXEC, save the original EXEC value to VCC.
2951   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2952     .addReg(CondReg, RegState::Kill);
2953 
2954   MRI.setSimpleHint(NewExec, CondReg);
2955 
2956   if (UseGPRIdxMode) {
2957     unsigned IdxReg;
2958     if (Offset == 0) {
2959       IdxReg = CurrentIdxReg;
2960     } else {
2961       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2962       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2963         .addReg(CurrentIdxReg, RegState::Kill)
2964         .addImm(Offset);
2965     }
2966     unsigned IdxMode = IsIndirectSrc ?
2967       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
2968     MachineInstr *SetOn =
2969       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2970       .addReg(IdxReg, RegState::Kill)
2971       .addImm(IdxMode);
2972     SetOn->getOperand(3).setIsUndef();
2973   } else {
2974     // Move index from VCC into M0
2975     if (Offset == 0) {
2976       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2977         .addReg(CurrentIdxReg, RegState::Kill);
2978     } else {
2979       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2980         .addReg(CurrentIdxReg, RegState::Kill)
2981         .addImm(Offset);
2982     }
2983   }
2984 
2985   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2986   MachineInstr *InsertPt =
2987     BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64_term), AMDGPU::EXEC)
2988     .addReg(AMDGPU::EXEC)
2989     .addReg(NewExec);
2990 
2991   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2992   // s_cbranch_scc0?
2993 
2994   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2995   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2996     .addMBB(&LoopBB);
2997 
2998   return InsertPt->getIterator();
2999 }
3000 
3001 // This has slightly sub-optimal regalloc when the source vector is killed by
3002 // the read. The register allocator does not understand that the kill is
3003 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3004 // subregister from it, using 1 more VGPR than necessary. This was saved when
3005 // this was expanded after register allocation.
3006 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3007                                                   MachineBasicBlock &MBB,
3008                                                   MachineInstr &MI,
3009                                                   unsigned InitResultReg,
3010                                                   unsigned PhiReg,
3011                                                   int Offset,
3012                                                   bool UseGPRIdxMode,
3013                                                   bool IsIndirectSrc) {
3014   MachineFunction *MF = MBB.getParent();
3015   MachineRegisterInfo &MRI = MF->getRegInfo();
3016   const DebugLoc &DL = MI.getDebugLoc();
3017   MachineBasicBlock::iterator I(&MI);
3018 
3019   unsigned DstReg = MI.getOperand(0).getReg();
3020   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3021   unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3022 
3023   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3024 
3025   // Save the EXEC mask
3026   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
3027     .addReg(AMDGPU::EXEC);
3028 
3029   // To insert the loop we need to split the block. Move everything after this
3030   // point to a new block, and insert a new empty block between the two.
3031   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3032   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3033   MachineFunction::iterator MBBI(MBB);
3034   ++MBBI;
3035 
3036   MF->insert(MBBI, LoopBB);
3037   MF->insert(MBBI, RemainderBB);
3038 
3039   LoopBB->addSuccessor(LoopBB);
3040   LoopBB->addSuccessor(RemainderBB);
3041 
3042   // Move the rest of the block into a new block.
3043   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3044   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3045 
3046   MBB.addSuccessor(LoopBB);
3047 
3048   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3049 
3050   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3051                                       InitResultReg, DstReg, PhiReg, TmpExec,
3052                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3053 
3054   MachineBasicBlock::iterator First = RemainderBB->begin();
3055   BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
3056     .addReg(SaveExec);
3057 
3058   return InsPt;
3059 }
3060 
3061 // Returns subreg index, offset
3062 static std::pair<unsigned, int>
3063 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3064                             const TargetRegisterClass *SuperRC,
3065                             unsigned VecReg,
3066                             int Offset) {
3067   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3068 
3069   // Skip out of bounds offsets, or else we would end up using an undefined
3070   // register.
3071   if (Offset >= NumElts || Offset < 0)
3072     return std::make_pair(AMDGPU::sub0, Offset);
3073 
3074   return std::make_pair(AMDGPU::sub0 + Offset, 0);
3075 }
3076 
3077 // Return true if the index is an SGPR and was set.
3078 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3079                                  MachineRegisterInfo &MRI,
3080                                  MachineInstr &MI,
3081                                  int Offset,
3082                                  bool UseGPRIdxMode,
3083                                  bool IsIndirectSrc) {
3084   MachineBasicBlock *MBB = MI.getParent();
3085   const DebugLoc &DL = MI.getDebugLoc();
3086   MachineBasicBlock::iterator I(&MI);
3087 
3088   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3089   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3090 
3091   assert(Idx->getReg() != AMDGPU::NoRegister);
3092 
3093   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3094     return false;
3095 
3096   if (UseGPRIdxMode) {
3097     unsigned IdxMode = IsIndirectSrc ?
3098       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3099     if (Offset == 0) {
3100       MachineInstr *SetOn =
3101           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3102               .add(*Idx)
3103               .addImm(IdxMode);
3104 
3105       SetOn->getOperand(3).setIsUndef();
3106     } else {
3107       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3108       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3109           .add(*Idx)
3110           .addImm(Offset);
3111       MachineInstr *SetOn =
3112         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3113         .addReg(Tmp, RegState::Kill)
3114         .addImm(IdxMode);
3115 
3116       SetOn->getOperand(3).setIsUndef();
3117     }
3118 
3119     return true;
3120   }
3121 
3122   if (Offset == 0) {
3123     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3124       .add(*Idx);
3125   } else {
3126     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3127       .add(*Idx)
3128       .addImm(Offset);
3129   }
3130 
3131   return true;
3132 }
3133 
3134 // Control flow needs to be inserted if indexing with a VGPR.
3135 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3136                                           MachineBasicBlock &MBB,
3137                                           const GCNSubtarget &ST) {
3138   const SIInstrInfo *TII = ST.getInstrInfo();
3139   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3140   MachineFunction *MF = MBB.getParent();
3141   MachineRegisterInfo &MRI = MF->getRegInfo();
3142 
3143   unsigned Dst = MI.getOperand(0).getReg();
3144   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3145   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3146 
3147   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3148 
3149   unsigned SubReg;
3150   std::tie(SubReg, Offset)
3151     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3152 
3153   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3154 
3155   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3156     MachineBasicBlock::iterator I(&MI);
3157     const DebugLoc &DL = MI.getDebugLoc();
3158 
3159     if (UseGPRIdxMode) {
3160       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3161       // to avoid interfering with other uses, so probably requires a new
3162       // optimization pass.
3163       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3164         .addReg(SrcReg, RegState::Undef, SubReg)
3165         .addReg(SrcReg, RegState::Implicit)
3166         .addReg(AMDGPU::M0, RegState::Implicit);
3167       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3168     } else {
3169       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3170         .addReg(SrcReg, RegState::Undef, SubReg)
3171         .addReg(SrcReg, RegState::Implicit);
3172     }
3173 
3174     MI.eraseFromParent();
3175 
3176     return &MBB;
3177   }
3178 
3179   const DebugLoc &DL = MI.getDebugLoc();
3180   MachineBasicBlock::iterator I(&MI);
3181 
3182   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3183   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3184 
3185   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3186 
3187   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3188                               Offset, UseGPRIdxMode, true);
3189   MachineBasicBlock *LoopBB = InsPt->getParent();
3190 
3191   if (UseGPRIdxMode) {
3192     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3193       .addReg(SrcReg, RegState::Undef, SubReg)
3194       .addReg(SrcReg, RegState::Implicit)
3195       .addReg(AMDGPU::M0, RegState::Implicit);
3196     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3197   } else {
3198     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3199       .addReg(SrcReg, RegState::Undef, SubReg)
3200       .addReg(SrcReg, RegState::Implicit);
3201   }
3202 
3203   MI.eraseFromParent();
3204 
3205   return LoopBB;
3206 }
3207 
3208 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3209                                  const TargetRegisterClass *VecRC) {
3210   switch (TRI.getRegSizeInBits(*VecRC)) {
3211   case 32: // 4 bytes
3212     return AMDGPU::V_MOVRELD_B32_V1;
3213   case 64: // 8 bytes
3214     return AMDGPU::V_MOVRELD_B32_V2;
3215   case 128: // 16 bytes
3216     return AMDGPU::V_MOVRELD_B32_V4;
3217   case 256: // 32 bytes
3218     return AMDGPU::V_MOVRELD_B32_V8;
3219   case 512: // 64 bytes
3220     return AMDGPU::V_MOVRELD_B32_V16;
3221   default:
3222     llvm_unreachable("unsupported size for MOVRELD pseudos");
3223   }
3224 }
3225 
3226 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3227                                           MachineBasicBlock &MBB,
3228                                           const GCNSubtarget &ST) {
3229   const SIInstrInfo *TII = ST.getInstrInfo();
3230   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3231   MachineFunction *MF = MBB.getParent();
3232   MachineRegisterInfo &MRI = MF->getRegInfo();
3233 
3234   unsigned Dst = MI.getOperand(0).getReg();
3235   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3236   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3237   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3238   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3239   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3240 
3241   // This can be an immediate, but will be folded later.
3242   assert(Val->getReg());
3243 
3244   unsigned SubReg;
3245   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3246                                                          SrcVec->getReg(),
3247                                                          Offset);
3248   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3249 
3250   if (Idx->getReg() == AMDGPU::NoRegister) {
3251     MachineBasicBlock::iterator I(&MI);
3252     const DebugLoc &DL = MI.getDebugLoc();
3253 
3254     assert(Offset == 0);
3255 
3256     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3257         .add(*SrcVec)
3258         .add(*Val)
3259         .addImm(SubReg);
3260 
3261     MI.eraseFromParent();
3262     return &MBB;
3263   }
3264 
3265   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3266     MachineBasicBlock::iterator I(&MI);
3267     const DebugLoc &DL = MI.getDebugLoc();
3268 
3269     if (UseGPRIdxMode) {
3270       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3271           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3272           .add(*Val)
3273           .addReg(Dst, RegState::ImplicitDefine)
3274           .addReg(SrcVec->getReg(), RegState::Implicit)
3275           .addReg(AMDGPU::M0, RegState::Implicit);
3276 
3277       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3278     } else {
3279       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3280 
3281       BuildMI(MBB, I, DL, MovRelDesc)
3282           .addReg(Dst, RegState::Define)
3283           .addReg(SrcVec->getReg())
3284           .add(*Val)
3285           .addImm(SubReg - AMDGPU::sub0);
3286     }
3287 
3288     MI.eraseFromParent();
3289     return &MBB;
3290   }
3291 
3292   if (Val->isReg())
3293     MRI.clearKillFlags(Val->getReg());
3294 
3295   const DebugLoc &DL = MI.getDebugLoc();
3296 
3297   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3298 
3299   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3300                               Offset, UseGPRIdxMode, false);
3301   MachineBasicBlock *LoopBB = InsPt->getParent();
3302 
3303   if (UseGPRIdxMode) {
3304     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3305         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3306         .add(*Val)                               // src0
3307         .addReg(Dst, RegState::ImplicitDefine)
3308         .addReg(PhiReg, RegState::Implicit)
3309         .addReg(AMDGPU::M0, RegState::Implicit);
3310     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3311   } else {
3312     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3313 
3314     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3315         .addReg(Dst, RegState::Define)
3316         .addReg(PhiReg)
3317         .add(*Val)
3318         .addImm(SubReg - AMDGPU::sub0);
3319   }
3320 
3321   MI.eraseFromParent();
3322 
3323   return LoopBB;
3324 }
3325 
3326 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3327   MachineInstr &MI, MachineBasicBlock *BB) const {
3328 
3329   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3330   MachineFunction *MF = BB->getParent();
3331   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3332 
3333   if (TII->isMIMG(MI)) {
3334     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3335       report_fatal_error("missing mem operand from MIMG instruction");
3336     }
3337     // Add a memoperand for mimg instructions so that they aren't assumed to
3338     // be ordered memory instuctions.
3339 
3340     return BB;
3341   }
3342 
3343   switch (MI.getOpcode()) {
3344   case AMDGPU::S_ADD_U64_PSEUDO:
3345   case AMDGPU::S_SUB_U64_PSEUDO: {
3346     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3347     const DebugLoc &DL = MI.getDebugLoc();
3348 
3349     MachineOperand &Dest = MI.getOperand(0);
3350     MachineOperand &Src0 = MI.getOperand(1);
3351     MachineOperand &Src1 = MI.getOperand(2);
3352 
3353     unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3354     unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3355 
3356     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3357      Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3358      &AMDGPU::SReg_32_XM0RegClass);
3359     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3360       Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3361       &AMDGPU::SReg_32_XM0RegClass);
3362 
3363     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3364       Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3365       &AMDGPU::SReg_32_XM0RegClass);
3366     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3367       Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3368       &AMDGPU::SReg_32_XM0RegClass);
3369 
3370     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3371 
3372     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3373     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3374     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3375       .add(Src0Sub0)
3376       .add(Src1Sub0);
3377     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3378       .add(Src0Sub1)
3379       .add(Src1Sub1);
3380     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3381       .addReg(DestSub0)
3382       .addImm(AMDGPU::sub0)
3383       .addReg(DestSub1)
3384       .addImm(AMDGPU::sub1);
3385     MI.eraseFromParent();
3386     return BB;
3387   }
3388   case AMDGPU::SI_INIT_M0: {
3389     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3390             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3391         .add(MI.getOperand(0));
3392     MI.eraseFromParent();
3393     return BB;
3394   }
3395   case AMDGPU::SI_INIT_EXEC:
3396     // This should be before all vector instructions.
3397     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3398             AMDGPU::EXEC)
3399         .addImm(MI.getOperand(0).getImm());
3400     MI.eraseFromParent();
3401     return BB;
3402 
3403   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3404     // Extract the thread count from an SGPR input and set EXEC accordingly.
3405     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3406     //
3407     // S_BFE_U32 count, input, {shift, 7}
3408     // S_BFM_B64 exec, count, 0
3409     // S_CMP_EQ_U32 count, 64
3410     // S_CMOV_B64 exec, -1
3411     MachineInstr *FirstMI = &*BB->begin();
3412     MachineRegisterInfo &MRI = MF->getRegInfo();
3413     unsigned InputReg = MI.getOperand(0).getReg();
3414     unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3415     bool Found = false;
3416 
3417     // Move the COPY of the input reg to the beginning, so that we can use it.
3418     for (auto I = BB->begin(); I != &MI; I++) {
3419       if (I->getOpcode() != TargetOpcode::COPY ||
3420           I->getOperand(0).getReg() != InputReg)
3421         continue;
3422 
3423       if (I == FirstMI) {
3424         FirstMI = &*++BB->begin();
3425       } else {
3426         I->removeFromParent();
3427         BB->insert(FirstMI, &*I);
3428       }
3429       Found = true;
3430       break;
3431     }
3432     assert(Found);
3433     (void)Found;
3434 
3435     // This should be before all vector instructions.
3436     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3437         .addReg(InputReg)
3438         .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3439     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3440             AMDGPU::EXEC)
3441         .addReg(CountReg)
3442         .addImm(0);
3443     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3444         .addReg(CountReg, RegState::Kill)
3445         .addImm(64);
3446     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3447             AMDGPU::EXEC)
3448         .addImm(-1);
3449     MI.eraseFromParent();
3450     return BB;
3451   }
3452 
3453   case AMDGPU::GET_GROUPSTATICSIZE: {
3454     DebugLoc DL = MI.getDebugLoc();
3455     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3456         .add(MI.getOperand(0))
3457         .addImm(MFI->getLDSSize());
3458     MI.eraseFromParent();
3459     return BB;
3460   }
3461   case AMDGPU::SI_INDIRECT_SRC_V1:
3462   case AMDGPU::SI_INDIRECT_SRC_V2:
3463   case AMDGPU::SI_INDIRECT_SRC_V4:
3464   case AMDGPU::SI_INDIRECT_SRC_V8:
3465   case AMDGPU::SI_INDIRECT_SRC_V16:
3466     return emitIndirectSrc(MI, *BB, *getSubtarget());
3467   case AMDGPU::SI_INDIRECT_DST_V1:
3468   case AMDGPU::SI_INDIRECT_DST_V2:
3469   case AMDGPU::SI_INDIRECT_DST_V4:
3470   case AMDGPU::SI_INDIRECT_DST_V8:
3471   case AMDGPU::SI_INDIRECT_DST_V16:
3472     return emitIndirectDst(MI, *BB, *getSubtarget());
3473   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3474   case AMDGPU::SI_KILL_I1_PSEUDO:
3475     return splitKillBlock(MI, BB);
3476   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3477     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3478 
3479     unsigned Dst = MI.getOperand(0).getReg();
3480     unsigned Src0 = MI.getOperand(1).getReg();
3481     unsigned Src1 = MI.getOperand(2).getReg();
3482     const DebugLoc &DL = MI.getDebugLoc();
3483     unsigned SrcCond = MI.getOperand(3).getReg();
3484 
3485     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3486     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3487     unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3488 
3489     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3490       .addReg(SrcCond);
3491     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3492       .addImm(0)
3493       .addReg(Src0, 0, AMDGPU::sub0)
3494       .addImm(0)
3495       .addReg(Src1, 0, AMDGPU::sub0)
3496       .addReg(SrcCondCopy);
3497     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3498       .addImm(0)
3499       .addReg(Src0, 0, AMDGPU::sub1)
3500       .addImm(0)
3501       .addReg(Src1, 0, AMDGPU::sub1)
3502       .addReg(SrcCondCopy);
3503 
3504     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3505       .addReg(DstLo)
3506       .addImm(AMDGPU::sub0)
3507       .addReg(DstHi)
3508       .addImm(AMDGPU::sub1);
3509     MI.eraseFromParent();
3510     return BB;
3511   }
3512   case AMDGPU::SI_BR_UNDEF: {
3513     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3514     const DebugLoc &DL = MI.getDebugLoc();
3515     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3516                            .add(MI.getOperand(0));
3517     Br->getOperand(1).setIsUndef(true); // read undef SCC
3518     MI.eraseFromParent();
3519     return BB;
3520   }
3521   case AMDGPU::ADJCALLSTACKUP:
3522   case AMDGPU::ADJCALLSTACKDOWN: {
3523     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3524     MachineInstrBuilder MIB(*MF, &MI);
3525 
3526     // Add an implicit use of the frame offset reg to prevent the restore copy
3527     // inserted after the call from being reorderd after stack operations in the
3528     // the caller's frame.
3529     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3530         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3531         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3532     return BB;
3533   }
3534   case AMDGPU::SI_CALL_ISEL: {
3535     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3536     const DebugLoc &DL = MI.getDebugLoc();
3537 
3538     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3539 
3540     MachineInstrBuilder MIB;
3541     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3542 
3543     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3544       MIB.add(MI.getOperand(I));
3545 
3546     MIB.cloneMemRefs(MI);
3547     MI.eraseFromParent();
3548     return BB;
3549   }
3550   case AMDGPU::V_ADD_I32_e32:
3551   case AMDGPU::V_SUB_I32_e32:
3552   case AMDGPU::V_SUBREV_I32_e32: {
3553     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3554     const DebugLoc &DL = MI.getDebugLoc();
3555     unsigned Opc = MI.getOpcode();
3556 
3557     bool NeedClampOperand = false;
3558     if (TII->pseudoToMCOpcode(Opc) == -1) {
3559       Opc = AMDGPU::getVOPe64(Opc);
3560       NeedClampOperand = true;
3561     }
3562 
3563     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3564     if (TII->isVOP3(*I)) {
3565       I.addReg(AMDGPU::VCC, RegState::Define);
3566     }
3567     I.add(MI.getOperand(1))
3568      .add(MI.getOperand(2));
3569     if (NeedClampOperand)
3570       I.addImm(0); // clamp bit for e64 encoding
3571 
3572     TII->legalizeOperands(*I);
3573 
3574     MI.eraseFromParent();
3575     return BB;
3576   }
3577   default:
3578     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3579   }
3580 }
3581 
3582 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3583   return isTypeLegal(VT.getScalarType());
3584 }
3585 
3586 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3587   // This currently forces unfolding various combinations of fsub into fma with
3588   // free fneg'd operands. As long as we have fast FMA (controlled by
3589   // isFMAFasterThanFMulAndFAdd), we should perform these.
3590 
3591   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3592   // most of these combines appear to be cycle neutral but save on instruction
3593   // count / code size.
3594   return true;
3595 }
3596 
3597 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3598                                          EVT VT) const {
3599   if (!VT.isVector()) {
3600     return MVT::i1;
3601   }
3602   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3603 }
3604 
3605 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3606   // TODO: Should i16 be used always if legal? For now it would force VALU
3607   // shifts.
3608   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3609 }
3610 
3611 // Answering this is somewhat tricky and depends on the specific device which
3612 // have different rates for fma or all f64 operations.
3613 //
3614 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3615 // regardless of which device (although the number of cycles differs between
3616 // devices), so it is always profitable for f64.
3617 //
3618 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3619 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3620 // which we can always do even without fused FP ops since it returns the same
3621 // result as the separate operations and since it is always full
3622 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3623 // however does not support denormals, so we do report fma as faster if we have
3624 // a fast fma device and require denormals.
3625 //
3626 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3627   VT = VT.getScalarType();
3628 
3629   switch (VT.getSimpleVT().SimpleTy) {
3630   case MVT::f32: {
3631     // This is as fast on some subtargets. However, we always have full rate f32
3632     // mad available which returns the same result as the separate operations
3633     // which we should prefer over fma. We can't use this if we want to support
3634     // denormals, so only report this in these cases.
3635     if (Subtarget->hasFP32Denormals())
3636       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3637 
3638     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3639     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3640   }
3641   case MVT::f64:
3642     return true;
3643   case MVT::f16:
3644     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3645   default:
3646     break;
3647   }
3648 
3649   return false;
3650 }
3651 
3652 //===----------------------------------------------------------------------===//
3653 // Custom DAG Lowering Operations
3654 //===----------------------------------------------------------------------===//
3655 
3656 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3657 // wider vector type is legal.
3658 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3659                                              SelectionDAG &DAG) const {
3660   unsigned Opc = Op.getOpcode();
3661   EVT VT = Op.getValueType();
3662   assert(VT == MVT::v4f16);
3663 
3664   SDValue Lo, Hi;
3665   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3666 
3667   SDLoc SL(Op);
3668   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3669                              Op->getFlags());
3670   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3671                              Op->getFlags());
3672 
3673   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3674 }
3675 
3676 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3677 // wider vector type is legal.
3678 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3679                                               SelectionDAG &DAG) const {
3680   unsigned Opc = Op.getOpcode();
3681   EVT VT = Op.getValueType();
3682   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3683 
3684   SDValue Lo0, Hi0;
3685   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3686   SDValue Lo1, Hi1;
3687   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3688 
3689   SDLoc SL(Op);
3690 
3691   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3692                              Op->getFlags());
3693   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3694                              Op->getFlags());
3695 
3696   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3697 }
3698 
3699 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3700   switch (Op.getOpcode()) {
3701   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3702   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3703   case ISD::LOAD: {
3704     SDValue Result = LowerLOAD(Op, DAG);
3705     assert((!Result.getNode() ||
3706             Result.getNode()->getNumValues() == 2) &&
3707            "Load should return a value and a chain");
3708     return Result;
3709   }
3710 
3711   case ISD::FSIN:
3712   case ISD::FCOS:
3713     return LowerTrig(Op, DAG);
3714   case ISD::SELECT: return LowerSELECT(Op, DAG);
3715   case ISD::FDIV: return LowerFDIV(Op, DAG);
3716   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3717   case ISD::STORE: return LowerSTORE(Op, DAG);
3718   case ISD::GlobalAddress: {
3719     MachineFunction &MF = DAG.getMachineFunction();
3720     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3721     return LowerGlobalAddress(MFI, Op, DAG);
3722   }
3723   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3724   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3725   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3726   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3727   case ISD::INSERT_VECTOR_ELT:
3728     return lowerINSERT_VECTOR_ELT(Op, DAG);
3729   case ISD::EXTRACT_VECTOR_ELT:
3730     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3731   case ISD::BUILD_VECTOR:
3732     return lowerBUILD_VECTOR(Op, DAG);
3733   case ISD::FP_ROUND:
3734     return lowerFP_ROUND(Op, DAG);
3735   case ISD::TRAP:
3736     return lowerTRAP(Op, DAG);
3737   case ISD::DEBUGTRAP:
3738     return lowerDEBUGTRAP(Op, DAG);
3739   case ISD::FABS:
3740   case ISD::FNEG:
3741   case ISD::FCANONICALIZE:
3742     return splitUnaryVectorOp(Op, DAG);
3743   case ISD::FMINNUM:
3744   case ISD::FMAXNUM:
3745     return lowerFMINNUM_FMAXNUM(Op, DAG);
3746   case ISD::SHL:
3747   case ISD::SRA:
3748   case ISD::SRL:
3749   case ISD::ADD:
3750   case ISD::SUB:
3751   case ISD::MUL:
3752   case ISD::SMIN:
3753   case ISD::SMAX:
3754   case ISD::UMIN:
3755   case ISD::UMAX:
3756   case ISD::FADD:
3757   case ISD::FMUL:
3758   case ISD::FMINNUM_IEEE:
3759   case ISD::FMAXNUM_IEEE:
3760     return splitBinaryVectorOp(Op, DAG);
3761   }
3762   return SDValue();
3763 }
3764 
3765 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
3766                                        const SDLoc &DL,
3767                                        SelectionDAG &DAG, bool Unpacked) {
3768   if (!LoadVT.isVector())
3769     return Result;
3770 
3771   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3772     // Truncate to v2i16/v4i16.
3773     EVT IntLoadVT = LoadVT.changeTypeToInteger();
3774 
3775     // Workaround legalizer not scalarizing truncate after vector op
3776     // legalization byt not creating intermediate vector trunc.
3777     SmallVector<SDValue, 4> Elts;
3778     DAG.ExtractVectorElements(Result, Elts);
3779     for (SDValue &Elt : Elts)
3780       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3781 
3782     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3783 
3784     // Bitcast to original type (v2f16/v4f16).
3785     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3786   }
3787 
3788   // Cast back to the original packed type.
3789   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3790 }
3791 
3792 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
3793                                               MemSDNode *M,
3794                                               SelectionDAG &DAG,
3795                                               ArrayRef<SDValue> Ops,
3796                                               bool IsIntrinsic) const {
3797   SDLoc DL(M);
3798 
3799   bool Unpacked = Subtarget->hasUnpackedD16VMem();
3800   EVT LoadVT = M->getValueType(0);
3801 
3802   EVT EquivLoadVT = LoadVT;
3803   if (Unpacked && LoadVT.isVector()) {
3804     EquivLoadVT = LoadVT.isVector() ?
3805       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3806                        LoadVT.getVectorNumElements()) : LoadVT;
3807   }
3808 
3809   // Change from v4f16/v2f16 to EquivLoadVT.
3810   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3811 
3812   SDValue Load
3813     = DAG.getMemIntrinsicNode(
3814       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
3815       VTList, Ops, M->getMemoryVT(),
3816       M->getMemOperand());
3817   if (!Unpacked) // Just adjusted the opcode.
3818     return Load;
3819 
3820   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
3821 
3822   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
3823 }
3824 
3825 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
3826                                   SDNode *N, SelectionDAG &DAG) {
3827   EVT VT = N->getValueType(0);
3828   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
3829   int CondCode = CD->getSExtValue();
3830   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
3831       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
3832     return DAG.getUNDEF(VT);
3833 
3834   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
3835 
3836 
3837   SDValue LHS = N->getOperand(1);
3838   SDValue RHS = N->getOperand(2);
3839 
3840   SDLoc DL(N);
3841 
3842   EVT CmpVT = LHS.getValueType();
3843   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
3844     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
3845       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3846     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
3847     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
3848   }
3849 
3850   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
3851 
3852   return DAG.getNode(AMDGPUISD::SETCC, DL, VT, LHS, RHS,
3853                      DAG.getCondCode(CCOpcode));
3854 }
3855 
3856 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
3857                                   SDNode *N, SelectionDAG &DAG) {
3858   EVT VT = N->getValueType(0);
3859   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
3860 
3861   int CondCode = CD->getSExtValue();
3862   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
3863       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
3864     return DAG.getUNDEF(VT);
3865   }
3866 
3867   SDValue Src0 = N->getOperand(1);
3868   SDValue Src1 = N->getOperand(2);
3869   EVT CmpVT = Src0.getValueType();
3870   SDLoc SL(N);
3871 
3872   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
3873     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3874     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3875   }
3876 
3877   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
3878   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
3879   return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src0,
3880                      Src1, DAG.getCondCode(CCOpcode));
3881 }
3882 
3883 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3884                                           SmallVectorImpl<SDValue> &Results,
3885                                           SelectionDAG &DAG) const {
3886   switch (N->getOpcode()) {
3887   case ISD::INSERT_VECTOR_ELT: {
3888     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3889       Results.push_back(Res);
3890     return;
3891   }
3892   case ISD::EXTRACT_VECTOR_ELT: {
3893     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3894       Results.push_back(Res);
3895     return;
3896   }
3897   case ISD::INTRINSIC_WO_CHAIN: {
3898     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3899     switch (IID) {
3900     case Intrinsic::amdgcn_cvt_pkrtz: {
3901       SDValue Src0 = N->getOperand(1);
3902       SDValue Src1 = N->getOperand(2);
3903       SDLoc SL(N);
3904       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3905                                 Src0, Src1);
3906       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3907       return;
3908     }
3909     case Intrinsic::amdgcn_cvt_pknorm_i16:
3910     case Intrinsic::amdgcn_cvt_pknorm_u16:
3911     case Intrinsic::amdgcn_cvt_pk_i16:
3912     case Intrinsic::amdgcn_cvt_pk_u16: {
3913       SDValue Src0 = N->getOperand(1);
3914       SDValue Src1 = N->getOperand(2);
3915       SDLoc SL(N);
3916       unsigned Opcode;
3917 
3918       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3919         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
3920       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3921         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
3922       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3923         Opcode = AMDGPUISD::CVT_PK_I16_I32;
3924       else
3925         Opcode = AMDGPUISD::CVT_PK_U16_U32;
3926 
3927       EVT VT = N->getValueType(0);
3928       if (isTypeLegal(VT))
3929         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
3930       else {
3931         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
3932         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
3933       }
3934       return;
3935     }
3936     }
3937     break;
3938   }
3939   case ISD::INTRINSIC_W_CHAIN: {
3940     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
3941       Results.push_back(Res);
3942       Results.push_back(Res.getValue(1));
3943       return;
3944     }
3945 
3946     break;
3947   }
3948   case ISD::SELECT: {
3949     SDLoc SL(N);
3950     EVT VT = N->getValueType(0);
3951     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3952     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3953     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3954 
3955     EVT SelectVT = NewVT;
3956     if (NewVT.bitsLT(MVT::i32)) {
3957       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3958       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3959       SelectVT = MVT::i32;
3960     }
3961 
3962     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3963                                     N->getOperand(0), LHS, RHS);
3964 
3965     if (NewVT != SelectVT)
3966       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3967     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3968     return;
3969   }
3970   case ISD::FNEG: {
3971     if (N->getValueType(0) != MVT::v2f16)
3972       break;
3973 
3974     SDLoc SL(N);
3975     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3976 
3977     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
3978                              BC,
3979                              DAG.getConstant(0x80008000, SL, MVT::i32));
3980     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3981     return;
3982   }
3983   case ISD::FABS: {
3984     if (N->getValueType(0) != MVT::v2f16)
3985       break;
3986 
3987     SDLoc SL(N);
3988     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3989 
3990     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
3991                              BC,
3992                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
3993     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3994     return;
3995   }
3996   default:
3997     break;
3998   }
3999 }
4000 
4001 /// Helper function for LowerBRCOND
4002 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4003 
4004   SDNode *Parent = Value.getNode();
4005   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4006        I != E; ++I) {
4007 
4008     if (I.getUse().get() != Value)
4009       continue;
4010 
4011     if (I->getOpcode() == Opcode)
4012       return *I;
4013   }
4014   return nullptr;
4015 }
4016 
4017 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4018   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4019     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4020     case Intrinsic::amdgcn_if:
4021       return AMDGPUISD::IF;
4022     case Intrinsic::amdgcn_else:
4023       return AMDGPUISD::ELSE;
4024     case Intrinsic::amdgcn_loop:
4025       return AMDGPUISD::LOOP;
4026     case Intrinsic::amdgcn_end_cf:
4027       llvm_unreachable("should not occur");
4028     default:
4029       return 0;
4030     }
4031   }
4032 
4033   // break, if_break, else_break are all only used as inputs to loop, not
4034   // directly as branch conditions.
4035   return 0;
4036 }
4037 
4038 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4039   const Triple &TT = getTargetMachine().getTargetTriple();
4040   return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4041           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4042          AMDGPU::shouldEmitConstantsToTextSection(TT);
4043 }
4044 
4045 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4046   // FIXME: Either avoid relying on address space here or change the default
4047   // address space for functions to avoid the explicit check.
4048   return (GV->getValueType()->isFunctionTy() ||
4049           GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4050           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4051           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4052          !shouldEmitFixup(GV) &&
4053          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4054 }
4055 
4056 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4057   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4058 }
4059 
4060 /// This transforms the control flow intrinsics to get the branch destination as
4061 /// last parameter, also switches branch target with BR if the need arise
4062 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4063                                       SelectionDAG &DAG) const {
4064   SDLoc DL(BRCOND);
4065 
4066   SDNode *Intr = BRCOND.getOperand(1).getNode();
4067   SDValue Target = BRCOND.getOperand(2);
4068   SDNode *BR = nullptr;
4069   SDNode *SetCC = nullptr;
4070 
4071   if (Intr->getOpcode() == ISD::SETCC) {
4072     // As long as we negate the condition everything is fine
4073     SetCC = Intr;
4074     Intr = SetCC->getOperand(0).getNode();
4075 
4076   } else {
4077     // Get the target from BR if we don't negate the condition
4078     BR = findUser(BRCOND, ISD::BR);
4079     Target = BR->getOperand(1);
4080   }
4081 
4082   // FIXME: This changes the types of the intrinsics instead of introducing new
4083   // nodes with the correct types.
4084   // e.g. llvm.amdgcn.loop
4085 
4086   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4087   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4088 
4089   unsigned CFNode = isCFIntrinsic(Intr);
4090   if (CFNode == 0) {
4091     // This is a uniform branch so we don't need to legalize.
4092     return BRCOND;
4093   }
4094 
4095   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4096                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4097 
4098   assert(!SetCC ||
4099         (SetCC->getConstantOperandVal(1) == 1 &&
4100          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4101                                                              ISD::SETNE));
4102 
4103   // operands of the new intrinsic call
4104   SmallVector<SDValue, 4> Ops;
4105   if (HaveChain)
4106     Ops.push_back(BRCOND.getOperand(0));
4107 
4108   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4109   Ops.push_back(Target);
4110 
4111   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4112 
4113   // build the new intrinsic call
4114   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4115 
4116   if (!HaveChain) {
4117     SDValue Ops[] =  {
4118       SDValue(Result, 0),
4119       BRCOND.getOperand(0)
4120     };
4121 
4122     Result = DAG.getMergeValues(Ops, DL).getNode();
4123   }
4124 
4125   if (BR) {
4126     // Give the branch instruction our target
4127     SDValue Ops[] = {
4128       BR->getOperand(0),
4129       BRCOND.getOperand(2)
4130     };
4131     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4132     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4133     BR = NewBR.getNode();
4134   }
4135 
4136   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4137 
4138   // Copy the intrinsic results to registers
4139   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4140     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4141     if (!CopyToReg)
4142       continue;
4143 
4144     Chain = DAG.getCopyToReg(
4145       Chain, DL,
4146       CopyToReg->getOperand(1),
4147       SDValue(Result, i - 1),
4148       SDValue());
4149 
4150     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4151   }
4152 
4153   // Remove the old intrinsic from the chain
4154   DAG.ReplaceAllUsesOfValueWith(
4155     SDValue(Intr, Intr->getNumValues() - 1),
4156     Intr->getOperand(0));
4157 
4158   return Chain;
4159 }
4160 
4161 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4162                                             SDValue Op,
4163                                             const SDLoc &DL,
4164                                             EVT VT) const {
4165   return Op.getValueType().bitsLE(VT) ?
4166       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4167       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4168 }
4169 
4170 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4171   assert(Op.getValueType() == MVT::f16 &&
4172          "Do not know how to custom lower FP_ROUND for non-f16 type");
4173 
4174   SDValue Src = Op.getOperand(0);
4175   EVT SrcVT = Src.getValueType();
4176   if (SrcVT != MVT::f64)
4177     return Op;
4178 
4179   SDLoc DL(Op);
4180 
4181   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4182   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4183   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4184 }
4185 
4186 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4187                                                SelectionDAG &DAG) const {
4188   EVT VT = Op.getValueType();
4189   const MachineFunction &MF = DAG.getMachineFunction();
4190   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4191   bool IsIEEEMode = Info->getMode().IEEE;
4192 
4193   // FIXME: Assert during eslection that this is only selected for
4194   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4195   // mode functions, but this happens to be OK since it's only done in cases
4196   // where there is known no sNaN.
4197   if (IsIEEEMode)
4198     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4199 
4200   if (VT == MVT::v4f16)
4201     return splitBinaryVectorOp(Op, DAG);
4202   return Op;
4203 }
4204 
4205 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4206   SDLoc SL(Op);
4207   SDValue Chain = Op.getOperand(0);
4208 
4209   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4210       !Subtarget->isTrapHandlerEnabled())
4211     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4212 
4213   MachineFunction &MF = DAG.getMachineFunction();
4214   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4215   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4216   assert(UserSGPR != AMDGPU::NoRegister);
4217   SDValue QueuePtr = CreateLiveInRegister(
4218     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4219   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4220   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4221                                    QueuePtr, SDValue());
4222   SDValue Ops[] = {
4223     ToReg,
4224     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4225     SGPR01,
4226     ToReg.getValue(1)
4227   };
4228   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4229 }
4230 
4231 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4232   SDLoc SL(Op);
4233   SDValue Chain = Op.getOperand(0);
4234   MachineFunction &MF = DAG.getMachineFunction();
4235 
4236   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4237       !Subtarget->isTrapHandlerEnabled()) {
4238     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4239                                      "debugtrap handler not supported",
4240                                      Op.getDebugLoc(),
4241                                      DS_Warning);
4242     LLVMContext &Ctx = MF.getFunction().getContext();
4243     Ctx.diagnose(NoTrap);
4244     return Chain;
4245   }
4246 
4247   SDValue Ops[] = {
4248     Chain,
4249     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4250   };
4251   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4252 }
4253 
4254 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4255                                              SelectionDAG &DAG) const {
4256   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4257   if (Subtarget->hasApertureRegs()) {
4258     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4259         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4260         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4261     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4262         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4263         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4264     unsigned Encoding =
4265         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4266         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4267         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4268 
4269     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4270     SDValue ApertureReg = SDValue(
4271         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4272     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4273     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4274   }
4275 
4276   MachineFunction &MF = DAG.getMachineFunction();
4277   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4278   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4279   assert(UserSGPR != AMDGPU::NoRegister);
4280 
4281   SDValue QueuePtr = CreateLiveInRegister(
4282     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4283 
4284   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4285   // private_segment_aperture_base_hi.
4286   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4287 
4288   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4289 
4290   // TODO: Use custom target PseudoSourceValue.
4291   // TODO: We should use the value from the IR intrinsic call, but it might not
4292   // be available and how do we get it?
4293   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4294                                               AMDGPUAS::CONSTANT_ADDRESS));
4295 
4296   MachinePointerInfo PtrInfo(V, StructOffset);
4297   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4298                      MinAlign(64, StructOffset),
4299                      MachineMemOperand::MODereferenceable |
4300                          MachineMemOperand::MOInvariant);
4301 }
4302 
4303 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4304                                              SelectionDAG &DAG) const {
4305   SDLoc SL(Op);
4306   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4307 
4308   SDValue Src = ASC->getOperand(0);
4309   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4310 
4311   const AMDGPUTargetMachine &TM =
4312     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4313 
4314   // flat -> local/private
4315   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4316     unsigned DestAS = ASC->getDestAddressSpace();
4317 
4318     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4319         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4320       unsigned NullVal = TM.getNullPointerValue(DestAS);
4321       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4322       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4323       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4324 
4325       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4326                          NonNull, Ptr, SegmentNullPtr);
4327     }
4328   }
4329 
4330   // local/private -> flat
4331   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4332     unsigned SrcAS = ASC->getSrcAddressSpace();
4333 
4334     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4335         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4336       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4337       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4338 
4339       SDValue NonNull
4340         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4341 
4342       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4343       SDValue CvtPtr
4344         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4345 
4346       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4347                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4348                          FlatNullPtr);
4349     }
4350   }
4351 
4352   // global <-> flat are no-ops and never emitted.
4353 
4354   const MachineFunction &MF = DAG.getMachineFunction();
4355   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4356     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4357   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4358 
4359   return DAG.getUNDEF(ASC->getValueType(0));
4360 }
4361 
4362 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4363                                                  SelectionDAG &DAG) const {
4364   SDValue Vec = Op.getOperand(0);
4365   SDValue InsVal = Op.getOperand(1);
4366   SDValue Idx = Op.getOperand(2);
4367   EVT VecVT = Vec.getValueType();
4368   EVT EltVT = VecVT.getVectorElementType();
4369   unsigned VecSize = VecVT.getSizeInBits();
4370   unsigned EltSize = EltVT.getSizeInBits();
4371 
4372 
4373   assert(VecSize <= 64);
4374 
4375   unsigned NumElts = VecVT.getVectorNumElements();
4376   SDLoc SL(Op);
4377   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4378 
4379   if (NumElts == 4 && EltSize == 16 && KIdx) {
4380     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4381 
4382     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4383                                  DAG.getConstant(0, SL, MVT::i32));
4384     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4385                                  DAG.getConstant(1, SL, MVT::i32));
4386 
4387     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4388     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4389 
4390     unsigned Idx = KIdx->getZExtValue();
4391     bool InsertLo = Idx < 2;
4392     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4393       InsertLo ? LoVec : HiVec,
4394       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4395       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4396 
4397     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4398 
4399     SDValue Concat = InsertLo ?
4400       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4401       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4402 
4403     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4404   }
4405 
4406   if (isa<ConstantSDNode>(Idx))
4407     return SDValue();
4408 
4409   MVT IntVT = MVT::getIntegerVT(VecSize);
4410 
4411   // Avoid stack access for dynamic indexing.
4412   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4413 
4414   // Create a congruent vector with the target value in each element so that
4415   // the required element can be masked and ORed into the target vector.
4416   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4417                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4418 
4419   assert(isPowerOf2_32(EltSize));
4420   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4421 
4422   // Convert vector index to bit-index.
4423   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4424 
4425   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4426   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4427                             DAG.getConstant(0xffff, SL, IntVT),
4428                             ScaledIdx);
4429 
4430   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4431   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4432                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4433 
4434   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4435   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4436 }
4437 
4438 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4439                                                   SelectionDAG &DAG) const {
4440   SDLoc SL(Op);
4441 
4442   EVT ResultVT = Op.getValueType();
4443   SDValue Vec = Op.getOperand(0);
4444   SDValue Idx = Op.getOperand(1);
4445   EVT VecVT = Vec.getValueType();
4446   unsigned VecSize = VecVT.getSizeInBits();
4447   EVT EltVT = VecVT.getVectorElementType();
4448   assert(VecSize <= 64);
4449 
4450   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4451 
4452   // Make sure we do any optimizations that will make it easier to fold
4453   // source modifiers before obscuring it with bit operations.
4454 
4455   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4456   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4457     return Combined;
4458 
4459   unsigned EltSize = EltVT.getSizeInBits();
4460   assert(isPowerOf2_32(EltSize));
4461 
4462   MVT IntVT = MVT::getIntegerVT(VecSize);
4463   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4464 
4465   // Convert vector index to bit-index (* EltSize)
4466   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4467 
4468   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4469   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4470 
4471   if (ResultVT == MVT::f16) {
4472     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4473     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4474   }
4475 
4476   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4477 }
4478 
4479 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4480                                             SelectionDAG &DAG) const {
4481   SDLoc SL(Op);
4482   EVT VT = Op.getValueType();
4483 
4484   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4485     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4486 
4487     // Turn into pair of packed build_vectors.
4488     // TODO: Special case for constants that can be materialized with s_mov_b64.
4489     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4490                                     { Op.getOperand(0), Op.getOperand(1) });
4491     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4492                                     { Op.getOperand(2), Op.getOperand(3) });
4493 
4494     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4495     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4496 
4497     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4498     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4499   }
4500 
4501   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4502   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4503 
4504   SDValue Lo = Op.getOperand(0);
4505   SDValue Hi = Op.getOperand(1);
4506 
4507   // Avoid adding defined bits with the zero_extend.
4508   if (Hi.isUndef()) {
4509     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4510     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4511     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4512   }
4513 
4514   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4515   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4516 
4517   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4518                               DAG.getConstant(16, SL, MVT::i32));
4519   if (Lo.isUndef())
4520     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4521 
4522   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4523   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4524 
4525   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4526   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4527 }
4528 
4529 bool
4530 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4531   // We can fold offsets for anything that doesn't require a GOT relocation.
4532   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4533           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4534           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4535          !shouldEmitGOTReloc(GA->getGlobal());
4536 }
4537 
4538 static SDValue
4539 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4540                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
4541                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
4542   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4543   // lowered to the following code sequence:
4544   //
4545   // For constant address space:
4546   //   s_getpc_b64 s[0:1]
4547   //   s_add_u32 s0, s0, $symbol
4548   //   s_addc_u32 s1, s1, 0
4549   //
4550   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4551   //   a fixup or relocation is emitted to replace $symbol with a literal
4552   //   constant, which is a pc-relative offset from the encoding of the $symbol
4553   //   operand to the global variable.
4554   //
4555   // For global address space:
4556   //   s_getpc_b64 s[0:1]
4557   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4558   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4559   //
4560   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4561   //   fixups or relocations are emitted to replace $symbol@*@lo and
4562   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4563   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
4564   //   operand to the global variable.
4565   //
4566   // What we want here is an offset from the value returned by s_getpc
4567   // (which is the address of the s_add_u32 instruction) to the global
4568   // variable, but since the encoding of $symbol starts 4 bytes after the start
4569   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4570   // small. This requires us to add 4 to the global variable offset in order to
4571   // compute the correct address.
4572   SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4573                                              GAFlags);
4574   SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4575                                              GAFlags == SIInstrInfo::MO_NONE ?
4576                                              GAFlags : GAFlags + 1);
4577   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4578 }
4579 
4580 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4581                                              SDValue Op,
4582                                              SelectionDAG &DAG) const {
4583   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4584   const GlobalValue *GV = GSD->getGlobal();
4585   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
4586       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
4587       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
4588     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4589 
4590   SDLoc DL(GSD);
4591   EVT PtrVT = Op.getValueType();
4592 
4593   // FIXME: Should not make address space based decisions here.
4594   if (shouldEmitFixup(GV))
4595     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4596   else if (shouldEmitPCReloc(GV))
4597     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4598                                    SIInstrInfo::MO_REL32);
4599 
4600   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4601                                             SIInstrInfo::MO_GOTPCREL32);
4602 
4603   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4604   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
4605   const DataLayout &DataLayout = DAG.getDataLayout();
4606   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4607   MachinePointerInfo PtrInfo
4608     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
4609 
4610   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4611                      MachineMemOperand::MODereferenceable |
4612                          MachineMemOperand::MOInvariant);
4613 }
4614 
4615 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4616                                    const SDLoc &DL, SDValue V) const {
4617   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4618   // the destination register.
4619   //
4620   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4621   // so we will end up with redundant moves to m0.
4622   //
4623   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4624 
4625   // A Null SDValue creates a glue result.
4626   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4627                                   V, Chain);
4628   return SDValue(M0, 0);
4629 }
4630 
4631 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4632                                                  SDValue Op,
4633                                                  MVT VT,
4634                                                  unsigned Offset) const {
4635   SDLoc SL(Op);
4636   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4637                                            DAG.getEntryNode(), Offset, 4, false);
4638   // The local size values will have the hi 16-bits as zero.
4639   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4640                      DAG.getValueType(VT));
4641 }
4642 
4643 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4644                                         EVT VT) {
4645   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4646                                       "non-hsa intrinsic with hsa target",
4647                                       DL.getDebugLoc());
4648   DAG.getContext()->diagnose(BadIntrin);
4649   return DAG.getUNDEF(VT);
4650 }
4651 
4652 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4653                                          EVT VT) {
4654   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4655                                       "intrinsic not supported on subtarget",
4656                                       DL.getDebugLoc());
4657   DAG.getContext()->diagnose(BadIntrin);
4658   return DAG.getUNDEF(VT);
4659 }
4660 
4661 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
4662                                     ArrayRef<SDValue> Elts) {
4663   assert(!Elts.empty());
4664   MVT Type;
4665   unsigned NumElts;
4666 
4667   if (Elts.size() == 1) {
4668     Type = MVT::f32;
4669     NumElts = 1;
4670   } else if (Elts.size() == 2) {
4671     Type = MVT::v2f32;
4672     NumElts = 2;
4673   } else if (Elts.size() <= 4) {
4674     Type = MVT::v4f32;
4675     NumElts = 4;
4676   } else if (Elts.size() <= 8) {
4677     Type = MVT::v8f32;
4678     NumElts = 8;
4679   } else {
4680     assert(Elts.size() <= 16);
4681     Type = MVT::v16f32;
4682     NumElts = 16;
4683   }
4684 
4685   SmallVector<SDValue, 16> VecElts(NumElts);
4686   for (unsigned i = 0; i < Elts.size(); ++i) {
4687     SDValue Elt = Elts[i];
4688     if (Elt.getValueType() != MVT::f32)
4689       Elt = DAG.getBitcast(MVT::f32, Elt);
4690     VecElts[i] = Elt;
4691   }
4692   for (unsigned i = Elts.size(); i < NumElts; ++i)
4693     VecElts[i] = DAG.getUNDEF(MVT::f32);
4694 
4695   if (NumElts == 1)
4696     return VecElts[0];
4697   return DAG.getBuildVector(Type, DL, VecElts);
4698 }
4699 
4700 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
4701                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
4702   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
4703 
4704   uint64_t Value = CachePolicyConst->getZExtValue();
4705   SDLoc DL(CachePolicy);
4706   if (GLC) {
4707     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4708     Value &= ~(uint64_t)0x1;
4709   }
4710   if (SLC) {
4711     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4712     Value &= ~(uint64_t)0x2;
4713   }
4714   if (DLC) {
4715     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
4716     Value &= ~(uint64_t)0x4;
4717   }
4718 
4719   return Value == 0;
4720 }
4721 
4722 // Re-construct the required return value for a image load intrinsic.
4723 // This is more complicated due to the optional use TexFailCtrl which means the required
4724 // return type is an aggregate
4725 static SDValue constructRetValue(SelectionDAG &DAG,
4726                                  MachineSDNode *Result,
4727                                  ArrayRef<EVT> ResultTypes,
4728                                  bool IsTexFail, bool Unpacked, bool IsD16,
4729                                  int DMaskPop, int NumVDataDwords,
4730                                  const SDLoc &DL, LLVMContext &Context) {
4731   // Determine the required return type. This is the same regardless of IsTexFail flag
4732   EVT ReqRetVT = ResultTypes[0];
4733   EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
4734   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
4735   EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
4736   EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
4737                                            : AdjEltVT
4738                        : ReqRetVT;
4739 
4740   // Extract data part of the result
4741   // Bitcast the result to the same type as the required return type
4742   int NumElts;
4743   if (IsD16 && !Unpacked)
4744     NumElts = NumVDataDwords << 1;
4745   else
4746     NumElts = NumVDataDwords;
4747 
4748   EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
4749                            : AdjEltVT;
4750 
4751   // Special case for v6f16. Rather than add support for this, use v3i32 to
4752   // extract the data elements
4753   bool V6F16Special = false;
4754   if (NumElts == 6) {
4755     CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
4756     DMaskPop >>= 1;
4757     ReqRetNumElts >>= 1;
4758     V6F16Special = true;
4759     AdjVT = MVT::v2i32;
4760   }
4761 
4762   SDValue N = SDValue(Result, 0);
4763   SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
4764 
4765   // Iterate over the result
4766   SmallVector<SDValue, 4> BVElts;
4767 
4768   if (CastVT.isVector()) {
4769     DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
4770   } else {
4771     BVElts.push_back(CastRes);
4772   }
4773   int ExtraElts = ReqRetNumElts - DMaskPop;
4774   while(ExtraElts--)
4775     BVElts.push_back(DAG.getUNDEF(AdjEltVT));
4776 
4777   SDValue PreTFCRes;
4778   if (ReqRetNumElts > 1) {
4779     SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
4780     if (IsD16 && Unpacked)
4781       PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
4782     else
4783       PreTFCRes = NewVec;
4784   } else {
4785     PreTFCRes = BVElts[0];
4786   }
4787 
4788   if (V6F16Special)
4789     PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
4790 
4791   if (!IsTexFail) {
4792     if (Result->getNumValues() > 1)
4793       return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
4794     else
4795       return PreTFCRes;
4796   }
4797 
4798   // Extract the TexFail result and insert into aggregate return
4799   SmallVector<SDValue, 1> TFCElt;
4800   DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
4801   SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
4802   return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
4803 }
4804 
4805 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
4806                          SDValue *LWE, bool &IsTexFail) {
4807   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
4808 
4809   uint64_t Value = TexFailCtrlConst->getZExtValue();
4810   if (Value) {
4811     IsTexFail = true;
4812   }
4813 
4814   SDLoc DL(TexFailCtrlConst);
4815   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4816   Value &= ~(uint64_t)0x1;
4817   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4818   Value &= ~(uint64_t)0x2;
4819 
4820   return Value == 0;
4821 }
4822 
4823 SDValue SITargetLowering::lowerImage(SDValue Op,
4824                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
4825                                      SelectionDAG &DAG) const {
4826   SDLoc DL(Op);
4827   MachineFunction &MF = DAG.getMachineFunction();
4828   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
4829   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4830       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
4831   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
4832   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
4833       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
4834   unsigned IntrOpcode = Intr->BaseOpcode;
4835   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
4836 
4837   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
4838   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
4839   bool IsD16 = false;
4840   bool IsA16 = false;
4841   SDValue VData;
4842   int NumVDataDwords;
4843   bool AdjustRetType = false;
4844 
4845   unsigned AddrIdx; // Index of first address argument
4846   unsigned DMask;
4847   unsigned DMaskLanes = 0;
4848 
4849   if (BaseOpcode->Atomic) {
4850     VData = Op.getOperand(2);
4851 
4852     bool Is64Bit = VData.getValueType() == MVT::i64;
4853     if (BaseOpcode->AtomicX2) {
4854       SDValue VData2 = Op.getOperand(3);
4855       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
4856                                  {VData, VData2});
4857       if (Is64Bit)
4858         VData = DAG.getBitcast(MVT::v4i32, VData);
4859 
4860       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
4861       DMask = Is64Bit ? 0xf : 0x3;
4862       NumVDataDwords = Is64Bit ? 4 : 2;
4863       AddrIdx = 4;
4864     } else {
4865       DMask = Is64Bit ? 0x3 : 0x1;
4866       NumVDataDwords = Is64Bit ? 2 : 1;
4867       AddrIdx = 3;
4868     }
4869   } else {
4870     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
4871     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
4872     DMask = DMaskConst->getZExtValue();
4873     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
4874 
4875     if (BaseOpcode->Store) {
4876       VData = Op.getOperand(2);
4877 
4878       MVT StoreVT = VData.getSimpleValueType();
4879       if (StoreVT.getScalarType() == MVT::f16) {
4880         if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4881             !BaseOpcode->HasD16)
4882           return Op; // D16 is unsupported for this instruction
4883 
4884         IsD16 = true;
4885         VData = handleD16VData(VData, DAG);
4886       }
4887 
4888       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
4889     } else {
4890       // Work out the num dwords based on the dmask popcount and underlying type
4891       // and whether packing is supported.
4892       MVT LoadVT = ResultTypes[0].getSimpleVT();
4893       if (LoadVT.getScalarType() == MVT::f16) {
4894         if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4895             !BaseOpcode->HasD16)
4896           return Op; // D16 is unsupported for this instruction
4897 
4898         IsD16 = true;
4899       }
4900 
4901       // Confirm that the return type is large enough for the dmask specified
4902       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
4903           (!LoadVT.isVector() && DMaskLanes > 1))
4904           return Op;
4905 
4906       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
4907         NumVDataDwords = (DMaskLanes + 1) / 2;
4908       else
4909         NumVDataDwords = DMaskLanes;
4910 
4911       AdjustRetType = true;
4912     }
4913 
4914     AddrIdx = DMaskIdx + 1;
4915   }
4916 
4917   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
4918   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
4919   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
4920   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
4921                        NumCoords + NumLCM;
4922   unsigned NumMIVAddrs = NumVAddrs;
4923 
4924   SmallVector<SDValue, 4> VAddrs;
4925 
4926   // Optimize _L to _LZ when _L is zero
4927   if (LZMappingInfo) {
4928     if (auto ConstantLod =
4929          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
4930       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
4931         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
4932         NumMIVAddrs--;               // remove 'lod'
4933       }
4934     }
4935   }
4936 
4937   // Check for 16 bit addresses and pack if true.
4938   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
4939   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
4940   const MVT VAddrScalarVT = VAddrVT.getScalarType();
4941   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
4942       ST->hasFeature(AMDGPU::FeatureR128A16)) {
4943     IsA16 = true;
4944     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
4945     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
4946       SDValue AddrLo, AddrHi;
4947       // Push back extra arguments.
4948       if (i < DimIdx) {
4949         AddrLo = Op.getOperand(i);
4950       } else {
4951         AddrLo = Op.getOperand(i);
4952         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
4953         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
4954         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
4955             ((NumGradients / 2) % 2 == 1 &&
4956             (i == DimIdx + (NumGradients / 2) - 1 ||
4957              i == DimIdx + NumGradients - 1))) {
4958           AddrHi = DAG.getUNDEF(MVT::f16);
4959         } else {
4960           AddrHi = Op.getOperand(i + 1);
4961           i++;
4962         }
4963         AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
4964                              {AddrLo, AddrHi});
4965         AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
4966       }
4967       VAddrs.push_back(AddrLo);
4968     }
4969   } else {
4970     for (unsigned i = 0; i < NumMIVAddrs; ++i)
4971       VAddrs.push_back(Op.getOperand(AddrIdx + i));
4972   }
4973 
4974   // If the register allocator cannot place the address registers contiguously
4975   // without introducing moves, then using the non-sequential address encoding
4976   // is always preferable, since it saves VALU instructions and is usually a
4977   // wash in terms of code size or even better.
4978   //
4979   // However, we currently have no way of hinting to the register allocator that
4980   // MIMG addresses should be placed contiguously when it is possible to do so,
4981   // so force non-NSA for the common 2-address case as a heuristic.
4982   //
4983   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
4984   // allocation when possible.
4985   bool UseNSA =
4986       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
4987   SDValue VAddr;
4988   if (!UseNSA)
4989     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
4990 
4991   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
4992   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
4993   unsigned CtrlIdx; // Index of texfailctrl argument
4994   SDValue Unorm;
4995   if (!BaseOpcode->Sampler) {
4996     Unorm = True;
4997     CtrlIdx = AddrIdx + NumVAddrs + 1;
4998   } else {
4999     auto UnormConst =
5000         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5001 
5002     Unorm = UnormConst->getZExtValue() ? True : False;
5003     CtrlIdx = AddrIdx + NumVAddrs + 3;
5004   }
5005 
5006   SDValue TFE;
5007   SDValue LWE;
5008   SDValue TexFail = Op.getOperand(CtrlIdx);
5009   bool IsTexFail = false;
5010   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5011     return Op;
5012 
5013   if (IsTexFail) {
5014     if (!DMaskLanes) {
5015       // Expecting to get an error flag since TFC is on - and dmask is 0
5016       // Force dmask to be at least 1 otherwise the instruction will fail
5017       DMask = 0x1;
5018       DMaskLanes = 1;
5019       NumVDataDwords = 1;
5020     }
5021     NumVDataDwords += 1;
5022     AdjustRetType = true;
5023   }
5024 
5025   // Has something earlier tagged that the return type needs adjusting
5026   // This happens if the instruction is a load or has set TexFailCtrl flags
5027   if (AdjustRetType) {
5028     // NumVDataDwords reflects the true number of dwords required in the return type
5029     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5030       // This is a no-op load. This can be eliminated
5031       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5032       if (isa<MemSDNode>(Op))
5033         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5034       return Undef;
5035     }
5036 
5037     EVT NewVT = NumVDataDwords > 1 ?
5038                   EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
5039                 : MVT::f32;
5040 
5041     ResultTypes[0] = NewVT;
5042     if (ResultTypes.size() == 3) {
5043       // Original result was aggregate type used for TexFailCtrl results
5044       // The actual instruction returns as a vector type which has now been
5045       // created. Remove the aggregate result.
5046       ResultTypes.erase(&ResultTypes[1]);
5047     }
5048   }
5049 
5050   SDValue GLC;
5051   SDValue SLC;
5052   SDValue DLC;
5053   if (BaseOpcode->Atomic) {
5054     GLC = True; // TODO no-return optimization
5055     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5056                           IsGFX10 ? &DLC : nullptr))
5057       return Op;
5058   } else {
5059     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5060                           IsGFX10 ? &DLC : nullptr))
5061       return Op;
5062   }
5063 
5064   SmallVector<SDValue, 26> Ops;
5065   if (BaseOpcode->Store || BaseOpcode->Atomic)
5066     Ops.push_back(VData); // vdata
5067   if (UseNSA) {
5068     for (const SDValue &Addr : VAddrs)
5069       Ops.push_back(Addr);
5070   } else {
5071     Ops.push_back(VAddr);
5072   }
5073   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5074   if (BaseOpcode->Sampler)
5075     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5076   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5077   if (IsGFX10)
5078     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5079   Ops.push_back(Unorm);
5080   if (IsGFX10)
5081     Ops.push_back(DLC);
5082   Ops.push_back(GLC);
5083   Ops.push_back(SLC);
5084   Ops.push_back(IsA16 &&  // a16 or r128
5085                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5086   Ops.push_back(TFE); // tfe
5087   Ops.push_back(LWE); // lwe
5088   if (!IsGFX10)
5089     Ops.push_back(DimInfo->DA ? True : False);
5090   if (BaseOpcode->HasD16)
5091     Ops.push_back(IsD16 ? True : False);
5092   if (isa<MemSDNode>(Op))
5093     Ops.push_back(Op.getOperand(0)); // chain
5094 
5095   int NumVAddrDwords =
5096       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5097   int Opcode = -1;
5098 
5099   if (IsGFX10) {
5100     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5101                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5102                                           : AMDGPU::MIMGEncGfx10Default,
5103                                    NumVDataDwords, NumVAddrDwords);
5104   } else {
5105     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5106       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5107                                      NumVDataDwords, NumVAddrDwords);
5108     if (Opcode == -1)
5109       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5110                                      NumVDataDwords, NumVAddrDwords);
5111   }
5112   assert(Opcode != -1);
5113 
5114   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5115   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5116     MachineMemOperand *MemRef = MemOp->getMemOperand();
5117     DAG.setNodeMemRefs(NewNode, {MemRef});
5118   }
5119 
5120   if (BaseOpcode->AtomicX2) {
5121     SmallVector<SDValue, 1> Elt;
5122     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5123     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5124   } else if (!BaseOpcode->Store) {
5125     return constructRetValue(DAG, NewNode,
5126                              OrigResultTypes, IsTexFail,
5127                              Subtarget->hasUnpackedD16VMem(), IsD16,
5128                              DMaskLanes, NumVDataDwords, DL,
5129                              *DAG.getContext());
5130   }
5131 
5132   return SDValue(NewNode, 0);
5133 }
5134 
5135 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5136                                        SDValue Offset, SDValue GLC,
5137                                        SelectionDAG &DAG) const {
5138   MachineFunction &MF = DAG.getMachineFunction();
5139   MachineMemOperand *MMO = MF.getMachineMemOperand(
5140       MachinePointerInfo(),
5141       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5142           MachineMemOperand::MOInvariant,
5143       VT.getStoreSize(), VT.getStoreSize());
5144 
5145   if (!Offset->isDivergent()) {
5146     SDValue Ops[] = {
5147         Rsrc,
5148         Offset, // Offset
5149         GLC     // glc
5150     };
5151     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5152                                    DAG.getVTList(VT), Ops, VT, MMO);
5153   }
5154 
5155   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5156   // assume that the buffer is unswizzled.
5157   SmallVector<SDValue, 4> Loads;
5158   unsigned NumLoads = 1;
5159   MVT LoadVT = VT.getSimpleVT();
5160   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5161   assert((LoadVT.getScalarType() == MVT::i32 ||
5162           LoadVT.getScalarType() == MVT::f32) &&
5163          isPowerOf2_32(NumElts));
5164 
5165   if (NumElts == 8 || NumElts == 16) {
5166     NumLoads = NumElts == 16 ? 4 : 2;
5167     LoadVT = MVT::v4i32;
5168   }
5169 
5170   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5171   unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5172   SDValue Ops[] = {
5173       DAG.getEntryNode(),                         // Chain
5174       Rsrc,                                       // rsrc
5175       DAG.getConstant(0, DL, MVT::i32),           // vindex
5176       {},                                         // voffset
5177       {},                                         // soffset
5178       {},                                         // offset
5179       DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5180       DAG.getConstant(0, DL, MVT::i1),            // idxen
5181   };
5182 
5183   // Use the alignment to ensure that the required offsets will fit into the
5184   // immediate offsets.
5185   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5186 
5187   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5188   for (unsigned i = 0; i < NumLoads; ++i) {
5189     Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32);
5190     Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
5191                                             Ops, LoadVT, MMO));
5192   }
5193 
5194   if (VT == MVT::v8i32 || VT == MVT::v16i32)
5195     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5196 
5197   return Loads[0];
5198 }
5199 
5200 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5201                                                   SelectionDAG &DAG) const {
5202   MachineFunction &MF = DAG.getMachineFunction();
5203   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5204 
5205   EVT VT = Op.getValueType();
5206   SDLoc DL(Op);
5207   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5208 
5209   // TODO: Should this propagate fast-math-flags?
5210 
5211   switch (IntrinsicID) {
5212   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5213     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5214       return emitNonHSAIntrinsicError(DAG, DL, VT);
5215     return getPreloadedValue(DAG, *MFI, VT,
5216                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5217   }
5218   case Intrinsic::amdgcn_dispatch_ptr:
5219   case Intrinsic::amdgcn_queue_ptr: {
5220     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5221       DiagnosticInfoUnsupported BadIntrin(
5222           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5223           DL.getDebugLoc());
5224       DAG.getContext()->diagnose(BadIntrin);
5225       return DAG.getUNDEF(VT);
5226     }
5227 
5228     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5229       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5230     return getPreloadedValue(DAG, *MFI, VT, RegID);
5231   }
5232   case Intrinsic::amdgcn_implicitarg_ptr: {
5233     if (MFI->isEntryFunction())
5234       return getImplicitArgPtr(DAG, DL);
5235     return getPreloadedValue(DAG, *MFI, VT,
5236                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5237   }
5238   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5239     return getPreloadedValue(DAG, *MFI, VT,
5240                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5241   }
5242   case Intrinsic::amdgcn_dispatch_id: {
5243     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5244   }
5245   case Intrinsic::amdgcn_rcp:
5246     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5247   case Intrinsic::amdgcn_rsq:
5248     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5249   case Intrinsic::amdgcn_rsq_legacy:
5250     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5251       return emitRemovedIntrinsicError(DAG, DL, VT);
5252 
5253     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5254   case Intrinsic::amdgcn_rcp_legacy:
5255     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5256       return emitRemovedIntrinsicError(DAG, DL, VT);
5257     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5258   case Intrinsic::amdgcn_rsq_clamp: {
5259     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5260       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5261 
5262     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5263     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5264     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5265 
5266     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5267     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5268                               DAG.getConstantFP(Max, DL, VT));
5269     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5270                        DAG.getConstantFP(Min, DL, VT));
5271   }
5272   case Intrinsic::r600_read_ngroups_x:
5273     if (Subtarget->isAmdHsaOS())
5274       return emitNonHSAIntrinsicError(DAG, DL, VT);
5275 
5276     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5277                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5278   case Intrinsic::r600_read_ngroups_y:
5279     if (Subtarget->isAmdHsaOS())
5280       return emitNonHSAIntrinsicError(DAG, DL, VT);
5281 
5282     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5283                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5284   case Intrinsic::r600_read_ngroups_z:
5285     if (Subtarget->isAmdHsaOS())
5286       return emitNonHSAIntrinsicError(DAG, DL, VT);
5287 
5288     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5289                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5290   case Intrinsic::r600_read_global_size_x:
5291     if (Subtarget->isAmdHsaOS())
5292       return emitNonHSAIntrinsicError(DAG, DL, VT);
5293 
5294     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5295                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5296   case Intrinsic::r600_read_global_size_y:
5297     if (Subtarget->isAmdHsaOS())
5298       return emitNonHSAIntrinsicError(DAG, DL, VT);
5299 
5300     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5301                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5302   case Intrinsic::r600_read_global_size_z:
5303     if (Subtarget->isAmdHsaOS())
5304       return emitNonHSAIntrinsicError(DAG, DL, VT);
5305 
5306     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5307                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5308   case Intrinsic::r600_read_local_size_x:
5309     if (Subtarget->isAmdHsaOS())
5310       return emitNonHSAIntrinsicError(DAG, DL, VT);
5311 
5312     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5313                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5314   case Intrinsic::r600_read_local_size_y:
5315     if (Subtarget->isAmdHsaOS())
5316       return emitNonHSAIntrinsicError(DAG, DL, VT);
5317 
5318     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5319                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5320   case Intrinsic::r600_read_local_size_z:
5321     if (Subtarget->isAmdHsaOS())
5322       return emitNonHSAIntrinsicError(DAG, DL, VT);
5323 
5324     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5325                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5326   case Intrinsic::amdgcn_workgroup_id_x:
5327   case Intrinsic::r600_read_tgid_x:
5328     return getPreloadedValue(DAG, *MFI, VT,
5329                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5330   case Intrinsic::amdgcn_workgroup_id_y:
5331   case Intrinsic::r600_read_tgid_y:
5332     return getPreloadedValue(DAG, *MFI, VT,
5333                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5334   case Intrinsic::amdgcn_workgroup_id_z:
5335   case Intrinsic::r600_read_tgid_z:
5336     return getPreloadedValue(DAG, *MFI, VT,
5337                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5338   case Intrinsic::amdgcn_workitem_id_x:
5339   case Intrinsic::r600_read_tidig_x:
5340     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5341                           SDLoc(DAG.getEntryNode()),
5342                           MFI->getArgInfo().WorkItemIDX);
5343   case Intrinsic::amdgcn_workitem_id_y:
5344   case Intrinsic::r600_read_tidig_y:
5345     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5346                           SDLoc(DAG.getEntryNode()),
5347                           MFI->getArgInfo().WorkItemIDY);
5348   case Intrinsic::amdgcn_workitem_id_z:
5349   case Intrinsic::r600_read_tidig_z:
5350     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5351                           SDLoc(DAG.getEntryNode()),
5352                           MFI->getArgInfo().WorkItemIDZ);
5353   case Intrinsic::amdgcn_s_buffer_load: {
5354     unsigned Cache = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
5355     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2),
5356                         DAG.getTargetConstant(Cache & 1, DL, MVT::i1), DAG);
5357   }
5358   case Intrinsic::amdgcn_fdiv_fast:
5359     return lowerFDIV_FAST(Op, DAG);
5360   case Intrinsic::amdgcn_interp_mov: {
5361     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5362     SDValue Glue = M0.getValue(1);
5363     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
5364                        Op.getOperand(2), Op.getOperand(3), Glue);
5365   }
5366   case Intrinsic::amdgcn_interp_p1: {
5367     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5368     SDValue Glue = M0.getValue(1);
5369     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
5370                        Op.getOperand(2), Op.getOperand(3), Glue);
5371   }
5372   case Intrinsic::amdgcn_interp_p2: {
5373     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5374     SDValue Glue = SDValue(M0.getNode(), 1);
5375     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
5376                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
5377                        Glue);
5378   }
5379   case Intrinsic::amdgcn_interp_p1_f16: {
5380     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5381     SDValue Glue = M0.getValue(1);
5382     if (getSubtarget()->getLDSBankCount() == 16) {
5383       // 16 bank LDS
5384       SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
5385                               DAG.getConstant(2, DL, MVT::i32), // P0
5386                               Op.getOperand(2), // Attrchan
5387                               Op.getOperand(3), // Attr
5388                               Glue);
5389       SDValue Ops[] = {
5390         Op.getOperand(1), // Src0
5391         Op.getOperand(2), // Attrchan
5392         Op.getOperand(3), // Attr
5393         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5394         S, // Src2 - holds two f16 values selected by high
5395         DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5396         Op.getOperand(4), // high
5397         DAG.getConstant(0, DL, MVT::i1), // $clamp
5398         DAG.getConstant(0, DL, MVT::i32) // $omod
5399       };
5400       return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
5401     } else {
5402       // 32 bank LDS
5403       SDValue Ops[] = {
5404         Op.getOperand(1), // Src0
5405         Op.getOperand(2), // Attrchan
5406         Op.getOperand(3), // Attr
5407         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5408         Op.getOperand(4), // high
5409         DAG.getConstant(0, DL, MVT::i1), // $clamp
5410         DAG.getConstant(0, DL, MVT::i32), // $omod
5411         Glue
5412       };
5413       return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
5414     }
5415   }
5416   case Intrinsic::amdgcn_interp_p2_f16: {
5417     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6));
5418     SDValue Glue = SDValue(M0.getNode(), 1);
5419     SDValue Ops[] = {
5420       Op.getOperand(2), // Src0
5421       Op.getOperand(3), // Attrchan
5422       Op.getOperand(4), // Attr
5423       DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5424       Op.getOperand(1), // Src2
5425       DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5426       Op.getOperand(5), // high
5427       DAG.getConstant(0, DL, MVT::i1), // $clamp
5428       Glue
5429     };
5430     return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops);
5431   }
5432   case Intrinsic::amdgcn_sin:
5433     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5434 
5435   case Intrinsic::amdgcn_cos:
5436     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5437 
5438   case Intrinsic::amdgcn_log_clamp: {
5439     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5440       return SDValue();
5441 
5442     DiagnosticInfoUnsupported BadIntrin(
5443       MF.getFunction(), "intrinsic not supported on subtarget",
5444       DL.getDebugLoc());
5445       DAG.getContext()->diagnose(BadIntrin);
5446       return DAG.getUNDEF(VT);
5447   }
5448   case Intrinsic::amdgcn_ldexp:
5449     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5450                        Op.getOperand(1), Op.getOperand(2));
5451 
5452   case Intrinsic::amdgcn_fract:
5453     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5454 
5455   case Intrinsic::amdgcn_class:
5456     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5457                        Op.getOperand(1), Op.getOperand(2));
5458   case Intrinsic::amdgcn_div_fmas:
5459     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5460                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5461                        Op.getOperand(4));
5462 
5463   case Intrinsic::amdgcn_div_fixup:
5464     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5465                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5466 
5467   case Intrinsic::amdgcn_trig_preop:
5468     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5469                        Op.getOperand(1), Op.getOperand(2));
5470   case Intrinsic::amdgcn_div_scale: {
5471     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5472 
5473     // Translate to the operands expected by the machine instruction. The
5474     // first parameter must be the same as the first instruction.
5475     SDValue Numerator = Op.getOperand(1);
5476     SDValue Denominator = Op.getOperand(2);
5477 
5478     // Note this order is opposite of the machine instruction's operations,
5479     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5480     // intrinsic has the numerator as the first operand to match a normal
5481     // division operation.
5482 
5483     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5484 
5485     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5486                        Denominator, Numerator);
5487   }
5488   case Intrinsic::amdgcn_icmp: {
5489     // There is a Pat that handles this variant, so return it as-is.
5490     if (Op.getOperand(1).getValueType() == MVT::i1 &&
5491         Op.getConstantOperandVal(2) == 0 &&
5492         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
5493       return Op;
5494     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
5495   }
5496   case Intrinsic::amdgcn_fcmp: {
5497     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
5498   }
5499   case Intrinsic::amdgcn_fmed3:
5500     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
5501                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5502   case Intrinsic::amdgcn_fdot2:
5503     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
5504                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5505                        Op.getOperand(4));
5506   case Intrinsic::amdgcn_fmul_legacy:
5507     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
5508                        Op.getOperand(1), Op.getOperand(2));
5509   case Intrinsic::amdgcn_sffbh:
5510     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
5511   case Intrinsic::amdgcn_sbfe:
5512     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
5513                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5514   case Intrinsic::amdgcn_ubfe:
5515     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
5516                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5517   case Intrinsic::amdgcn_cvt_pkrtz:
5518   case Intrinsic::amdgcn_cvt_pknorm_i16:
5519   case Intrinsic::amdgcn_cvt_pknorm_u16:
5520   case Intrinsic::amdgcn_cvt_pk_i16:
5521   case Intrinsic::amdgcn_cvt_pk_u16: {
5522     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
5523     EVT VT = Op.getValueType();
5524     unsigned Opcode;
5525 
5526     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
5527       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
5528     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
5529       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5530     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
5531       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5532     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
5533       Opcode = AMDGPUISD::CVT_PK_I16_I32;
5534     else
5535       Opcode = AMDGPUISD::CVT_PK_U16_U32;
5536 
5537     if (isTypeLegal(VT))
5538       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
5539 
5540     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
5541                                Op.getOperand(1), Op.getOperand(2));
5542     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
5543   }
5544   case Intrinsic::amdgcn_wqm: {
5545     SDValue Src = Op.getOperand(1);
5546     return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
5547                    0);
5548   }
5549   case Intrinsic::amdgcn_wwm: {
5550     SDValue Src = Op.getOperand(1);
5551     return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
5552                    0);
5553   }
5554   case Intrinsic::amdgcn_fmad_ftz:
5555     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
5556                        Op.getOperand(2), Op.getOperand(3));
5557   default:
5558     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5559             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5560       return lowerImage(Op, ImageDimIntr, DAG);
5561 
5562     return Op;
5563   }
5564 }
5565 
5566 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
5567                                                  SelectionDAG &DAG) const {
5568   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5569   SDLoc DL(Op);
5570 
5571   switch (IntrID) {
5572   case Intrinsic::amdgcn_ds_ordered_add:
5573   case Intrinsic::amdgcn_ds_ordered_swap: {
5574     MemSDNode *M = cast<MemSDNode>(Op);
5575     SDValue Chain = M->getOperand(0);
5576     SDValue M0 = M->getOperand(2);
5577     SDValue Value = M->getOperand(3);
5578     unsigned OrderedCountIndex = M->getConstantOperandVal(7);
5579     unsigned WaveRelease = M->getConstantOperandVal(8);
5580     unsigned WaveDone = M->getConstantOperandVal(9);
5581     unsigned ShaderType;
5582     unsigned Instruction;
5583 
5584     switch (IntrID) {
5585     case Intrinsic::amdgcn_ds_ordered_add:
5586       Instruction = 0;
5587       break;
5588     case Intrinsic::amdgcn_ds_ordered_swap:
5589       Instruction = 1;
5590       break;
5591     }
5592 
5593     if (WaveDone && !WaveRelease)
5594       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
5595 
5596     switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
5597     case CallingConv::AMDGPU_CS:
5598     case CallingConv::AMDGPU_KERNEL:
5599       ShaderType = 0;
5600       break;
5601     case CallingConv::AMDGPU_PS:
5602       ShaderType = 1;
5603       break;
5604     case CallingConv::AMDGPU_VS:
5605       ShaderType = 2;
5606       break;
5607     case CallingConv::AMDGPU_GS:
5608       ShaderType = 3;
5609       break;
5610     default:
5611       report_fatal_error("ds_ordered_count unsupported for this calling conv");
5612     }
5613 
5614     unsigned Offset0 = OrderedCountIndex << 2;
5615     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
5616                        (Instruction << 4);
5617     unsigned Offset = Offset0 | (Offset1 << 8);
5618 
5619     SDValue Ops[] = {
5620       Chain,
5621       Value,
5622       DAG.getTargetConstant(Offset, DL, MVT::i16),
5623       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
5624     };
5625     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
5626                                    M->getVTList(), Ops, M->getMemoryVT(),
5627                                    M->getMemOperand());
5628   }
5629   case Intrinsic::amdgcn_ds_fadd: {
5630     MemSDNode *M = cast<MemSDNode>(Op);
5631     unsigned Opc;
5632     switch (IntrID) {
5633     case Intrinsic::amdgcn_ds_fadd:
5634       Opc = ISD::ATOMIC_LOAD_FADD;
5635       break;
5636     }
5637 
5638     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
5639                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
5640                          M->getMemOperand());
5641   }
5642   case Intrinsic::amdgcn_atomic_inc:
5643   case Intrinsic::amdgcn_atomic_dec:
5644   case Intrinsic::amdgcn_ds_fmin:
5645   case Intrinsic::amdgcn_ds_fmax: {
5646     MemSDNode *M = cast<MemSDNode>(Op);
5647     unsigned Opc;
5648     switch (IntrID) {
5649     case Intrinsic::amdgcn_atomic_inc:
5650       Opc = AMDGPUISD::ATOMIC_INC;
5651       break;
5652     case Intrinsic::amdgcn_atomic_dec:
5653       Opc = AMDGPUISD::ATOMIC_DEC;
5654       break;
5655     case Intrinsic::amdgcn_ds_fmin:
5656       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
5657       break;
5658     case Intrinsic::amdgcn_ds_fmax:
5659       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
5660       break;
5661     default:
5662       llvm_unreachable("Unknown intrinsic!");
5663     }
5664     SDValue Ops[] = {
5665       M->getOperand(0), // Chain
5666       M->getOperand(2), // Ptr
5667       M->getOperand(3)  // Value
5668     };
5669 
5670     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
5671                                    M->getMemoryVT(), M->getMemOperand());
5672   }
5673   case Intrinsic::amdgcn_buffer_load:
5674   case Intrinsic::amdgcn_buffer_load_format: {
5675     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
5676     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
5677     unsigned IdxEn = 1;
5678     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
5679       IdxEn = Idx->getZExtValue() != 0;
5680     SDValue Ops[] = {
5681       Op.getOperand(0), // Chain
5682       Op.getOperand(2), // rsrc
5683       Op.getOperand(3), // vindex
5684       SDValue(),        // voffset -- will be set by setBufferOffsets
5685       SDValue(),        // soffset -- will be set by setBufferOffsets
5686       SDValue(),        // offset -- will be set by setBufferOffsets
5687       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
5688       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
5689     };
5690 
5691     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
5692     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
5693         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5694 
5695     EVT VT = Op.getValueType();
5696     EVT IntVT = VT.changeTypeToInteger();
5697     auto *M = cast<MemSDNode>(Op);
5698     EVT LoadVT = Op.getValueType();
5699 
5700     if (LoadVT.getScalarType() == MVT::f16)
5701       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5702                                  M, DAG, Ops);
5703 
5704     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
5705     if (LoadVT.getScalarType() == MVT::i8 ||
5706         LoadVT.getScalarType() == MVT::i16)
5707       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
5708 
5709     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5710                                M->getMemOperand(), DAG);
5711   }
5712   case Intrinsic::amdgcn_raw_buffer_load:
5713   case Intrinsic::amdgcn_raw_buffer_load_format: {
5714     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
5715     SDValue Ops[] = {
5716       Op.getOperand(0), // Chain
5717       Op.getOperand(2), // rsrc
5718       DAG.getConstant(0, DL, MVT::i32), // vindex
5719       Offsets.first,    // voffset
5720       Op.getOperand(4), // soffset
5721       Offsets.second,   // offset
5722       Op.getOperand(5), // cachepolicy
5723       DAG.getConstant(0, DL, MVT::i1), // idxen
5724     };
5725 
5726     unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ?
5727         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5728 
5729     EVT VT = Op.getValueType();
5730     EVT IntVT = VT.changeTypeToInteger();
5731     auto *M = cast<MemSDNode>(Op);
5732     EVT LoadVT = Op.getValueType();
5733 
5734     if (LoadVT.getScalarType() == MVT::f16)
5735       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5736                                  M, DAG, Ops);
5737 
5738     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
5739     if (LoadVT.getScalarType() == MVT::i8 ||
5740         LoadVT.getScalarType() == MVT::i16)
5741       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
5742 
5743     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5744                                M->getMemOperand(), DAG);
5745   }
5746   case Intrinsic::amdgcn_struct_buffer_load:
5747   case Intrinsic::amdgcn_struct_buffer_load_format: {
5748     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
5749     SDValue Ops[] = {
5750       Op.getOperand(0), // Chain
5751       Op.getOperand(2), // rsrc
5752       Op.getOperand(3), // vindex
5753       Offsets.first,    // voffset
5754       Op.getOperand(5), // soffset
5755       Offsets.second,   // offset
5756       Op.getOperand(6), // cachepolicy
5757       DAG.getConstant(1, DL, MVT::i1), // idxen
5758     };
5759 
5760     unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ?
5761         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5762 
5763     EVT VT = Op.getValueType();
5764     EVT IntVT = VT.changeTypeToInteger();
5765     auto *M = cast<MemSDNode>(Op);
5766     EVT LoadVT = Op.getValueType();
5767 
5768     if (LoadVT.getScalarType() == MVT::f16)
5769       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5770                                  M, DAG, Ops);
5771 
5772     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
5773     if (LoadVT.getScalarType() == MVT::i8 ||
5774         LoadVT.getScalarType() == MVT::i16)
5775       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
5776 
5777     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5778                                M->getMemOperand(), DAG);
5779   }
5780   case Intrinsic::amdgcn_tbuffer_load: {
5781     MemSDNode *M = cast<MemSDNode>(Op);
5782     EVT LoadVT = Op.getValueType();
5783 
5784     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
5785     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
5786     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
5787     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
5788     unsigned IdxEn = 1;
5789     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
5790       IdxEn = Idx->getZExtValue() != 0;
5791     SDValue Ops[] = {
5792       Op.getOperand(0),  // Chain
5793       Op.getOperand(2),  // rsrc
5794       Op.getOperand(3),  // vindex
5795       Op.getOperand(4),  // voffset
5796       Op.getOperand(5),  // soffset
5797       Op.getOperand(6),  // offset
5798       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
5799       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
5800       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
5801     };
5802 
5803     if (LoadVT.getScalarType() == MVT::f16)
5804       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
5805                                  M, DAG, Ops);
5806     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5807                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
5808                                DAG);
5809   }
5810   case Intrinsic::amdgcn_raw_tbuffer_load: {
5811     MemSDNode *M = cast<MemSDNode>(Op);
5812     EVT LoadVT = Op.getValueType();
5813     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
5814 
5815     SDValue Ops[] = {
5816       Op.getOperand(0),  // Chain
5817       Op.getOperand(2),  // rsrc
5818       DAG.getConstant(0, DL, MVT::i32), // vindex
5819       Offsets.first,     // voffset
5820       Op.getOperand(4),  // soffset
5821       Offsets.second,    // offset
5822       Op.getOperand(5),  // format
5823       Op.getOperand(6),  // cachepolicy
5824       DAG.getConstant(0, DL, MVT::i1), // idxen
5825     };
5826 
5827     if (LoadVT.getScalarType() == MVT::f16)
5828       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
5829                                  M, DAG, Ops);
5830     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5831                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
5832                                DAG);
5833   }
5834   case Intrinsic::amdgcn_struct_tbuffer_load: {
5835     MemSDNode *M = cast<MemSDNode>(Op);
5836     EVT LoadVT = Op.getValueType();
5837     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
5838 
5839     SDValue Ops[] = {
5840       Op.getOperand(0),  // Chain
5841       Op.getOperand(2),  // rsrc
5842       Op.getOperand(3),  // vindex
5843       Offsets.first,     // voffset
5844       Op.getOperand(5),  // soffset
5845       Offsets.second,    // offset
5846       Op.getOperand(6),  // format
5847       Op.getOperand(7),  // cachepolicy
5848       DAG.getConstant(1, DL, MVT::i1), // idxen
5849     };
5850 
5851     if (LoadVT.getScalarType() == MVT::f16)
5852       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
5853                                  M, DAG, Ops);
5854     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5855                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
5856                                DAG);
5857   }
5858   case Intrinsic::amdgcn_buffer_atomic_swap:
5859   case Intrinsic::amdgcn_buffer_atomic_add:
5860   case Intrinsic::amdgcn_buffer_atomic_sub:
5861   case Intrinsic::amdgcn_buffer_atomic_smin:
5862   case Intrinsic::amdgcn_buffer_atomic_umin:
5863   case Intrinsic::amdgcn_buffer_atomic_smax:
5864   case Intrinsic::amdgcn_buffer_atomic_umax:
5865   case Intrinsic::amdgcn_buffer_atomic_and:
5866   case Intrinsic::amdgcn_buffer_atomic_or:
5867   case Intrinsic::amdgcn_buffer_atomic_xor: {
5868     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
5869     unsigned IdxEn = 1;
5870     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
5871       IdxEn = Idx->getZExtValue() != 0;
5872     SDValue Ops[] = {
5873       Op.getOperand(0), // Chain
5874       Op.getOperand(2), // vdata
5875       Op.getOperand(3), // rsrc
5876       Op.getOperand(4), // vindex
5877       SDValue(),        // voffset -- will be set by setBufferOffsets
5878       SDValue(),        // soffset -- will be set by setBufferOffsets
5879       SDValue(),        // offset -- will be set by setBufferOffsets
5880       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
5881       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
5882     };
5883     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
5884     EVT VT = Op.getValueType();
5885 
5886     auto *M = cast<MemSDNode>(Op);
5887     unsigned Opcode = 0;
5888 
5889     switch (IntrID) {
5890     case Intrinsic::amdgcn_buffer_atomic_swap:
5891       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
5892       break;
5893     case Intrinsic::amdgcn_buffer_atomic_add:
5894       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
5895       break;
5896     case Intrinsic::amdgcn_buffer_atomic_sub:
5897       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
5898       break;
5899     case Intrinsic::amdgcn_buffer_atomic_smin:
5900       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
5901       break;
5902     case Intrinsic::amdgcn_buffer_atomic_umin:
5903       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
5904       break;
5905     case Intrinsic::amdgcn_buffer_atomic_smax:
5906       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
5907       break;
5908     case Intrinsic::amdgcn_buffer_atomic_umax:
5909       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
5910       break;
5911     case Intrinsic::amdgcn_buffer_atomic_and:
5912       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
5913       break;
5914     case Intrinsic::amdgcn_buffer_atomic_or:
5915       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5916       break;
5917     case Intrinsic::amdgcn_buffer_atomic_xor:
5918       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5919       break;
5920     default:
5921       llvm_unreachable("unhandled atomic opcode");
5922     }
5923 
5924     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5925                                    M->getMemOperand());
5926   }
5927   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
5928   case Intrinsic::amdgcn_raw_buffer_atomic_add:
5929   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
5930   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
5931   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
5932   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
5933   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
5934   case Intrinsic::amdgcn_raw_buffer_atomic_and:
5935   case Intrinsic::amdgcn_raw_buffer_atomic_or:
5936   case Intrinsic::amdgcn_raw_buffer_atomic_xor: {
5937     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
5938     SDValue Ops[] = {
5939       Op.getOperand(0), // Chain
5940       Op.getOperand(2), // vdata
5941       Op.getOperand(3), // rsrc
5942       DAG.getConstant(0, DL, MVT::i32), // vindex
5943       Offsets.first,    // voffset
5944       Op.getOperand(5), // soffset
5945       Offsets.second,   // offset
5946       Op.getOperand(6), // cachepolicy
5947       DAG.getConstant(0, DL, MVT::i1), // idxen
5948     };
5949     EVT VT = Op.getValueType();
5950 
5951     auto *M = cast<MemSDNode>(Op);
5952     unsigned Opcode = 0;
5953 
5954     switch (IntrID) {
5955     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
5956       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
5957       break;
5958     case Intrinsic::amdgcn_raw_buffer_atomic_add:
5959       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
5960       break;
5961     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
5962       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
5963       break;
5964     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
5965       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
5966       break;
5967     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
5968       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
5969       break;
5970     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
5971       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
5972       break;
5973     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
5974       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
5975       break;
5976     case Intrinsic::amdgcn_raw_buffer_atomic_and:
5977       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
5978       break;
5979     case Intrinsic::amdgcn_raw_buffer_atomic_or:
5980       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5981       break;
5982     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
5983       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5984       break;
5985     default:
5986       llvm_unreachable("unhandled atomic opcode");
5987     }
5988 
5989     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5990                                    M->getMemOperand());
5991   }
5992   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
5993   case Intrinsic::amdgcn_struct_buffer_atomic_add:
5994   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
5995   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
5996   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
5997   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
5998   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
5999   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6000   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6001   case Intrinsic::amdgcn_struct_buffer_atomic_xor: {
6002     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6003     SDValue Ops[] = {
6004       Op.getOperand(0), // Chain
6005       Op.getOperand(2), // vdata
6006       Op.getOperand(3), // rsrc
6007       Op.getOperand(4), // vindex
6008       Offsets.first,    // voffset
6009       Op.getOperand(6), // soffset
6010       Offsets.second,   // offset
6011       Op.getOperand(7), // cachepolicy
6012       DAG.getConstant(1, DL, MVT::i1), // idxen
6013     };
6014     EVT VT = Op.getValueType();
6015 
6016     auto *M = cast<MemSDNode>(Op);
6017     unsigned Opcode = 0;
6018 
6019     switch (IntrID) {
6020     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6021       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6022       break;
6023     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6024       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6025       break;
6026     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6027       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6028       break;
6029     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6030       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6031       break;
6032     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6033       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6034       break;
6035     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6036       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6037       break;
6038     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6039       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6040       break;
6041     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6042       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6043       break;
6044     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6045       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6046       break;
6047     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6048       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6049       break;
6050     default:
6051       llvm_unreachable("unhandled atomic opcode");
6052     }
6053 
6054     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6055                                    M->getMemOperand());
6056   }
6057   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6058     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6059     unsigned IdxEn = 1;
6060     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6061       IdxEn = Idx->getZExtValue() != 0;
6062     SDValue Ops[] = {
6063       Op.getOperand(0), // Chain
6064       Op.getOperand(2), // src
6065       Op.getOperand(3), // cmp
6066       Op.getOperand(4), // rsrc
6067       Op.getOperand(5), // vindex
6068       SDValue(),        // voffset -- will be set by setBufferOffsets
6069       SDValue(),        // soffset -- will be set by setBufferOffsets
6070       SDValue(),        // offset -- will be set by setBufferOffsets
6071       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6072       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6073     };
6074     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6075     EVT VT = Op.getValueType();
6076     auto *M = cast<MemSDNode>(Op);
6077 
6078     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6079                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6080   }
6081   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6082     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6083     SDValue Ops[] = {
6084       Op.getOperand(0), // Chain
6085       Op.getOperand(2), // src
6086       Op.getOperand(3), // cmp
6087       Op.getOperand(4), // rsrc
6088       DAG.getConstant(0, DL, MVT::i32), // vindex
6089       Offsets.first,    // voffset
6090       Op.getOperand(6), // soffset
6091       Offsets.second,   // offset
6092       Op.getOperand(7), // cachepolicy
6093       DAG.getConstant(0, DL, MVT::i1), // idxen
6094     };
6095     EVT VT = Op.getValueType();
6096     auto *M = cast<MemSDNode>(Op);
6097 
6098     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6099                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6100   }
6101   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6102     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6103     SDValue Ops[] = {
6104       Op.getOperand(0), // Chain
6105       Op.getOperand(2), // src
6106       Op.getOperand(3), // cmp
6107       Op.getOperand(4), // rsrc
6108       Op.getOperand(5), // vindex
6109       Offsets.first,    // voffset
6110       Op.getOperand(7), // soffset
6111       Offsets.second,   // offset
6112       Op.getOperand(8), // cachepolicy
6113       DAG.getConstant(1, DL, MVT::i1), // idxen
6114     };
6115     EVT VT = Op.getValueType();
6116     auto *M = cast<MemSDNode>(Op);
6117 
6118     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6119                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6120   }
6121 
6122   default:
6123     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6124             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6125       return lowerImage(Op, ImageDimIntr, DAG);
6126 
6127     return SDValue();
6128   }
6129 }
6130 
6131 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6132 // dwordx4 if on SI.
6133 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6134                                               SDVTList VTList,
6135                                               ArrayRef<SDValue> Ops, EVT MemVT,
6136                                               MachineMemOperand *MMO,
6137                                               SelectionDAG &DAG) const {
6138   EVT VT = VTList.VTs[0];
6139   EVT WidenedVT = VT;
6140   EVT WidenedMemVT = MemVT;
6141   if (!Subtarget->hasDwordx3LoadStores() &&
6142       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6143     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6144                                  WidenedVT.getVectorElementType(), 4);
6145     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6146                                     WidenedMemVT.getVectorElementType(), 4);
6147     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6148   }
6149 
6150   assert(VTList.NumVTs == 2);
6151   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6152 
6153   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6154                                        WidenedMemVT, MMO);
6155   if (WidenedVT != VT) {
6156     auto Extract = DAG.getNode(
6157         ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6158         DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
6159     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6160   }
6161   return NewOp;
6162 }
6163 
6164 SDValue SITargetLowering::handleD16VData(SDValue VData,
6165                                          SelectionDAG &DAG) const {
6166   EVT StoreVT = VData.getValueType();
6167 
6168   // No change for f16 and legal vector D16 types.
6169   if (!StoreVT.isVector())
6170     return VData;
6171 
6172   SDLoc DL(VData);
6173   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6174 
6175   if (Subtarget->hasUnpackedD16VMem()) {
6176     // We need to unpack the packed data to store.
6177     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6178     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6179 
6180     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6181                                         StoreVT.getVectorNumElements());
6182     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6183     return DAG.UnrollVectorOp(ZExt.getNode());
6184   }
6185 
6186   assert(isTypeLegal(StoreVT));
6187   return VData;
6188 }
6189 
6190 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6191                                               SelectionDAG &DAG) const {
6192   SDLoc DL(Op);
6193   SDValue Chain = Op.getOperand(0);
6194   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6195   MachineFunction &MF = DAG.getMachineFunction();
6196 
6197   switch (IntrinsicID) {
6198   case Intrinsic::amdgcn_exp: {
6199     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6200     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6201     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
6202     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
6203 
6204     const SDValue Ops[] = {
6205       Chain,
6206       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6207       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6208       Op.getOperand(4), // src0
6209       Op.getOperand(5), // src1
6210       Op.getOperand(6), // src2
6211       Op.getOperand(7), // src3
6212       DAG.getTargetConstant(0, DL, MVT::i1), // compr
6213       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6214     };
6215 
6216     unsigned Opc = Done->isNullValue() ?
6217       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6218     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6219   }
6220   case Intrinsic::amdgcn_exp_compr: {
6221     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6222     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6223     SDValue Src0 = Op.getOperand(4);
6224     SDValue Src1 = Op.getOperand(5);
6225     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6226     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
6227 
6228     SDValue Undef = DAG.getUNDEF(MVT::f32);
6229     const SDValue Ops[] = {
6230       Chain,
6231       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6232       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6233       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
6234       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
6235       Undef, // src2
6236       Undef, // src3
6237       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6238       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6239     };
6240 
6241     unsigned Opc = Done->isNullValue() ?
6242       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6243     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6244   }
6245   case Intrinsic::amdgcn_s_sendmsg:
6246   case Intrinsic::amdgcn_s_sendmsghalt: {
6247     unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
6248       AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
6249     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
6250     SDValue Glue = Chain.getValue(1);
6251     return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
6252                        Op.getOperand(2), Glue);
6253   }
6254   case Intrinsic::amdgcn_init_exec: {
6255     return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
6256                        Op.getOperand(2));
6257   }
6258   case Intrinsic::amdgcn_init_exec_from_input: {
6259     return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
6260                        Op.getOperand(2), Op.getOperand(3));
6261   }
6262   case Intrinsic::amdgcn_s_barrier: {
6263     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6264       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6265       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6266       if (WGSize <= ST.getWavefrontSize())
6267         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6268                                           Op.getOperand(0)), 0);
6269     }
6270     return SDValue();
6271   };
6272   case Intrinsic::amdgcn_tbuffer_store: {
6273     SDValue VData = Op.getOperand(2);
6274     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6275     if (IsD16)
6276       VData = handleD16VData(VData, DAG);
6277     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6278     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6279     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6280     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6281     unsigned IdxEn = 1;
6282     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6283       IdxEn = Idx->getZExtValue() != 0;
6284     SDValue Ops[] = {
6285       Chain,
6286       VData,             // vdata
6287       Op.getOperand(3),  // rsrc
6288       Op.getOperand(4),  // vindex
6289       Op.getOperand(5),  // voffset
6290       Op.getOperand(6),  // soffset
6291       Op.getOperand(7),  // offset
6292       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6293       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6294       DAG.getConstant(IdxEn, DL, MVT::i1), // idexen
6295     };
6296     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6297                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6298     MemSDNode *M = cast<MemSDNode>(Op);
6299     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6300                                    M->getMemoryVT(), M->getMemOperand());
6301   }
6302 
6303   case Intrinsic::amdgcn_struct_tbuffer_store: {
6304     SDValue VData = Op.getOperand(2);
6305     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6306     if (IsD16)
6307       VData = handleD16VData(VData, DAG);
6308     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6309     SDValue Ops[] = {
6310       Chain,
6311       VData,             // vdata
6312       Op.getOperand(3),  // rsrc
6313       Op.getOperand(4),  // vindex
6314       Offsets.first,     // voffset
6315       Op.getOperand(6),  // soffset
6316       Offsets.second,    // offset
6317       Op.getOperand(7),  // format
6318       Op.getOperand(8),  // cachepolicy
6319       DAG.getConstant(1, DL, MVT::i1), // idexen
6320     };
6321     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6322                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6323     MemSDNode *M = cast<MemSDNode>(Op);
6324     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6325                                    M->getMemoryVT(), M->getMemOperand());
6326   }
6327 
6328   case Intrinsic::amdgcn_raw_tbuffer_store: {
6329     SDValue VData = Op.getOperand(2);
6330     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6331     if (IsD16)
6332       VData = handleD16VData(VData, DAG);
6333     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6334     SDValue Ops[] = {
6335       Chain,
6336       VData,             // vdata
6337       Op.getOperand(3),  // rsrc
6338       DAG.getConstant(0, DL, MVT::i32), // vindex
6339       Offsets.first,     // voffset
6340       Op.getOperand(5),  // soffset
6341       Offsets.second,    // offset
6342       Op.getOperand(6),  // format
6343       Op.getOperand(7),  // cachepolicy
6344       DAG.getConstant(0, DL, MVT::i1), // idexen
6345     };
6346     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6347                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6348     MemSDNode *M = cast<MemSDNode>(Op);
6349     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6350                                    M->getMemoryVT(), M->getMemOperand());
6351   }
6352 
6353   case Intrinsic::amdgcn_buffer_store:
6354   case Intrinsic::amdgcn_buffer_store_format: {
6355     SDValue VData = Op.getOperand(2);
6356     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6357     if (IsD16)
6358       VData = handleD16VData(VData, DAG);
6359     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6360     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6361     unsigned IdxEn = 1;
6362     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6363       IdxEn = Idx->getZExtValue() != 0;
6364     SDValue Ops[] = {
6365       Chain,
6366       VData,
6367       Op.getOperand(3), // rsrc
6368       Op.getOperand(4), // vindex
6369       SDValue(), // voffset -- will be set by setBufferOffsets
6370       SDValue(), // soffset -- will be set by setBufferOffsets
6371       SDValue(), // offset -- will be set by setBufferOffsets
6372       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6373       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6374     };
6375     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6376     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6377                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6378     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6379     MemSDNode *M = cast<MemSDNode>(Op);
6380 
6381     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6382     EVT VDataType = VData.getValueType().getScalarType();
6383     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6384       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6385 
6386     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6387                                    M->getMemoryVT(), M->getMemOperand());
6388   }
6389 
6390   case Intrinsic::amdgcn_raw_buffer_store:
6391   case Intrinsic::amdgcn_raw_buffer_store_format: {
6392     SDValue VData = Op.getOperand(2);
6393     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6394     if (IsD16)
6395       VData = handleD16VData(VData, DAG);
6396     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6397     SDValue Ops[] = {
6398       Chain,
6399       VData,
6400       Op.getOperand(3), // rsrc
6401       DAG.getConstant(0, DL, MVT::i32), // vindex
6402       Offsets.first,    // voffset
6403       Op.getOperand(5), // soffset
6404       Offsets.second,   // offset
6405       Op.getOperand(6), // cachepolicy
6406       DAG.getConstant(0, DL, MVT::i1), // idxen
6407     };
6408     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ?
6409                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6410     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6411     MemSDNode *M = cast<MemSDNode>(Op);
6412 
6413     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6414     EVT VDataType = VData.getValueType().getScalarType();
6415     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6416       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6417 
6418     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6419                                    M->getMemoryVT(), M->getMemOperand());
6420   }
6421 
6422   case Intrinsic::amdgcn_struct_buffer_store:
6423   case Intrinsic::amdgcn_struct_buffer_store_format: {
6424     SDValue VData = Op.getOperand(2);
6425     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6426     if (IsD16)
6427       VData = handleD16VData(VData, DAG);
6428     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6429     SDValue Ops[] = {
6430       Chain,
6431       VData,
6432       Op.getOperand(3), // rsrc
6433       Op.getOperand(4), // vindex
6434       Offsets.first,    // voffset
6435       Op.getOperand(6), // soffset
6436       Offsets.second,   // offset
6437       Op.getOperand(7), // cachepolicy
6438       DAG.getConstant(1, DL, MVT::i1), // idxen
6439     };
6440     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6441                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6442     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6443     MemSDNode *M = cast<MemSDNode>(Op);
6444 
6445     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6446     EVT VDataType = VData.getValueType().getScalarType();
6447     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6448       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6449 
6450     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6451                                    M->getMemoryVT(), M->getMemOperand());
6452   }
6453 
6454   default: {
6455     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6456             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6457       return lowerImage(Op, ImageDimIntr, DAG);
6458 
6459     return Op;
6460   }
6461   }
6462 }
6463 
6464 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
6465 // offset (the offset that is included in bounds checking and swizzling, to be
6466 // split between the instruction's voffset and immoffset fields) and soffset
6467 // (the offset that is excluded from bounds checking and swizzling, to go in
6468 // the instruction's soffset field).  This function takes the first kind of
6469 // offset and figures out how to split it between voffset and immoffset.
6470 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
6471     SDValue Offset, SelectionDAG &DAG) const {
6472   SDLoc DL(Offset);
6473   const unsigned MaxImm = 4095;
6474   SDValue N0 = Offset;
6475   ConstantSDNode *C1 = nullptr;
6476 
6477   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
6478     N0 = SDValue();
6479   else if (DAG.isBaseWithConstantOffset(N0)) {
6480     C1 = cast<ConstantSDNode>(N0.getOperand(1));
6481     N0 = N0.getOperand(0);
6482   }
6483 
6484   if (C1) {
6485     unsigned ImmOffset = C1->getZExtValue();
6486     // If the immediate value is too big for the immoffset field, put the value
6487     // and -4096 into the immoffset field so that the value that is copied/added
6488     // for the voffset field is a multiple of 4096, and it stands more chance
6489     // of being CSEd with the copy/add for another similar load/store.
6490     // However, do not do that rounding down to a multiple of 4096 if that is a
6491     // negative number, as it appears to be illegal to have a negative offset
6492     // in the vgpr, even if adding the immediate offset makes it positive.
6493     unsigned Overflow = ImmOffset & ~MaxImm;
6494     ImmOffset -= Overflow;
6495     if ((int32_t)Overflow < 0) {
6496       Overflow += ImmOffset;
6497       ImmOffset = 0;
6498     }
6499     C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32));
6500     if (Overflow) {
6501       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
6502       if (!N0)
6503         N0 = OverflowVal;
6504       else {
6505         SDValue Ops[] = { N0, OverflowVal };
6506         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
6507       }
6508     }
6509   }
6510   if (!N0)
6511     N0 = DAG.getConstant(0, DL, MVT::i32);
6512   if (!C1)
6513     C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32));
6514   return {N0, SDValue(C1, 0)};
6515 }
6516 
6517 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
6518 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
6519 // pointed to by Offsets.
6520 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
6521                                         SelectionDAG &DAG, SDValue *Offsets,
6522                                         unsigned Align) const {
6523   SDLoc DL(CombinedOffset);
6524   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
6525     uint32_t Imm = C->getZExtValue();
6526     uint32_t SOffset, ImmOffset;
6527     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
6528       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
6529       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6530       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6531       return;
6532     }
6533   }
6534   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
6535     SDValue N0 = CombinedOffset.getOperand(0);
6536     SDValue N1 = CombinedOffset.getOperand(1);
6537     uint32_t SOffset, ImmOffset;
6538     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
6539     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
6540                                                 Subtarget, Align)) {
6541       Offsets[0] = N0;
6542       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6543       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6544       return;
6545     }
6546   }
6547   Offsets[0] = CombinedOffset;
6548   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
6549   Offsets[2] = DAG.getConstant(0, DL, MVT::i32);
6550 }
6551 
6552 // Handle 8 bit and 16 bit buffer loads
6553 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
6554                                                      EVT LoadVT, SDLoc DL,
6555                                                      ArrayRef<SDValue> Ops,
6556                                                      MemSDNode *M) const {
6557   EVT IntVT = LoadVT.changeTypeToInteger();
6558   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
6559          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
6560 
6561   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
6562   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
6563                                                Ops, IntVT,
6564                                                M->getMemOperand());
6565   SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL,
6566                                         LoadVT.getScalarType(), BufferLoad);
6567   return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL);
6568 }
6569 
6570 // Handle 8 bit and 16 bit buffer stores
6571 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
6572                                                       EVT VDataType, SDLoc DL,
6573                                                       SDValue Ops[],
6574                                                       MemSDNode *M) const {
6575   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
6576   Ops[1] = BufferStoreExt;
6577   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
6578                                  AMDGPUISD::BUFFER_STORE_SHORT;
6579   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
6580   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
6581                                      M->getMemOperand());
6582 }
6583 
6584 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
6585                                  ISD::LoadExtType ExtType, SDValue Op,
6586                                  const SDLoc &SL, EVT VT) {
6587   if (VT.bitsLT(Op.getValueType()))
6588     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
6589 
6590   switch (ExtType) {
6591   case ISD::SEXTLOAD:
6592     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
6593   case ISD::ZEXTLOAD:
6594     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
6595   case ISD::EXTLOAD:
6596     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
6597   case ISD::NON_EXTLOAD:
6598     return Op;
6599   }
6600 
6601   llvm_unreachable("invalid ext type");
6602 }
6603 
6604 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
6605   SelectionDAG &DAG = DCI.DAG;
6606   if (Ld->getAlignment() < 4 || Ld->isDivergent())
6607     return SDValue();
6608 
6609   // FIXME: Constant loads should all be marked invariant.
6610   unsigned AS = Ld->getAddressSpace();
6611   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
6612       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
6613       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
6614     return SDValue();
6615 
6616   // Don't do this early, since it may interfere with adjacent load merging for
6617   // illegal types. We can avoid losing alignment information for exotic types
6618   // pre-legalize.
6619   EVT MemVT = Ld->getMemoryVT();
6620   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
6621       MemVT.getSizeInBits() >= 32)
6622     return SDValue();
6623 
6624   SDLoc SL(Ld);
6625 
6626   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
6627          "unexpected vector extload");
6628 
6629   // TODO: Drop only high part of range.
6630   SDValue Ptr = Ld->getBasePtr();
6631   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
6632                                 MVT::i32, SL, Ld->getChain(), Ptr,
6633                                 Ld->getOffset(),
6634                                 Ld->getPointerInfo(), MVT::i32,
6635                                 Ld->getAlignment(),
6636                                 Ld->getMemOperand()->getFlags(),
6637                                 Ld->getAAInfo(),
6638                                 nullptr); // Drop ranges
6639 
6640   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
6641   if (MemVT.isFloatingPoint()) {
6642     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
6643            "unexpected fp extload");
6644     TruncVT = MemVT.changeTypeToInteger();
6645   }
6646 
6647   SDValue Cvt = NewLoad;
6648   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
6649     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
6650                       DAG.getValueType(TruncVT));
6651   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
6652              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
6653     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
6654   } else {
6655     assert(Ld->getExtensionType() == ISD::EXTLOAD);
6656   }
6657 
6658   EVT VT = Ld->getValueType(0);
6659   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6660 
6661   DCI.AddToWorklist(Cvt.getNode());
6662 
6663   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
6664   // the appropriate extension from the 32-bit load.
6665   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
6666   DCI.AddToWorklist(Cvt.getNode());
6667 
6668   // Handle conversion back to floating point if necessary.
6669   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
6670 
6671   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
6672 }
6673 
6674 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6675   SDLoc DL(Op);
6676   LoadSDNode *Load = cast<LoadSDNode>(Op);
6677   ISD::LoadExtType ExtType = Load->getExtensionType();
6678   EVT MemVT = Load->getMemoryVT();
6679 
6680   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
6681     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
6682       return SDValue();
6683 
6684     // FIXME: Copied from PPC
6685     // First, load into 32 bits, then truncate to 1 bit.
6686 
6687     SDValue Chain = Load->getChain();
6688     SDValue BasePtr = Load->getBasePtr();
6689     MachineMemOperand *MMO = Load->getMemOperand();
6690 
6691     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
6692 
6693     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
6694                                    BasePtr, RealMemVT, MMO);
6695 
6696     if (!MemVT.isVector()) {
6697       SDValue Ops[] = {
6698         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
6699         NewLD.getValue(1)
6700       };
6701 
6702       return DAG.getMergeValues(Ops, DL);
6703     }
6704 
6705     SmallVector<SDValue, 3> Elts;
6706     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
6707       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
6708                                 DAG.getConstant(I, DL, MVT::i32));
6709 
6710       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
6711     }
6712 
6713     SDValue Ops[] = {
6714       DAG.getBuildVector(MemVT, DL, Elts),
6715       NewLD.getValue(1)
6716     };
6717 
6718     return DAG.getMergeValues(Ops, DL);
6719   }
6720 
6721   if (!MemVT.isVector())
6722     return SDValue();
6723 
6724   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
6725          "Custom lowering for non-i32 vectors hasn't been implemented.");
6726 
6727   unsigned Alignment = Load->getAlignment();
6728   unsigned AS = Load->getAddressSpace();
6729   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
6730                           AS, Alignment)) {
6731     SDValue Ops[2];
6732     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
6733     return DAG.getMergeValues(Ops, DL);
6734   }
6735   if (Subtarget->hasLDSMisalignedBug() &&
6736       AS == AMDGPUAS::FLAT_ADDRESS &&
6737       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
6738     return SplitVectorLoad(Op, DAG);
6739   }
6740 
6741   MachineFunction &MF = DAG.getMachineFunction();
6742   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
6743   // If there is a possibilty that flat instruction access scratch memory
6744   // then we need to use the same legalization rules we use for private.
6745   if (AS == AMDGPUAS::FLAT_ADDRESS)
6746     AS = MFI->hasFlatScratchInit() ?
6747          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
6748 
6749   unsigned NumElements = MemVT.getVectorNumElements();
6750 
6751   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6752       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
6753     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
6754       if (MemVT.isPow2VectorType())
6755         return SDValue();
6756       if (NumElements == 3)
6757         return WidenVectorLoad(Op, DAG);
6758       return SplitVectorLoad(Op, DAG);
6759     }
6760     // Non-uniform loads will be selected to MUBUF instructions, so they
6761     // have the same legalization requirements as global and private
6762     // loads.
6763     //
6764   }
6765 
6766   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6767       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
6768       AS == AMDGPUAS::GLOBAL_ADDRESS) {
6769     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
6770         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
6771         Alignment >= 4 && NumElements < 32) {
6772       if (MemVT.isPow2VectorType())
6773         return SDValue();
6774       if (NumElements == 3)
6775         return WidenVectorLoad(Op, DAG);
6776       return SplitVectorLoad(Op, DAG);
6777     }
6778     // Non-uniform loads will be selected to MUBUF instructions, so they
6779     // have the same legalization requirements as global and private
6780     // loads.
6781     //
6782   }
6783   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6784       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
6785       AS == AMDGPUAS::GLOBAL_ADDRESS ||
6786       AS == AMDGPUAS::FLAT_ADDRESS) {
6787     if (NumElements > 4)
6788       return SplitVectorLoad(Op, DAG);
6789     // v3 loads not supported on SI.
6790     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
6791       return WidenVectorLoad(Op, DAG);
6792     // v3 and v4 loads are supported for private and global memory.
6793     return SDValue();
6794   }
6795   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
6796     // Depending on the setting of the private_element_size field in the
6797     // resource descriptor, we can only make private accesses up to a certain
6798     // size.
6799     switch (Subtarget->getMaxPrivateElementSize()) {
6800     case 4:
6801       return scalarizeVectorLoad(Load, DAG);
6802     case 8:
6803       if (NumElements > 2)
6804         return SplitVectorLoad(Op, DAG);
6805       return SDValue();
6806     case 16:
6807       // Same as global/flat
6808       if (NumElements > 4)
6809         return SplitVectorLoad(Op, DAG);
6810       // v3 loads not supported on SI.
6811       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
6812         return WidenVectorLoad(Op, DAG);
6813       return SDValue();
6814     default:
6815       llvm_unreachable("unsupported private_element_size");
6816     }
6817   } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
6818     // Use ds_read_b128 if possible.
6819     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
6820         MemVT.getStoreSize() == 16)
6821       return SDValue();
6822 
6823     if (NumElements > 2)
6824       return SplitVectorLoad(Op, DAG);
6825 
6826     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
6827     // address is negative, then the instruction is incorrectly treated as
6828     // out-of-bounds even if base + offsets is in bounds. Split vectorized
6829     // loads here to avoid emitting ds_read2_b32. We may re-combine the
6830     // load later in the SILoadStoreOptimizer.
6831     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
6832         NumElements == 2 && MemVT.getStoreSize() == 8 &&
6833         Load->getAlignment() < 8) {
6834       return SplitVectorLoad(Op, DAG);
6835     }
6836   }
6837   return SDValue();
6838 }
6839 
6840 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6841   EVT VT = Op.getValueType();
6842   assert(VT.getSizeInBits() == 64);
6843 
6844   SDLoc DL(Op);
6845   SDValue Cond = Op.getOperand(0);
6846 
6847   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
6848   SDValue One = DAG.getConstant(1, DL, MVT::i32);
6849 
6850   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
6851   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
6852 
6853   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
6854   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
6855 
6856   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
6857 
6858   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
6859   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
6860 
6861   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
6862 
6863   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
6864   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6865 }
6866 
6867 // Catch division cases where we can use shortcuts with rcp and rsq
6868 // instructions.
6869 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
6870                                               SelectionDAG &DAG) const {
6871   SDLoc SL(Op);
6872   SDValue LHS = Op.getOperand(0);
6873   SDValue RHS = Op.getOperand(1);
6874   EVT VT = Op.getValueType();
6875   const SDNodeFlags Flags = Op->getFlags();
6876   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
6877 
6878   if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
6879     return SDValue();
6880 
6881   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
6882     if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
6883       if (CLHS->isExactlyValue(1.0)) {
6884         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
6885         // the CI documentation has a worst case error of 1 ulp.
6886         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
6887         // use it as long as we aren't trying to use denormals.
6888         //
6889         // v_rcp_f16 and v_rsq_f16 DO support denormals.
6890 
6891         // 1.0 / sqrt(x) -> rsq(x)
6892 
6893         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
6894         // error seems really high at 2^29 ULP.
6895         if (RHS.getOpcode() == ISD::FSQRT)
6896           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
6897 
6898         // 1.0 / x -> rcp(x)
6899         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
6900       }
6901 
6902       // Same as for 1.0, but expand the sign out of the constant.
6903       if (CLHS->isExactlyValue(-1.0)) {
6904         // -1.0 / x -> rcp (fneg x)
6905         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
6906         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
6907       }
6908     }
6909   }
6910 
6911   if (Unsafe) {
6912     // Turn into multiply by the reciprocal.
6913     // x / y -> x * (1.0 / y)
6914     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
6915     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
6916   }
6917 
6918   return SDValue();
6919 }
6920 
6921 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
6922                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
6923   if (GlueChain->getNumValues() <= 1) {
6924     return DAG.getNode(Opcode, SL, VT, A, B);
6925   }
6926 
6927   assert(GlueChain->getNumValues() == 3);
6928 
6929   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
6930   switch (Opcode) {
6931   default: llvm_unreachable("no chain equivalent for opcode");
6932   case ISD::FMUL:
6933     Opcode = AMDGPUISD::FMUL_W_CHAIN;
6934     break;
6935   }
6936 
6937   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
6938                      GlueChain.getValue(2));
6939 }
6940 
6941 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
6942                            EVT VT, SDValue A, SDValue B, SDValue C,
6943                            SDValue GlueChain) {
6944   if (GlueChain->getNumValues() <= 1) {
6945     return DAG.getNode(Opcode, SL, VT, A, B, C);
6946   }
6947 
6948   assert(GlueChain->getNumValues() == 3);
6949 
6950   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
6951   switch (Opcode) {
6952   default: llvm_unreachable("no chain equivalent for opcode");
6953   case ISD::FMA:
6954     Opcode = AMDGPUISD::FMA_W_CHAIN;
6955     break;
6956   }
6957 
6958   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
6959                      GlueChain.getValue(2));
6960 }
6961 
6962 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
6963   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
6964     return FastLowered;
6965 
6966   SDLoc SL(Op);
6967   SDValue Src0 = Op.getOperand(0);
6968   SDValue Src1 = Op.getOperand(1);
6969 
6970   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
6971   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
6972 
6973   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
6974   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
6975 
6976   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
6977   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
6978 
6979   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
6980 }
6981 
6982 // Faster 2.5 ULP division that does not support denormals.
6983 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
6984   SDLoc SL(Op);
6985   SDValue LHS = Op.getOperand(1);
6986   SDValue RHS = Op.getOperand(2);
6987 
6988   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
6989 
6990   const APFloat K0Val(BitsToFloat(0x6f800000));
6991   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
6992 
6993   const APFloat K1Val(BitsToFloat(0x2f800000));
6994   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
6995 
6996   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
6997 
6998   EVT SetCCVT =
6999     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7000 
7001   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7002 
7003   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7004 
7005   // TODO: Should this propagate fast-math-flags?
7006   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7007 
7008   // rcp does not support denormals.
7009   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7010 
7011   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7012 
7013   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7014 }
7015 
7016 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7017   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7018     return FastLowered;
7019 
7020   SDLoc SL(Op);
7021   SDValue LHS = Op.getOperand(0);
7022   SDValue RHS = Op.getOperand(1);
7023 
7024   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7025 
7026   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7027 
7028   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7029                                           RHS, RHS, LHS);
7030   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7031                                         LHS, RHS, LHS);
7032 
7033   // Denominator is scaled to not be denormal, so using rcp is ok.
7034   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7035                                   DenominatorScaled);
7036   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7037                                      DenominatorScaled);
7038 
7039   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7040                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7041                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7042 
7043   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7044 
7045   if (!Subtarget->hasFP32Denormals()) {
7046     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7047     const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7048                                                       SL, MVT::i32);
7049     SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7050                                        DAG.getEntryNode(),
7051                                        EnableDenormValue, BitField);
7052     SDValue Ops[3] = {
7053       NegDivScale0,
7054       EnableDenorm.getValue(0),
7055       EnableDenorm.getValue(1)
7056     };
7057 
7058     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7059   }
7060 
7061   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7062                              ApproxRcp, One, NegDivScale0);
7063 
7064   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7065                              ApproxRcp, Fma0);
7066 
7067   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7068                            Fma1, Fma1);
7069 
7070   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7071                              NumeratorScaled, Mul);
7072 
7073   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7074 
7075   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7076                              NumeratorScaled, Fma3);
7077 
7078   if (!Subtarget->hasFP32Denormals()) {
7079     const SDValue DisableDenormValue =
7080         DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7081     SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7082                                         Fma4.getValue(1),
7083                                         DisableDenormValue,
7084                                         BitField,
7085                                         Fma4.getValue(2));
7086 
7087     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7088                                       DisableDenorm, DAG.getRoot());
7089     DAG.setRoot(OutputChain);
7090   }
7091 
7092   SDValue Scale = NumeratorScaled.getValue(1);
7093   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7094                              Fma4, Fma1, Fma3, Scale);
7095 
7096   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7097 }
7098 
7099 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7100   if (DAG.getTarget().Options.UnsafeFPMath)
7101     return lowerFastUnsafeFDIV(Op, DAG);
7102 
7103   SDLoc SL(Op);
7104   SDValue X = Op.getOperand(0);
7105   SDValue Y = Op.getOperand(1);
7106 
7107   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7108 
7109   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7110 
7111   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7112 
7113   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7114 
7115   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7116 
7117   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7118 
7119   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7120 
7121   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7122 
7123   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7124 
7125   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7126   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7127 
7128   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7129                              NegDivScale0, Mul, DivScale1);
7130 
7131   SDValue Scale;
7132 
7133   if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
7134     // Workaround a hardware bug on SI where the condition output from div_scale
7135     // is not usable.
7136 
7137     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7138 
7139     // Figure out if the scale to use for div_fmas.
7140     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7141     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7142     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7143     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7144 
7145     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7146     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7147 
7148     SDValue Scale0Hi
7149       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7150     SDValue Scale1Hi
7151       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7152 
7153     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7154     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7155     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7156   } else {
7157     Scale = DivScale1.getValue(1);
7158   }
7159 
7160   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7161                              Fma4, Fma3, Mul, Scale);
7162 
7163   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7164 }
7165 
7166 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7167   EVT VT = Op.getValueType();
7168 
7169   if (VT == MVT::f32)
7170     return LowerFDIV32(Op, DAG);
7171 
7172   if (VT == MVT::f64)
7173     return LowerFDIV64(Op, DAG);
7174 
7175   if (VT == MVT::f16)
7176     return LowerFDIV16(Op, DAG);
7177 
7178   llvm_unreachable("Unexpected type for fdiv");
7179 }
7180 
7181 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7182   SDLoc DL(Op);
7183   StoreSDNode *Store = cast<StoreSDNode>(Op);
7184   EVT VT = Store->getMemoryVT();
7185 
7186   if (VT == MVT::i1) {
7187     return DAG.getTruncStore(Store->getChain(), DL,
7188        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7189        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7190   }
7191 
7192   assert(VT.isVector() &&
7193          Store->getValue().getValueType().getScalarType() == MVT::i32);
7194 
7195   unsigned AS = Store->getAddressSpace();
7196   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7197                           AS, Store->getAlignment())) {
7198     return expandUnalignedStore(Store, DAG);
7199   }
7200 
7201   if (Subtarget->hasLDSMisalignedBug() &&
7202       AS == AMDGPUAS::FLAT_ADDRESS &&
7203       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7204     return SplitVectorStore(Op, DAG);
7205   }
7206 
7207   MachineFunction &MF = DAG.getMachineFunction();
7208   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7209   // If there is a possibilty that flat instruction access scratch memory
7210   // then we need to use the same legalization rules we use for private.
7211   if (AS == AMDGPUAS::FLAT_ADDRESS)
7212     AS = MFI->hasFlatScratchInit() ?
7213          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7214 
7215   unsigned NumElements = VT.getVectorNumElements();
7216   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7217       AS == AMDGPUAS::FLAT_ADDRESS) {
7218     if (NumElements > 4)
7219       return SplitVectorStore(Op, DAG);
7220     // v3 stores not supported on SI.
7221     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7222       return SplitVectorStore(Op, DAG);
7223     return SDValue();
7224   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7225     switch (Subtarget->getMaxPrivateElementSize()) {
7226     case 4:
7227       return scalarizeVectorStore(Store, DAG);
7228     case 8:
7229       if (NumElements > 2)
7230         return SplitVectorStore(Op, DAG);
7231       return SDValue();
7232     case 16:
7233       if (NumElements > 4 || NumElements == 3)
7234         return SplitVectorStore(Op, DAG);
7235       return SDValue();
7236     default:
7237       llvm_unreachable("unsupported private_element_size");
7238     }
7239   } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
7240     // Use ds_write_b128 if possible.
7241     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7242         VT.getStoreSize() == 16 && NumElements != 3)
7243       return SDValue();
7244 
7245     if (NumElements > 2)
7246       return SplitVectorStore(Op, DAG);
7247 
7248     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7249     // address is negative, then the instruction is incorrectly treated as
7250     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7251     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7252     // store later in the SILoadStoreOptimizer.
7253     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7254         NumElements == 2 && VT.getStoreSize() == 8 &&
7255         Store->getAlignment() < 8) {
7256       return SplitVectorStore(Op, DAG);
7257     }
7258 
7259     return SDValue();
7260   } else {
7261     llvm_unreachable("unhandled address space");
7262   }
7263 }
7264 
7265 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7266   SDLoc DL(Op);
7267   EVT VT = Op.getValueType();
7268   SDValue Arg = Op.getOperand(0);
7269   SDValue TrigVal;
7270 
7271   // TODO: Should this propagate fast-math-flags?
7272 
7273   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7274 
7275   if (Subtarget->hasTrigReducedRange()) {
7276     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7277     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7278   } else {
7279     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7280   }
7281 
7282   switch (Op.getOpcode()) {
7283   case ISD::FCOS:
7284     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7285   case ISD::FSIN:
7286     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7287   default:
7288     llvm_unreachable("Wrong trig opcode");
7289   }
7290 }
7291 
7292 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7293   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7294   assert(AtomicNode->isCompareAndSwap());
7295   unsigned AS = AtomicNode->getAddressSpace();
7296 
7297   // No custom lowering required for local address space
7298   if (!isFlatGlobalAddrSpace(AS))
7299     return Op;
7300 
7301   // Non-local address space requires custom lowering for atomic compare
7302   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7303   SDLoc DL(Op);
7304   SDValue ChainIn = Op.getOperand(0);
7305   SDValue Addr = Op.getOperand(1);
7306   SDValue Old = Op.getOperand(2);
7307   SDValue New = Op.getOperand(3);
7308   EVT VT = Op.getValueType();
7309   MVT SimpleVT = VT.getSimpleVT();
7310   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7311 
7312   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
7313   SDValue Ops[] = { ChainIn, Addr, NewOld };
7314 
7315   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7316                                  Ops, VT, AtomicNode->getMemOperand());
7317 }
7318 
7319 //===----------------------------------------------------------------------===//
7320 // Custom DAG optimizations
7321 //===----------------------------------------------------------------------===//
7322 
7323 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
7324                                                      DAGCombinerInfo &DCI) const {
7325   EVT VT = N->getValueType(0);
7326   EVT ScalarVT = VT.getScalarType();
7327   if (ScalarVT != MVT::f32)
7328     return SDValue();
7329 
7330   SelectionDAG &DAG = DCI.DAG;
7331   SDLoc DL(N);
7332 
7333   SDValue Src = N->getOperand(0);
7334   EVT SrcVT = Src.getValueType();
7335 
7336   // TODO: We could try to match extracting the higher bytes, which would be
7337   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7338   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7339   // about in practice.
7340   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
7341     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7342       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7343       DCI.AddToWorklist(Cvt.getNode());
7344       return Cvt;
7345     }
7346   }
7347 
7348   return SDValue();
7349 }
7350 
7351 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7352 
7353 // This is a variant of
7354 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7355 //
7356 // The normal DAG combiner will do this, but only if the add has one use since
7357 // that would increase the number of instructions.
7358 //
7359 // This prevents us from seeing a constant offset that can be folded into a
7360 // memory instruction's addressing mode. If we know the resulting add offset of
7361 // a pointer can be folded into an addressing offset, we can replace the pointer
7362 // operand with the add of new constant offset. This eliminates one of the uses,
7363 // and may allow the remaining use to also be simplified.
7364 //
7365 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7366                                                unsigned AddrSpace,
7367                                                EVT MemVT,
7368                                                DAGCombinerInfo &DCI) const {
7369   SDValue N0 = N->getOperand(0);
7370   SDValue N1 = N->getOperand(1);
7371 
7372   // We only do this to handle cases where it's profitable when there are
7373   // multiple uses of the add, so defer to the standard combine.
7374   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
7375       N0->hasOneUse())
7376     return SDValue();
7377 
7378   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
7379   if (!CN1)
7380     return SDValue();
7381 
7382   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7383   if (!CAdd)
7384     return SDValue();
7385 
7386   // If the resulting offset is too large, we can't fold it into the addressing
7387   // mode offset.
7388   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
7389   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
7390 
7391   AddrMode AM;
7392   AM.HasBaseReg = true;
7393   AM.BaseOffs = Offset.getSExtValue();
7394   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
7395     return SDValue();
7396 
7397   SelectionDAG &DAG = DCI.DAG;
7398   SDLoc SL(N);
7399   EVT VT = N->getValueType(0);
7400 
7401   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
7402   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
7403 
7404   SDNodeFlags Flags;
7405   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
7406                           (N0.getOpcode() == ISD::OR ||
7407                            N0->getFlags().hasNoUnsignedWrap()));
7408 
7409   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
7410 }
7411 
7412 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
7413                                                   DAGCombinerInfo &DCI) const {
7414   SDValue Ptr = N->getBasePtr();
7415   SelectionDAG &DAG = DCI.DAG;
7416   SDLoc SL(N);
7417 
7418   // TODO: We could also do this for multiplies.
7419   if (Ptr.getOpcode() == ISD::SHL) {
7420     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
7421                                           N->getMemoryVT(), DCI);
7422     if (NewPtr) {
7423       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
7424 
7425       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
7426       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
7427     }
7428   }
7429 
7430   return SDValue();
7431 }
7432 
7433 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
7434   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
7435          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
7436          (Opc == ISD::XOR && Val == 0);
7437 }
7438 
7439 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
7440 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
7441 // integer combine opportunities since most 64-bit operations are decomposed
7442 // this way.  TODO: We won't want this for SALU especially if it is an inline
7443 // immediate.
7444 SDValue SITargetLowering::splitBinaryBitConstantOp(
7445   DAGCombinerInfo &DCI,
7446   const SDLoc &SL,
7447   unsigned Opc, SDValue LHS,
7448   const ConstantSDNode *CRHS) const {
7449   uint64_t Val = CRHS->getZExtValue();
7450   uint32_t ValLo = Lo_32(Val);
7451   uint32_t ValHi = Hi_32(Val);
7452   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7453 
7454     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
7455          bitOpWithConstantIsReducible(Opc, ValHi)) ||
7456         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
7457     // If we need to materialize a 64-bit immediate, it will be split up later
7458     // anyway. Avoid creating the harder to understand 64-bit immediate
7459     // materialization.
7460     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
7461   }
7462 
7463   return SDValue();
7464 }
7465 
7466 // Returns true if argument is a boolean value which is not serialized into
7467 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
7468 static bool isBoolSGPR(SDValue V) {
7469   if (V.getValueType() != MVT::i1)
7470     return false;
7471   switch (V.getOpcode()) {
7472   default: break;
7473   case ISD::SETCC:
7474   case ISD::AND:
7475   case ISD::OR:
7476   case ISD::XOR:
7477   case AMDGPUISD::FP_CLASS:
7478     return true;
7479   }
7480   return false;
7481 }
7482 
7483 // If a constant has all zeroes or all ones within each byte return it.
7484 // Otherwise return 0.
7485 static uint32_t getConstantPermuteMask(uint32_t C) {
7486   // 0xff for any zero byte in the mask
7487   uint32_t ZeroByteMask = 0;
7488   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
7489   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
7490   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
7491   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
7492   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
7493   if ((NonZeroByteMask & C) != NonZeroByteMask)
7494     return 0; // Partial bytes selected.
7495   return C;
7496 }
7497 
7498 // Check if a node selects whole bytes from its operand 0 starting at a byte
7499 // boundary while masking the rest. Returns select mask as in the v_perm_b32
7500 // or -1 if not succeeded.
7501 // Note byte select encoding:
7502 // value 0-3 selects corresponding source byte;
7503 // value 0xc selects zero;
7504 // value 0xff selects 0xff.
7505 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
7506   assert(V.getValueSizeInBits() == 32);
7507 
7508   if (V.getNumOperands() != 2)
7509     return ~0;
7510 
7511   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
7512   if (!N1)
7513     return ~0;
7514 
7515   uint32_t C = N1->getZExtValue();
7516 
7517   switch (V.getOpcode()) {
7518   default:
7519     break;
7520   case ISD::AND:
7521     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7522       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
7523     }
7524     break;
7525 
7526   case ISD::OR:
7527     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7528       return (0x03020100 & ~ConstMask) | ConstMask;
7529     }
7530     break;
7531 
7532   case ISD::SHL:
7533     if (C % 8)
7534       return ~0;
7535 
7536     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
7537 
7538   case ISD::SRL:
7539     if (C % 8)
7540       return ~0;
7541 
7542     return uint32_t(0x0c0c0c0c03020100ull >> C);
7543   }
7544 
7545   return ~0;
7546 }
7547 
7548 SDValue SITargetLowering::performAndCombine(SDNode *N,
7549                                             DAGCombinerInfo &DCI) const {
7550   if (DCI.isBeforeLegalize())
7551     return SDValue();
7552 
7553   SelectionDAG &DAG = DCI.DAG;
7554   EVT VT = N->getValueType(0);
7555   SDValue LHS = N->getOperand(0);
7556   SDValue RHS = N->getOperand(1);
7557 
7558 
7559   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
7560   if (VT == MVT::i64 && CRHS) {
7561     if (SDValue Split
7562         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
7563       return Split;
7564   }
7565 
7566   if (CRHS && VT == MVT::i32) {
7567     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
7568     // nb = number of trailing zeroes in mask
7569     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
7570     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
7571     uint64_t Mask = CRHS->getZExtValue();
7572     unsigned Bits = countPopulation(Mask);
7573     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
7574         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
7575       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
7576         unsigned Shift = CShift->getZExtValue();
7577         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
7578         unsigned Offset = NB + Shift;
7579         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
7580           SDLoc SL(N);
7581           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
7582                                     LHS->getOperand(0),
7583                                     DAG.getConstant(Offset, SL, MVT::i32),
7584                                     DAG.getConstant(Bits, SL, MVT::i32));
7585           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7586           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
7587                                     DAG.getValueType(NarrowVT));
7588           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
7589                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
7590           return Shl;
7591         }
7592       }
7593     }
7594 
7595     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
7596     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
7597         isa<ConstantSDNode>(LHS.getOperand(2))) {
7598       uint32_t Sel = getConstantPermuteMask(Mask);
7599       if (!Sel)
7600         return SDValue();
7601 
7602       // Select 0xc for all zero bytes
7603       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
7604       SDLoc DL(N);
7605       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
7606                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
7607     }
7608   }
7609 
7610   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
7611   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
7612   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
7613     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7614     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
7615 
7616     SDValue X = LHS.getOperand(0);
7617     SDValue Y = RHS.getOperand(0);
7618     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
7619       return SDValue();
7620 
7621     if (LCC == ISD::SETO) {
7622       if (X != LHS.getOperand(1))
7623         return SDValue();
7624 
7625       if (RCC == ISD::SETUNE) {
7626         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
7627         if (!C1 || !C1->isInfinity() || C1->isNegative())
7628           return SDValue();
7629 
7630         const uint32_t Mask = SIInstrFlags::N_NORMAL |
7631                               SIInstrFlags::N_SUBNORMAL |
7632                               SIInstrFlags::N_ZERO |
7633                               SIInstrFlags::P_ZERO |
7634                               SIInstrFlags::P_SUBNORMAL |
7635                               SIInstrFlags::P_NORMAL;
7636 
7637         static_assert(((~(SIInstrFlags::S_NAN |
7638                           SIInstrFlags::Q_NAN |
7639                           SIInstrFlags::N_INFINITY |
7640                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
7641                       "mask not equal");
7642 
7643         SDLoc DL(N);
7644         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
7645                            X, DAG.getConstant(Mask, DL, MVT::i32));
7646       }
7647     }
7648   }
7649 
7650   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
7651     std::swap(LHS, RHS);
7652 
7653   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
7654       RHS.hasOneUse()) {
7655     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7656     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
7657     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
7658     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7659     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
7660         (RHS.getOperand(0) == LHS.getOperand(0) &&
7661          LHS.getOperand(0) == LHS.getOperand(1))) {
7662       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
7663       unsigned NewMask = LCC == ISD::SETO ?
7664         Mask->getZExtValue() & ~OrdMask :
7665         Mask->getZExtValue() & OrdMask;
7666 
7667       SDLoc DL(N);
7668       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
7669                          DAG.getConstant(NewMask, DL, MVT::i32));
7670     }
7671   }
7672 
7673   if (VT == MVT::i32 &&
7674       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
7675     // and x, (sext cc from i1) => select cc, x, 0
7676     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
7677       std::swap(LHS, RHS);
7678     if (isBoolSGPR(RHS.getOperand(0)))
7679       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
7680                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
7681   }
7682 
7683   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
7684   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7685   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
7686       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
7687     uint32_t LHSMask = getPermuteMask(DAG, LHS);
7688     uint32_t RHSMask = getPermuteMask(DAG, RHS);
7689     if (LHSMask != ~0u && RHSMask != ~0u) {
7690       // Canonicalize the expression in an attempt to have fewer unique masks
7691       // and therefore fewer registers used to hold the masks.
7692       if (LHSMask > RHSMask) {
7693         std::swap(LHSMask, RHSMask);
7694         std::swap(LHS, RHS);
7695       }
7696 
7697       // Select 0xc for each lane used from source operand. Zero has 0xc mask
7698       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
7699       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7700       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7701 
7702       // Check of we need to combine values from two sources within a byte.
7703       if (!(LHSUsedLanes & RHSUsedLanes) &&
7704           // If we select high and lower word keep it for SDWA.
7705           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
7706           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
7707         // Each byte in each mask is either selector mask 0-3, or has higher
7708         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
7709         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
7710         // mask which is not 0xff wins. By anding both masks we have a correct
7711         // result except that 0x0c shall be corrected to give 0x0c only.
7712         uint32_t Mask = LHSMask & RHSMask;
7713         for (unsigned I = 0; I < 32; I += 8) {
7714           uint32_t ByteSel = 0xff << I;
7715           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
7716             Mask &= (0x0c << I) & 0xffffffff;
7717         }
7718 
7719         // Add 4 to each active LHS lane. It will not affect any existing 0xff
7720         // or 0x0c.
7721         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
7722         SDLoc DL(N);
7723 
7724         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
7725                            LHS.getOperand(0), RHS.getOperand(0),
7726                            DAG.getConstant(Sel, DL, MVT::i32));
7727       }
7728     }
7729   }
7730 
7731   return SDValue();
7732 }
7733 
7734 SDValue SITargetLowering::performOrCombine(SDNode *N,
7735                                            DAGCombinerInfo &DCI) const {
7736   SelectionDAG &DAG = DCI.DAG;
7737   SDValue LHS = N->getOperand(0);
7738   SDValue RHS = N->getOperand(1);
7739 
7740   EVT VT = N->getValueType(0);
7741   if (VT == MVT::i1) {
7742     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
7743     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
7744         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
7745       SDValue Src = LHS.getOperand(0);
7746       if (Src != RHS.getOperand(0))
7747         return SDValue();
7748 
7749       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
7750       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7751       if (!CLHS || !CRHS)
7752         return SDValue();
7753 
7754       // Only 10 bits are used.
7755       static const uint32_t MaxMask = 0x3ff;
7756 
7757       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
7758       SDLoc DL(N);
7759       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
7760                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
7761     }
7762 
7763     return SDValue();
7764   }
7765 
7766   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
7767   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
7768       LHS.getOpcode() == AMDGPUISD::PERM &&
7769       isa<ConstantSDNode>(LHS.getOperand(2))) {
7770     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
7771     if (!Sel)
7772       return SDValue();
7773 
7774     Sel |= LHS.getConstantOperandVal(2);
7775     SDLoc DL(N);
7776     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
7777                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
7778   }
7779 
7780   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
7781   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7782   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
7783       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
7784     uint32_t LHSMask = getPermuteMask(DAG, LHS);
7785     uint32_t RHSMask = getPermuteMask(DAG, RHS);
7786     if (LHSMask != ~0u && RHSMask != ~0u) {
7787       // Canonicalize the expression in an attempt to have fewer unique masks
7788       // and therefore fewer registers used to hold the masks.
7789       if (LHSMask > RHSMask) {
7790         std::swap(LHSMask, RHSMask);
7791         std::swap(LHS, RHS);
7792       }
7793 
7794       // Select 0xc for each lane used from source operand. Zero has 0xc mask
7795       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
7796       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7797       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7798 
7799       // Check of we need to combine values from two sources within a byte.
7800       if (!(LHSUsedLanes & RHSUsedLanes) &&
7801           // If we select high and lower word keep it for SDWA.
7802           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
7803           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
7804         // Kill zero bytes selected by other mask. Zero value is 0xc.
7805         LHSMask &= ~RHSUsedLanes;
7806         RHSMask &= ~LHSUsedLanes;
7807         // Add 4 to each active LHS lane
7808         LHSMask |= LHSUsedLanes & 0x04040404;
7809         // Combine masks
7810         uint32_t Sel = LHSMask | RHSMask;
7811         SDLoc DL(N);
7812 
7813         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
7814                            LHS.getOperand(0), RHS.getOperand(0),
7815                            DAG.getConstant(Sel, DL, MVT::i32));
7816       }
7817     }
7818   }
7819 
7820   if (VT != MVT::i64)
7821     return SDValue();
7822 
7823   // TODO: This could be a generic combine with a predicate for extracting the
7824   // high half of an integer being free.
7825 
7826   // (or i64:x, (zero_extend i32:y)) ->
7827   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
7828   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
7829       RHS.getOpcode() != ISD::ZERO_EXTEND)
7830     std::swap(LHS, RHS);
7831 
7832   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
7833     SDValue ExtSrc = RHS.getOperand(0);
7834     EVT SrcVT = ExtSrc.getValueType();
7835     if (SrcVT == MVT::i32) {
7836       SDLoc SL(N);
7837       SDValue LowLHS, HiBits;
7838       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
7839       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
7840 
7841       DCI.AddToWorklist(LowOr.getNode());
7842       DCI.AddToWorklist(HiBits.getNode());
7843 
7844       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
7845                                 LowOr, HiBits);
7846       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
7847     }
7848   }
7849 
7850   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
7851   if (CRHS) {
7852     if (SDValue Split
7853           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
7854       return Split;
7855   }
7856 
7857   return SDValue();
7858 }
7859 
7860 SDValue SITargetLowering::performXorCombine(SDNode *N,
7861                                             DAGCombinerInfo &DCI) const {
7862   EVT VT = N->getValueType(0);
7863   if (VT != MVT::i64)
7864     return SDValue();
7865 
7866   SDValue LHS = N->getOperand(0);
7867   SDValue RHS = N->getOperand(1);
7868 
7869   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
7870   if (CRHS) {
7871     if (SDValue Split
7872           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
7873       return Split;
7874   }
7875 
7876   return SDValue();
7877 }
7878 
7879 // Instructions that will be lowered with a final instruction that zeros the
7880 // high result bits.
7881 // XXX - probably only need to list legal operations.
7882 static bool fp16SrcZerosHighBits(unsigned Opc) {
7883   switch (Opc) {
7884   case ISD::FADD:
7885   case ISD::FSUB:
7886   case ISD::FMUL:
7887   case ISD::FDIV:
7888   case ISD::FREM:
7889   case ISD::FMA:
7890   case ISD::FMAD:
7891   case ISD::FCANONICALIZE:
7892   case ISD::FP_ROUND:
7893   case ISD::UINT_TO_FP:
7894   case ISD::SINT_TO_FP:
7895   case ISD::FABS:
7896     // Fabs is lowered to a bit operation, but it's an and which will clear the
7897     // high bits anyway.
7898   case ISD::FSQRT:
7899   case ISD::FSIN:
7900   case ISD::FCOS:
7901   case ISD::FPOWI:
7902   case ISD::FPOW:
7903   case ISD::FLOG:
7904   case ISD::FLOG2:
7905   case ISD::FLOG10:
7906   case ISD::FEXP:
7907   case ISD::FEXP2:
7908   case ISD::FCEIL:
7909   case ISD::FTRUNC:
7910   case ISD::FRINT:
7911   case ISD::FNEARBYINT:
7912   case ISD::FROUND:
7913   case ISD::FFLOOR:
7914   case ISD::FMINNUM:
7915   case ISD::FMAXNUM:
7916   case AMDGPUISD::FRACT:
7917   case AMDGPUISD::CLAMP:
7918   case AMDGPUISD::COS_HW:
7919   case AMDGPUISD::SIN_HW:
7920   case AMDGPUISD::FMIN3:
7921   case AMDGPUISD::FMAX3:
7922   case AMDGPUISD::FMED3:
7923   case AMDGPUISD::FMAD_FTZ:
7924   case AMDGPUISD::RCP:
7925   case AMDGPUISD::RSQ:
7926   case AMDGPUISD::RCP_IFLAG:
7927   case AMDGPUISD::LDEXP:
7928     return true;
7929   default:
7930     // fcopysign, select and others may be lowered to 32-bit bit operations
7931     // which don't zero the high bits.
7932     return false;
7933   }
7934 }
7935 
7936 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
7937                                                    DAGCombinerInfo &DCI) const {
7938   if (!Subtarget->has16BitInsts() ||
7939       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7940     return SDValue();
7941 
7942   EVT VT = N->getValueType(0);
7943   if (VT != MVT::i32)
7944     return SDValue();
7945 
7946   SDValue Src = N->getOperand(0);
7947   if (Src.getValueType() != MVT::i16)
7948     return SDValue();
7949 
7950   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
7951   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
7952   if (Src.getOpcode() == ISD::BITCAST) {
7953     SDValue BCSrc = Src.getOperand(0);
7954     if (BCSrc.getValueType() == MVT::f16 &&
7955         fp16SrcZerosHighBits(BCSrc.getOpcode()))
7956       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
7957   }
7958 
7959   return SDValue();
7960 }
7961 
7962 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
7963                                                         DAGCombinerInfo &DCI)
7964                                                         const {
7965   SDValue Src = N->getOperand(0);
7966   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
7967 
7968   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
7969       VTSign->getVT() == MVT::i8) ||
7970       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
7971       VTSign->getVT() == MVT::i16)) &&
7972       Src.hasOneUse()) {
7973     auto *M = cast<MemSDNode>(Src);
7974     SDValue Ops[] = {
7975       Src.getOperand(0), // Chain
7976       Src.getOperand(1), // rsrc
7977       Src.getOperand(2), // vindex
7978       Src.getOperand(3), // voffset
7979       Src.getOperand(4), // soffset
7980       Src.getOperand(5), // offset
7981       Src.getOperand(6),
7982       Src.getOperand(7)
7983     };
7984     // replace with BUFFER_LOAD_BYTE/SHORT
7985     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
7986                                          Src.getOperand(0).getValueType());
7987     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
7988                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
7989     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
7990                                                           ResList,
7991                                                           Ops, M->getMemoryVT(),
7992                                                           M->getMemOperand());
7993     return DCI.DAG.getMergeValues({BufferLoadSignExt,
7994                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
7995   }
7996   return SDValue();
7997 }
7998 
7999 SDValue SITargetLowering::performClassCombine(SDNode *N,
8000                                               DAGCombinerInfo &DCI) const {
8001   SelectionDAG &DAG = DCI.DAG;
8002   SDValue Mask = N->getOperand(1);
8003 
8004   // fp_class x, 0 -> false
8005   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8006     if (CMask->isNullValue())
8007       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8008   }
8009 
8010   if (N->getOperand(0).isUndef())
8011     return DAG.getUNDEF(MVT::i1);
8012 
8013   return SDValue();
8014 }
8015 
8016 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8017                                             DAGCombinerInfo &DCI) const {
8018   EVT VT = N->getValueType(0);
8019   SDValue N0 = N->getOperand(0);
8020 
8021   if (N0.isUndef())
8022     return N0;
8023 
8024   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8025                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8026     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8027                            N->getFlags());
8028   }
8029 
8030   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8031 }
8032 
8033 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8034                                        unsigned MaxDepth) const {
8035   unsigned Opcode = Op.getOpcode();
8036   if (Opcode == ISD::FCANONICALIZE)
8037     return true;
8038 
8039   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8040     auto F = CFP->getValueAPF();
8041     if (F.isNaN() && F.isSignaling())
8042       return false;
8043     return !F.isDenormal() || denormalsEnabledForType(Op.getValueType());
8044   }
8045 
8046   // If source is a result of another standard FP operation it is already in
8047   // canonical form.
8048   if (MaxDepth == 0)
8049     return false;
8050 
8051   switch (Opcode) {
8052   // These will flush denorms if required.
8053   case ISD::FADD:
8054   case ISD::FSUB:
8055   case ISD::FMUL:
8056   case ISD::FCEIL:
8057   case ISD::FFLOOR:
8058   case ISD::FMA:
8059   case ISD::FMAD:
8060   case ISD::FSQRT:
8061   case ISD::FDIV:
8062   case ISD::FREM:
8063   case ISD::FP_ROUND:
8064   case ISD::FP_EXTEND:
8065   case AMDGPUISD::FMUL_LEGACY:
8066   case AMDGPUISD::FMAD_FTZ:
8067   case AMDGPUISD::RCP:
8068   case AMDGPUISD::RSQ:
8069   case AMDGPUISD::RSQ_CLAMP:
8070   case AMDGPUISD::RCP_LEGACY:
8071   case AMDGPUISD::RSQ_LEGACY:
8072   case AMDGPUISD::RCP_IFLAG:
8073   case AMDGPUISD::TRIG_PREOP:
8074   case AMDGPUISD::DIV_SCALE:
8075   case AMDGPUISD::DIV_FMAS:
8076   case AMDGPUISD::DIV_FIXUP:
8077   case AMDGPUISD::FRACT:
8078   case AMDGPUISD::LDEXP:
8079   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8080   case AMDGPUISD::CVT_F32_UBYTE0:
8081   case AMDGPUISD::CVT_F32_UBYTE1:
8082   case AMDGPUISD::CVT_F32_UBYTE2:
8083   case AMDGPUISD::CVT_F32_UBYTE3:
8084     return true;
8085 
8086   // It can/will be lowered or combined as a bit operation.
8087   // Need to check their input recursively to handle.
8088   case ISD::FNEG:
8089   case ISD::FABS:
8090   case ISD::FCOPYSIGN:
8091     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8092 
8093   case ISD::FSIN:
8094   case ISD::FCOS:
8095   case ISD::FSINCOS:
8096     return Op.getValueType().getScalarType() != MVT::f16;
8097 
8098   case ISD::FMINNUM:
8099   case ISD::FMAXNUM:
8100   case ISD::FMINNUM_IEEE:
8101   case ISD::FMAXNUM_IEEE:
8102   case AMDGPUISD::CLAMP:
8103   case AMDGPUISD::FMED3:
8104   case AMDGPUISD::FMAX3:
8105   case AMDGPUISD::FMIN3: {
8106     // FIXME: Shouldn't treat the generic operations different based these.
8107     // However, we aren't really required to flush the result from
8108     // minnum/maxnum..
8109 
8110     // snans will be quieted, so we only need to worry about denormals.
8111     if (Subtarget->supportsMinMaxDenormModes() ||
8112         denormalsEnabledForType(Op.getValueType()))
8113       return true;
8114 
8115     // Flushing may be required.
8116     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8117     // targets need to check their input recursively.
8118 
8119     // FIXME: Does this apply with clamp? It's implemented with max.
8120     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8121       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8122         return false;
8123     }
8124 
8125     return true;
8126   }
8127   case ISD::SELECT: {
8128     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8129            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8130   }
8131   case ISD::BUILD_VECTOR: {
8132     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8133       SDValue SrcOp = Op.getOperand(i);
8134       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8135         return false;
8136     }
8137 
8138     return true;
8139   }
8140   case ISD::EXTRACT_VECTOR_ELT:
8141   case ISD::EXTRACT_SUBVECTOR: {
8142     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8143   }
8144   case ISD::INSERT_VECTOR_ELT: {
8145     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8146            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8147   }
8148   case ISD::UNDEF:
8149     // Could be anything.
8150     return false;
8151 
8152   case ISD::BITCAST: {
8153     // Hack round the mess we make when legalizing extract_vector_elt
8154     SDValue Src = Op.getOperand(0);
8155     if (Src.getValueType() == MVT::i16 &&
8156         Src.getOpcode() == ISD::TRUNCATE) {
8157       SDValue TruncSrc = Src.getOperand(0);
8158       if (TruncSrc.getValueType() == MVT::i32 &&
8159           TruncSrc.getOpcode() == ISD::BITCAST &&
8160           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8161         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8162       }
8163     }
8164 
8165     return false;
8166   }
8167   case ISD::INTRINSIC_WO_CHAIN: {
8168     unsigned IntrinsicID
8169       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8170     // TODO: Handle more intrinsics
8171     switch (IntrinsicID) {
8172     case Intrinsic::amdgcn_cvt_pkrtz:
8173     case Intrinsic::amdgcn_cubeid:
8174     case Intrinsic::amdgcn_frexp_mant:
8175     case Intrinsic::amdgcn_fdot2:
8176       return true;
8177     default:
8178       break;
8179     }
8180 
8181     LLVM_FALLTHROUGH;
8182   }
8183   default:
8184     return denormalsEnabledForType(Op.getValueType()) &&
8185            DAG.isKnownNeverSNaN(Op);
8186   }
8187 
8188   llvm_unreachable("invalid operation");
8189 }
8190 
8191 // Constant fold canonicalize.
8192 SDValue SITargetLowering::getCanonicalConstantFP(
8193   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8194   // Flush denormals to 0 if not enabled.
8195   if (C.isDenormal() && !denormalsEnabledForType(VT))
8196     return DAG.getConstantFP(0.0, SL, VT);
8197 
8198   if (C.isNaN()) {
8199     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8200     if (C.isSignaling()) {
8201       // Quiet a signaling NaN.
8202       // FIXME: Is this supposed to preserve payload bits?
8203       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8204     }
8205 
8206     // Make sure it is the canonical NaN bitpattern.
8207     //
8208     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8209     // immediate?
8210     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8211       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8212   }
8213 
8214   // Already canonical.
8215   return DAG.getConstantFP(C, SL, VT);
8216 }
8217 
8218 static bool vectorEltWillFoldAway(SDValue Op) {
8219   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8220 }
8221 
8222 SDValue SITargetLowering::performFCanonicalizeCombine(
8223   SDNode *N,
8224   DAGCombinerInfo &DCI) const {
8225   SelectionDAG &DAG = DCI.DAG;
8226   SDValue N0 = N->getOperand(0);
8227   EVT VT = N->getValueType(0);
8228 
8229   // fcanonicalize undef -> qnan
8230   if (N0.isUndef()) {
8231     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8232     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8233   }
8234 
8235   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8236     EVT VT = N->getValueType(0);
8237     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8238   }
8239 
8240   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8241   //                                                   (fcanonicalize k)
8242   //
8243   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8244 
8245   // TODO: This could be better with wider vectors that will be split to v2f16,
8246   // and to consider uses since there aren't that many packed operations.
8247   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8248       isTypeLegal(MVT::v2f16)) {
8249     SDLoc SL(N);
8250     SDValue NewElts[2];
8251     SDValue Lo = N0.getOperand(0);
8252     SDValue Hi = N0.getOperand(1);
8253     EVT EltVT = Lo.getValueType();
8254 
8255     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8256       for (unsigned I = 0; I != 2; ++I) {
8257         SDValue Op = N0.getOperand(I);
8258         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8259           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8260                                               CFP->getValueAPF());
8261         } else if (Op.isUndef()) {
8262           // Handled below based on what the other operand is.
8263           NewElts[I] = Op;
8264         } else {
8265           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8266         }
8267       }
8268 
8269       // If one half is undef, and one is constant, perfer a splat vector rather
8270       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8271       // cheaper to use and may be free with a packed operation.
8272       if (NewElts[0].isUndef()) {
8273         if (isa<ConstantFPSDNode>(NewElts[1]))
8274           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8275             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8276       }
8277 
8278       if (NewElts[1].isUndef()) {
8279         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8280           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8281       }
8282 
8283       return DAG.getBuildVector(VT, SL, NewElts);
8284     }
8285   }
8286 
8287   unsigned SrcOpc = N0.getOpcode();
8288 
8289   // If it's free to do so, push canonicalizes further up the source, which may
8290   // find a canonical source.
8291   //
8292   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8293   // sNaNs.
8294   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8295     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8296     if (CRHS && N0.hasOneUse()) {
8297       SDLoc SL(N);
8298       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8299                                    N0.getOperand(0));
8300       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8301       DCI.AddToWorklist(Canon0.getNode());
8302 
8303       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8304     }
8305   }
8306 
8307   return isCanonicalized(DAG, N0) ? N0 : SDValue();
8308 }
8309 
8310 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
8311   switch (Opc) {
8312   case ISD::FMAXNUM:
8313   case ISD::FMAXNUM_IEEE:
8314     return AMDGPUISD::FMAX3;
8315   case ISD::SMAX:
8316     return AMDGPUISD::SMAX3;
8317   case ISD::UMAX:
8318     return AMDGPUISD::UMAX3;
8319   case ISD::FMINNUM:
8320   case ISD::FMINNUM_IEEE:
8321     return AMDGPUISD::FMIN3;
8322   case ISD::SMIN:
8323     return AMDGPUISD::SMIN3;
8324   case ISD::UMIN:
8325     return AMDGPUISD::UMIN3;
8326   default:
8327     llvm_unreachable("Not a min/max opcode");
8328   }
8329 }
8330 
8331 SDValue SITargetLowering::performIntMed3ImmCombine(
8332   SelectionDAG &DAG, const SDLoc &SL,
8333   SDValue Op0, SDValue Op1, bool Signed) const {
8334   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8335   if (!K1)
8336     return SDValue();
8337 
8338   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8339   if (!K0)
8340     return SDValue();
8341 
8342   if (Signed) {
8343     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8344       return SDValue();
8345   } else {
8346     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8347       return SDValue();
8348   }
8349 
8350   EVT VT = K0->getValueType(0);
8351   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8352   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8353     return DAG.getNode(Med3Opc, SL, VT,
8354                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8355   }
8356 
8357   // If there isn't a 16-bit med3 operation, convert to 32-bit.
8358   MVT NVT = MVT::i32;
8359   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8360 
8361   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8362   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8363   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
8364 
8365   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8366   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
8367 }
8368 
8369 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8370   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8371     return C;
8372 
8373   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8374     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
8375       return C;
8376   }
8377 
8378   return nullptr;
8379 }
8380 
8381 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
8382                                                   const SDLoc &SL,
8383                                                   SDValue Op0,
8384                                                   SDValue Op1) const {
8385   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
8386   if (!K1)
8387     return SDValue();
8388 
8389   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
8390   if (!K0)
8391     return SDValue();
8392 
8393   // Ordered >= (although NaN inputs should have folded away by now).
8394   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
8395   if (Cmp == APFloat::cmpGreaterThan)
8396     return SDValue();
8397 
8398   const MachineFunction &MF = DAG.getMachineFunction();
8399   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8400 
8401   // TODO: Check IEEE bit enabled?
8402   EVT VT = Op0.getValueType();
8403   if (Info->getMode().DX10Clamp) {
8404     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
8405     // hardware fmed3 behavior converting to a min.
8406     // FIXME: Should this be allowing -0.0?
8407     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
8408       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
8409   }
8410 
8411   // med3 for f16 is only available on gfx9+, and not available for v2f16.
8412   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
8413     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
8414     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
8415     // then give the other result, which is different from med3 with a NaN
8416     // input.
8417     SDValue Var = Op0.getOperand(0);
8418     if (!DAG.isKnownNeverSNaN(Var))
8419       return SDValue();
8420 
8421     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8422 
8423     if ((!K0->hasOneUse() ||
8424          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
8425         (!K1->hasOneUse() ||
8426          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
8427       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
8428                          Var, SDValue(K0, 0), SDValue(K1, 0));
8429     }
8430   }
8431 
8432   return SDValue();
8433 }
8434 
8435 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
8436                                                DAGCombinerInfo &DCI) const {
8437   SelectionDAG &DAG = DCI.DAG;
8438 
8439   EVT VT = N->getValueType(0);
8440   unsigned Opc = N->getOpcode();
8441   SDValue Op0 = N->getOperand(0);
8442   SDValue Op1 = N->getOperand(1);
8443 
8444   // Only do this if the inner op has one use since this will just increases
8445   // register pressure for no benefit.
8446 
8447   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
8448       !VT.isVector() &&
8449       (VT == MVT::i32 || VT == MVT::f32 ||
8450        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
8451     // max(max(a, b), c) -> max3(a, b, c)
8452     // min(min(a, b), c) -> min3(a, b, c)
8453     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
8454       SDLoc DL(N);
8455       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8456                          DL,
8457                          N->getValueType(0),
8458                          Op0.getOperand(0),
8459                          Op0.getOperand(1),
8460                          Op1);
8461     }
8462 
8463     // Try commuted.
8464     // max(a, max(b, c)) -> max3(a, b, c)
8465     // min(a, min(b, c)) -> min3(a, b, c)
8466     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
8467       SDLoc DL(N);
8468       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8469                          DL,
8470                          N->getValueType(0),
8471                          Op0,
8472                          Op1.getOperand(0),
8473                          Op1.getOperand(1));
8474     }
8475   }
8476 
8477   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
8478   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
8479     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
8480       return Med3;
8481   }
8482 
8483   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
8484     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
8485       return Med3;
8486   }
8487 
8488   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
8489   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
8490        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
8491        (Opc == AMDGPUISD::FMIN_LEGACY &&
8492         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
8493       (VT == MVT::f32 || VT == MVT::f64 ||
8494        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
8495        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
8496       Op0.hasOneUse()) {
8497     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
8498       return Res;
8499   }
8500 
8501   return SDValue();
8502 }
8503 
8504 static bool isClampZeroToOne(SDValue A, SDValue B) {
8505   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
8506     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
8507       // FIXME: Should this be allowing -0.0?
8508       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
8509              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
8510     }
8511   }
8512 
8513   return false;
8514 }
8515 
8516 // FIXME: Should only worry about snans for version with chain.
8517 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
8518                                               DAGCombinerInfo &DCI) const {
8519   EVT VT = N->getValueType(0);
8520   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
8521   // NaNs. With a NaN input, the order of the operands may change the result.
8522 
8523   SelectionDAG &DAG = DCI.DAG;
8524   SDLoc SL(N);
8525 
8526   SDValue Src0 = N->getOperand(0);
8527   SDValue Src1 = N->getOperand(1);
8528   SDValue Src2 = N->getOperand(2);
8529 
8530   if (isClampZeroToOne(Src0, Src1)) {
8531     // const_a, const_b, x -> clamp is safe in all cases including signaling
8532     // nans.
8533     // FIXME: Should this be allowing -0.0?
8534     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
8535   }
8536 
8537   const MachineFunction &MF = DAG.getMachineFunction();
8538   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8539 
8540   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
8541   // handling no dx10-clamp?
8542   if (Info->getMode().DX10Clamp) {
8543     // If NaNs is clamped to 0, we are free to reorder the inputs.
8544 
8545     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8546       std::swap(Src0, Src1);
8547 
8548     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
8549       std::swap(Src1, Src2);
8550 
8551     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8552       std::swap(Src0, Src1);
8553 
8554     if (isClampZeroToOne(Src1, Src2))
8555       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
8556   }
8557 
8558   return SDValue();
8559 }
8560 
8561 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
8562                                                  DAGCombinerInfo &DCI) const {
8563   SDValue Src0 = N->getOperand(0);
8564   SDValue Src1 = N->getOperand(1);
8565   if (Src0.isUndef() && Src1.isUndef())
8566     return DCI.DAG.getUNDEF(N->getValueType(0));
8567   return SDValue();
8568 }
8569 
8570 SDValue SITargetLowering::performExtractVectorEltCombine(
8571   SDNode *N, DAGCombinerInfo &DCI) const {
8572   SDValue Vec = N->getOperand(0);
8573   SelectionDAG &DAG = DCI.DAG;
8574 
8575   EVT VecVT = Vec.getValueType();
8576   EVT EltVT = VecVT.getVectorElementType();
8577 
8578   if ((Vec.getOpcode() == ISD::FNEG ||
8579        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
8580     SDLoc SL(N);
8581     EVT EltVT = N->getValueType(0);
8582     SDValue Idx = N->getOperand(1);
8583     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8584                               Vec.getOperand(0), Idx);
8585     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
8586   }
8587 
8588   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
8589   //    =>
8590   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
8591   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
8592   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
8593   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
8594     SDLoc SL(N);
8595     EVT EltVT = N->getValueType(0);
8596     SDValue Idx = N->getOperand(1);
8597     unsigned Opc = Vec.getOpcode();
8598 
8599     switch(Opc) {
8600     default:
8601       break;
8602       // TODO: Support other binary operations.
8603     case ISD::FADD:
8604     case ISD::FSUB:
8605     case ISD::FMUL:
8606     case ISD::ADD:
8607     case ISD::UMIN:
8608     case ISD::UMAX:
8609     case ISD::SMIN:
8610     case ISD::SMAX:
8611     case ISD::FMAXNUM:
8612     case ISD::FMINNUM:
8613     case ISD::FMAXNUM_IEEE:
8614     case ISD::FMINNUM_IEEE: {
8615       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8616                                  Vec.getOperand(0), Idx);
8617       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8618                                  Vec.getOperand(1), Idx);
8619 
8620       DCI.AddToWorklist(Elt0.getNode());
8621       DCI.AddToWorklist(Elt1.getNode());
8622       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
8623     }
8624     }
8625   }
8626 
8627   unsigned VecSize = VecVT.getSizeInBits();
8628   unsigned EltSize = EltVT.getSizeInBits();
8629 
8630   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
8631   // This elminates non-constant index and subsequent movrel or scratch access.
8632   // Sub-dword vectors of size 2 dword or less have better implementation.
8633   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
8634   // instructions.
8635   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
8636       !isa<ConstantSDNode>(N->getOperand(1))) {
8637     SDLoc SL(N);
8638     SDValue Idx = N->getOperand(1);
8639     EVT IdxVT = Idx.getValueType();
8640     SDValue V;
8641     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
8642       SDValue IC = DAG.getConstant(I, SL, IdxVT);
8643       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
8644       if (I == 0)
8645         V = Elt;
8646       else
8647         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
8648     }
8649     return V;
8650   }
8651 
8652   if (!DCI.isBeforeLegalize())
8653     return SDValue();
8654 
8655   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
8656   // elements. This exposes more load reduction opportunities by replacing
8657   // multiple small extract_vector_elements with a single 32-bit extract.
8658   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
8659   if (isa<MemSDNode>(Vec) &&
8660       EltSize <= 16 &&
8661       EltVT.isByteSized() &&
8662       VecSize > 32 &&
8663       VecSize % 32 == 0 &&
8664       Idx) {
8665     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
8666 
8667     unsigned BitIndex = Idx->getZExtValue() * EltSize;
8668     unsigned EltIdx = BitIndex / 32;
8669     unsigned LeftoverBitIdx = BitIndex % 32;
8670     SDLoc SL(N);
8671 
8672     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
8673     DCI.AddToWorklist(Cast.getNode());
8674 
8675     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
8676                               DAG.getConstant(EltIdx, SL, MVT::i32));
8677     DCI.AddToWorklist(Elt.getNode());
8678     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
8679                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
8680     DCI.AddToWorklist(Srl.getNode());
8681 
8682     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
8683     DCI.AddToWorklist(Trunc.getNode());
8684     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
8685   }
8686 
8687   return SDValue();
8688 }
8689 
8690 SDValue
8691 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
8692                                                 DAGCombinerInfo &DCI) const {
8693   SDValue Vec = N->getOperand(0);
8694   SDValue Idx = N->getOperand(2);
8695   EVT VecVT = Vec.getValueType();
8696   EVT EltVT = VecVT.getVectorElementType();
8697   unsigned VecSize = VecVT.getSizeInBits();
8698   unsigned EltSize = EltVT.getSizeInBits();
8699 
8700   // INSERT_VECTOR_ELT (<n x e>, var-idx)
8701   // => BUILD_VECTOR n x select (e, const-idx)
8702   // This elminates non-constant index and subsequent movrel or scratch access.
8703   // Sub-dword vectors of size 2 dword or less have better implementation.
8704   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
8705   // instructions.
8706   if (isa<ConstantSDNode>(Idx) ||
8707       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
8708     return SDValue();
8709 
8710   SelectionDAG &DAG = DCI.DAG;
8711   SDLoc SL(N);
8712   SDValue Ins = N->getOperand(1);
8713   EVT IdxVT = Idx.getValueType();
8714 
8715   SmallVector<SDValue, 16> Ops;
8716   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
8717     SDValue IC = DAG.getConstant(I, SL, IdxVT);
8718     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
8719     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
8720     Ops.push_back(V);
8721   }
8722 
8723   return DAG.getBuildVector(VecVT, SL, Ops);
8724 }
8725 
8726 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
8727                                           const SDNode *N0,
8728                                           const SDNode *N1) const {
8729   EVT VT = N0->getValueType(0);
8730 
8731   // Only do this if we are not trying to support denormals. v_mad_f32 does not
8732   // support denormals ever.
8733   if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
8734        (VT == MVT::f16 && !Subtarget->hasFP16Denormals() &&
8735         getSubtarget()->hasMadF16())) &&
8736        isOperationLegal(ISD::FMAD, VT))
8737     return ISD::FMAD;
8738 
8739   const TargetOptions &Options = DAG.getTarget().Options;
8740   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
8741        (N0->getFlags().hasAllowContract() &&
8742         N1->getFlags().hasAllowContract())) &&
8743       isFMAFasterThanFMulAndFAdd(VT)) {
8744     return ISD::FMA;
8745   }
8746 
8747   return 0;
8748 }
8749 
8750 // For a reassociatable opcode perform:
8751 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
8752 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
8753                                                SelectionDAG &DAG) const {
8754   EVT VT = N->getValueType(0);
8755   if (VT != MVT::i32 && VT != MVT::i64)
8756     return SDValue();
8757 
8758   unsigned Opc = N->getOpcode();
8759   SDValue Op0 = N->getOperand(0);
8760   SDValue Op1 = N->getOperand(1);
8761 
8762   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
8763     return SDValue();
8764 
8765   if (Op0->isDivergent())
8766     std::swap(Op0, Op1);
8767 
8768   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
8769     return SDValue();
8770 
8771   SDValue Op2 = Op1.getOperand(1);
8772   Op1 = Op1.getOperand(0);
8773   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
8774     return SDValue();
8775 
8776   if (Op1->isDivergent())
8777     std::swap(Op1, Op2);
8778 
8779   // If either operand is constant this will conflict with
8780   // DAGCombiner::ReassociateOps().
8781   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
8782       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
8783     return SDValue();
8784 
8785   SDLoc SL(N);
8786   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
8787   return DAG.getNode(Opc, SL, VT, Add1, Op2);
8788 }
8789 
8790 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
8791                            EVT VT,
8792                            SDValue N0, SDValue N1, SDValue N2,
8793                            bool Signed) {
8794   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
8795   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
8796   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
8797   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
8798 }
8799 
8800 SDValue SITargetLowering::performAddCombine(SDNode *N,
8801                                             DAGCombinerInfo &DCI) const {
8802   SelectionDAG &DAG = DCI.DAG;
8803   EVT VT = N->getValueType(0);
8804   SDLoc SL(N);
8805   SDValue LHS = N->getOperand(0);
8806   SDValue RHS = N->getOperand(1);
8807 
8808   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
8809       && Subtarget->hasMad64_32() &&
8810       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
8811       VT.getScalarSizeInBits() <= 64) {
8812     if (LHS.getOpcode() != ISD::MUL)
8813       std::swap(LHS, RHS);
8814 
8815     SDValue MulLHS = LHS.getOperand(0);
8816     SDValue MulRHS = LHS.getOperand(1);
8817     SDValue AddRHS = RHS;
8818 
8819     // TODO: Maybe restrict if SGPR inputs.
8820     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
8821         numBitsUnsigned(MulRHS, DAG) <= 32) {
8822       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
8823       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
8824       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
8825       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
8826     }
8827 
8828     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
8829       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
8830       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
8831       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
8832       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
8833     }
8834 
8835     return SDValue();
8836   }
8837 
8838   if (SDValue V = reassociateScalarOps(N, DAG)) {
8839     return V;
8840   }
8841 
8842   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
8843     return SDValue();
8844 
8845   // add x, zext (setcc) => addcarry x, 0, setcc
8846   // add x, sext (setcc) => subcarry x, 0, setcc
8847   unsigned Opc = LHS.getOpcode();
8848   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
8849       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
8850     std::swap(RHS, LHS);
8851 
8852   Opc = RHS.getOpcode();
8853   switch (Opc) {
8854   default: break;
8855   case ISD::ZERO_EXTEND:
8856   case ISD::SIGN_EXTEND:
8857   case ISD::ANY_EXTEND: {
8858     auto Cond = RHS.getOperand(0);
8859     if (!isBoolSGPR(Cond))
8860       break;
8861     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
8862     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
8863     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
8864     return DAG.getNode(Opc, SL, VTList, Args);
8865   }
8866   case ISD::ADDCARRY: {
8867     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
8868     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8869     if (!C || C->getZExtValue() != 0) break;
8870     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
8871     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
8872   }
8873   }
8874   return SDValue();
8875 }
8876 
8877 SDValue SITargetLowering::performSubCombine(SDNode *N,
8878                                             DAGCombinerInfo &DCI) const {
8879   SelectionDAG &DAG = DCI.DAG;
8880   EVT VT = N->getValueType(0);
8881 
8882   if (VT != MVT::i32)
8883     return SDValue();
8884 
8885   SDLoc SL(N);
8886   SDValue LHS = N->getOperand(0);
8887   SDValue RHS = N->getOperand(1);
8888 
8889   if (LHS.getOpcode() == ISD::SUBCARRY) {
8890     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
8891     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8892     if (!C || !C->isNullValue())
8893       return SDValue();
8894     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
8895     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
8896   }
8897   return SDValue();
8898 }
8899 
8900 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
8901   DAGCombinerInfo &DCI) const {
8902 
8903   if (N->getValueType(0) != MVT::i32)
8904     return SDValue();
8905 
8906   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8907   if (!C || C->getZExtValue() != 0)
8908     return SDValue();
8909 
8910   SelectionDAG &DAG = DCI.DAG;
8911   SDValue LHS = N->getOperand(0);
8912 
8913   // addcarry (add x, y), 0, cc => addcarry x, y, cc
8914   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
8915   unsigned LHSOpc = LHS.getOpcode();
8916   unsigned Opc = N->getOpcode();
8917   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
8918       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
8919     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
8920     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
8921   }
8922   return SDValue();
8923 }
8924 
8925 SDValue SITargetLowering::performFAddCombine(SDNode *N,
8926                                              DAGCombinerInfo &DCI) const {
8927   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8928     return SDValue();
8929 
8930   SelectionDAG &DAG = DCI.DAG;
8931   EVT VT = N->getValueType(0);
8932 
8933   SDLoc SL(N);
8934   SDValue LHS = N->getOperand(0);
8935   SDValue RHS = N->getOperand(1);
8936 
8937   // These should really be instruction patterns, but writing patterns with
8938   // source modiifiers is a pain.
8939 
8940   // fadd (fadd (a, a), b) -> mad 2.0, a, b
8941   if (LHS.getOpcode() == ISD::FADD) {
8942     SDValue A = LHS.getOperand(0);
8943     if (A == LHS.getOperand(1)) {
8944       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
8945       if (FusedOp != 0) {
8946         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
8947         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
8948       }
8949     }
8950   }
8951 
8952   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
8953   if (RHS.getOpcode() == ISD::FADD) {
8954     SDValue A = RHS.getOperand(0);
8955     if (A == RHS.getOperand(1)) {
8956       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
8957       if (FusedOp != 0) {
8958         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
8959         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
8960       }
8961     }
8962   }
8963 
8964   return SDValue();
8965 }
8966 
8967 SDValue SITargetLowering::performFSubCombine(SDNode *N,
8968                                              DAGCombinerInfo &DCI) const {
8969   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8970     return SDValue();
8971 
8972   SelectionDAG &DAG = DCI.DAG;
8973   SDLoc SL(N);
8974   EVT VT = N->getValueType(0);
8975   assert(!VT.isVector());
8976 
8977   // Try to get the fneg to fold into the source modifier. This undoes generic
8978   // DAG combines and folds them into the mad.
8979   //
8980   // Only do this if we are not trying to support denormals. v_mad_f32 does
8981   // not support denormals ever.
8982   SDValue LHS = N->getOperand(0);
8983   SDValue RHS = N->getOperand(1);
8984   if (LHS.getOpcode() == ISD::FADD) {
8985     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
8986     SDValue A = LHS.getOperand(0);
8987     if (A == LHS.getOperand(1)) {
8988       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
8989       if (FusedOp != 0){
8990         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
8991         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8992 
8993         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
8994       }
8995     }
8996   }
8997 
8998   if (RHS.getOpcode() == ISD::FADD) {
8999     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9000 
9001     SDValue A = RHS.getOperand(0);
9002     if (A == RHS.getOperand(1)) {
9003       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9004       if (FusedOp != 0){
9005         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9006         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9007       }
9008     }
9009   }
9010 
9011   return SDValue();
9012 }
9013 
9014 SDValue SITargetLowering::performFMACombine(SDNode *N,
9015                                             DAGCombinerInfo &DCI) const {
9016   SelectionDAG &DAG = DCI.DAG;
9017   EVT VT = N->getValueType(0);
9018   SDLoc SL(N);
9019 
9020   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9021     return SDValue();
9022 
9023   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9024   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9025   SDValue Op1 = N->getOperand(0);
9026   SDValue Op2 = N->getOperand(1);
9027   SDValue FMA = N->getOperand(2);
9028 
9029   if (FMA.getOpcode() != ISD::FMA ||
9030       Op1.getOpcode() != ISD::FP_EXTEND ||
9031       Op2.getOpcode() != ISD::FP_EXTEND)
9032     return SDValue();
9033 
9034   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9035   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9036   // is sufficient to allow generaing fdot2.
9037   const TargetOptions &Options = DAG.getTarget().Options;
9038   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9039       (N->getFlags().hasAllowContract() &&
9040        FMA->getFlags().hasAllowContract())) {
9041     Op1 = Op1.getOperand(0);
9042     Op2 = Op2.getOperand(0);
9043     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9044         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9045       return SDValue();
9046 
9047     SDValue Vec1 = Op1.getOperand(0);
9048     SDValue Idx1 = Op1.getOperand(1);
9049     SDValue Vec2 = Op2.getOperand(0);
9050 
9051     SDValue FMAOp1 = FMA.getOperand(0);
9052     SDValue FMAOp2 = FMA.getOperand(1);
9053     SDValue FMAAcc = FMA.getOperand(2);
9054 
9055     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9056         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9057       return SDValue();
9058 
9059     FMAOp1 = FMAOp1.getOperand(0);
9060     FMAOp2 = FMAOp2.getOperand(0);
9061     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9062         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9063       return SDValue();
9064 
9065     SDValue Vec3 = FMAOp1.getOperand(0);
9066     SDValue Vec4 = FMAOp2.getOperand(0);
9067     SDValue Idx2 = FMAOp1.getOperand(1);
9068 
9069     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9070         // Idx1 and Idx2 cannot be the same.
9071         Idx1 == Idx2)
9072       return SDValue();
9073 
9074     if (Vec1 == Vec2 || Vec3 == Vec4)
9075       return SDValue();
9076 
9077     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9078       return SDValue();
9079 
9080     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9081         (Vec1 == Vec4 && Vec2 == Vec3)) {
9082       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9083                          DAG.getTargetConstant(0, SL, MVT::i1));
9084     }
9085   }
9086   return SDValue();
9087 }
9088 
9089 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9090                                               DAGCombinerInfo &DCI) const {
9091   SelectionDAG &DAG = DCI.DAG;
9092   SDLoc SL(N);
9093 
9094   SDValue LHS = N->getOperand(0);
9095   SDValue RHS = N->getOperand(1);
9096   EVT VT = LHS.getValueType();
9097   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9098 
9099   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9100   if (!CRHS) {
9101     CRHS = dyn_cast<ConstantSDNode>(LHS);
9102     if (CRHS) {
9103       std::swap(LHS, RHS);
9104       CC = getSetCCSwappedOperands(CC);
9105     }
9106   }
9107 
9108   if (CRHS) {
9109     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9110         isBoolSGPR(LHS.getOperand(0))) {
9111       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9112       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9113       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9114       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9115       if ((CRHS->isAllOnesValue() &&
9116            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9117           (CRHS->isNullValue() &&
9118            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9119         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9120                            DAG.getConstant(-1, SL, MVT::i1));
9121       if ((CRHS->isAllOnesValue() &&
9122            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9123           (CRHS->isNullValue() &&
9124            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9125         return LHS.getOperand(0);
9126     }
9127 
9128     uint64_t CRHSVal = CRHS->getZExtValue();
9129     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9130         LHS.getOpcode() == ISD::SELECT &&
9131         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9132         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9133         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9134         isBoolSGPR(LHS.getOperand(0))) {
9135       // Given CT != FT:
9136       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9137       // setcc (select cc, CT, CF), CF, ne => cc
9138       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9139       // setcc (select cc, CT, CF), CT, eq => cc
9140       uint64_t CT = LHS.getConstantOperandVal(1);
9141       uint64_t CF = LHS.getConstantOperandVal(2);
9142 
9143       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9144           (CT == CRHSVal && CC == ISD::SETNE))
9145         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9146                            DAG.getConstant(-1, SL, MVT::i1));
9147       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9148           (CT == CRHSVal && CC == ISD::SETEQ))
9149         return LHS.getOperand(0);
9150     }
9151   }
9152 
9153   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9154                                            VT != MVT::f16))
9155     return SDValue();
9156 
9157   // Match isinf/isfinite pattern
9158   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9159   // (fcmp one (fabs x), inf) -> (fp_class x,
9160   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9161   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9162     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9163     if (!CRHS)
9164       return SDValue();
9165 
9166     const APFloat &APF = CRHS->getValueAPF();
9167     if (APF.isInfinity() && !APF.isNegative()) {
9168       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9169                                  SIInstrFlags::N_INFINITY;
9170       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9171                                     SIInstrFlags::P_ZERO |
9172                                     SIInstrFlags::N_NORMAL |
9173                                     SIInstrFlags::P_NORMAL |
9174                                     SIInstrFlags::N_SUBNORMAL |
9175                                     SIInstrFlags::P_SUBNORMAL;
9176       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9177       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9178                          DAG.getConstant(Mask, SL, MVT::i32));
9179     }
9180   }
9181 
9182   return SDValue();
9183 }
9184 
9185 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9186                                                      DAGCombinerInfo &DCI) const {
9187   SelectionDAG &DAG = DCI.DAG;
9188   SDLoc SL(N);
9189   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9190 
9191   SDValue Src = N->getOperand(0);
9192   SDValue Srl = N->getOperand(0);
9193   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9194     Srl = Srl.getOperand(0);
9195 
9196   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9197   if (Srl.getOpcode() == ISD::SRL) {
9198     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9199     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9200     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9201 
9202     if (const ConstantSDNode *C =
9203         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9204       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9205                                EVT(MVT::i32));
9206 
9207       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9208       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9209         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9210                            MVT::f32, Srl);
9211       }
9212     }
9213   }
9214 
9215   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9216 
9217   KnownBits Known;
9218   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9219                                         !DCI.isBeforeLegalizeOps());
9220   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9221   if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
9222     DCI.CommitTargetLoweringOpt(TLO);
9223   }
9224 
9225   return SDValue();
9226 }
9227 
9228 SDValue SITargetLowering::performClampCombine(SDNode *N,
9229                                               DAGCombinerInfo &DCI) const {
9230   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9231   if (!CSrc)
9232     return SDValue();
9233 
9234   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9235   const APFloat &F = CSrc->getValueAPF();
9236   APFloat Zero = APFloat::getZero(F.getSemantics());
9237   APFloat::cmpResult Cmp0 = F.compare(Zero);
9238   if (Cmp0 == APFloat::cmpLessThan ||
9239       (Cmp0 == APFloat::cmpUnordered &&
9240        MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9241     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9242   }
9243 
9244   APFloat One(F.getSemantics(), "1.0");
9245   APFloat::cmpResult Cmp1 = F.compare(One);
9246   if (Cmp1 == APFloat::cmpGreaterThan)
9247     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9248 
9249   return SDValue(CSrc, 0);
9250 }
9251 
9252 
9253 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9254                                             DAGCombinerInfo &DCI) const {
9255   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9256     return SDValue();
9257   switch (N->getOpcode()) {
9258   default:
9259     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9260   case ISD::ADD:
9261     return performAddCombine(N, DCI);
9262   case ISD::SUB:
9263     return performSubCombine(N, DCI);
9264   case ISD::ADDCARRY:
9265   case ISD::SUBCARRY:
9266     return performAddCarrySubCarryCombine(N, DCI);
9267   case ISD::FADD:
9268     return performFAddCombine(N, DCI);
9269   case ISD::FSUB:
9270     return performFSubCombine(N, DCI);
9271   case ISD::SETCC:
9272     return performSetCCCombine(N, DCI);
9273   case ISD::FMAXNUM:
9274   case ISD::FMINNUM:
9275   case ISD::FMAXNUM_IEEE:
9276   case ISD::FMINNUM_IEEE:
9277   case ISD::SMAX:
9278   case ISD::SMIN:
9279   case ISD::UMAX:
9280   case ISD::UMIN:
9281   case AMDGPUISD::FMIN_LEGACY:
9282   case AMDGPUISD::FMAX_LEGACY:
9283     return performMinMaxCombine(N, DCI);
9284   case ISD::FMA:
9285     return performFMACombine(N, DCI);
9286   case ISD::LOAD: {
9287     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9288       return Widended;
9289     LLVM_FALLTHROUGH;
9290   }
9291   case ISD::STORE:
9292   case ISD::ATOMIC_LOAD:
9293   case ISD::ATOMIC_STORE:
9294   case ISD::ATOMIC_CMP_SWAP:
9295   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9296   case ISD::ATOMIC_SWAP:
9297   case ISD::ATOMIC_LOAD_ADD:
9298   case ISD::ATOMIC_LOAD_SUB:
9299   case ISD::ATOMIC_LOAD_AND:
9300   case ISD::ATOMIC_LOAD_OR:
9301   case ISD::ATOMIC_LOAD_XOR:
9302   case ISD::ATOMIC_LOAD_NAND:
9303   case ISD::ATOMIC_LOAD_MIN:
9304   case ISD::ATOMIC_LOAD_MAX:
9305   case ISD::ATOMIC_LOAD_UMIN:
9306   case ISD::ATOMIC_LOAD_UMAX:
9307   case ISD::ATOMIC_LOAD_FADD:
9308   case AMDGPUISD::ATOMIC_INC:
9309   case AMDGPUISD::ATOMIC_DEC:
9310   case AMDGPUISD::ATOMIC_LOAD_FMIN:
9311   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
9312     if (DCI.isBeforeLegalize())
9313       break;
9314     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
9315   case ISD::AND:
9316     return performAndCombine(N, DCI);
9317   case ISD::OR:
9318     return performOrCombine(N, DCI);
9319   case ISD::XOR:
9320     return performXorCombine(N, DCI);
9321   case ISD::ZERO_EXTEND:
9322     return performZeroExtendCombine(N, DCI);
9323   case ISD::SIGN_EXTEND_INREG:
9324     return performSignExtendInRegCombine(N , DCI);
9325   case AMDGPUISD::FP_CLASS:
9326     return performClassCombine(N, DCI);
9327   case ISD::FCANONICALIZE:
9328     return performFCanonicalizeCombine(N, DCI);
9329   case AMDGPUISD::RCP:
9330     return performRcpCombine(N, DCI);
9331   case AMDGPUISD::FRACT:
9332   case AMDGPUISD::RSQ:
9333   case AMDGPUISD::RCP_LEGACY:
9334   case AMDGPUISD::RSQ_LEGACY:
9335   case AMDGPUISD::RCP_IFLAG:
9336   case AMDGPUISD::RSQ_CLAMP:
9337   case AMDGPUISD::LDEXP: {
9338     SDValue Src = N->getOperand(0);
9339     if (Src.isUndef())
9340       return Src;
9341     break;
9342   }
9343   case ISD::SINT_TO_FP:
9344   case ISD::UINT_TO_FP:
9345     return performUCharToFloatCombine(N, DCI);
9346   case AMDGPUISD::CVT_F32_UBYTE0:
9347   case AMDGPUISD::CVT_F32_UBYTE1:
9348   case AMDGPUISD::CVT_F32_UBYTE2:
9349   case AMDGPUISD::CVT_F32_UBYTE3:
9350     return performCvtF32UByteNCombine(N, DCI);
9351   case AMDGPUISD::FMED3:
9352     return performFMed3Combine(N, DCI);
9353   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9354     return performCvtPkRTZCombine(N, DCI);
9355   case AMDGPUISD::CLAMP:
9356     return performClampCombine(N, DCI);
9357   case ISD::SCALAR_TO_VECTOR: {
9358     SelectionDAG &DAG = DCI.DAG;
9359     EVT VT = N->getValueType(0);
9360 
9361     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
9362     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
9363       SDLoc SL(N);
9364       SDValue Src = N->getOperand(0);
9365       EVT EltVT = Src.getValueType();
9366       if (EltVT == MVT::f16)
9367         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
9368 
9369       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
9370       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
9371     }
9372 
9373     break;
9374   }
9375   case ISD::EXTRACT_VECTOR_ELT:
9376     return performExtractVectorEltCombine(N, DCI);
9377   case ISD::INSERT_VECTOR_ELT:
9378     return performInsertVectorEltCombine(N, DCI);
9379   }
9380   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9381 }
9382 
9383 /// Helper function for adjustWritemask
9384 static unsigned SubIdx2Lane(unsigned Idx) {
9385   switch (Idx) {
9386   default: return 0;
9387   case AMDGPU::sub0: return 0;
9388   case AMDGPU::sub1: return 1;
9389   case AMDGPU::sub2: return 2;
9390   case AMDGPU::sub3: return 3;
9391   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
9392   }
9393 }
9394 
9395 /// Adjust the writemask of MIMG instructions
9396 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
9397                                           SelectionDAG &DAG) const {
9398   unsigned Opcode = Node->getMachineOpcode();
9399 
9400   // Subtract 1 because the vdata output is not a MachineSDNode operand.
9401   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
9402   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
9403     return Node; // not implemented for D16
9404 
9405   SDNode *Users[5] = { nullptr };
9406   unsigned Lane = 0;
9407   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
9408   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
9409   unsigned NewDmask = 0;
9410   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
9411   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
9412   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
9413                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
9414   unsigned TFCLane = 0;
9415   bool HasChain = Node->getNumValues() > 1;
9416 
9417   if (OldDmask == 0) {
9418     // These are folded out, but on the chance it happens don't assert.
9419     return Node;
9420   }
9421 
9422   unsigned OldBitsSet = countPopulation(OldDmask);
9423   // Work out which is the TFE/LWE lane if that is enabled.
9424   if (UsesTFC) {
9425     TFCLane = OldBitsSet;
9426   }
9427 
9428   // Try to figure out the used register components
9429   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
9430        I != E; ++I) {
9431 
9432     // Don't look at users of the chain.
9433     if (I.getUse().getResNo() != 0)
9434       continue;
9435 
9436     // Abort if we can't understand the usage
9437     if (!I->isMachineOpcode() ||
9438         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
9439       return Node;
9440 
9441     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
9442     // Note that subregs are packed, i.e. Lane==0 is the first bit set
9443     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
9444     // set, etc.
9445     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
9446 
9447     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
9448     if (UsesTFC && Lane == TFCLane) {
9449       Users[Lane] = *I;
9450     } else {
9451       // Set which texture component corresponds to the lane.
9452       unsigned Comp;
9453       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
9454         Comp = countTrailingZeros(Dmask);
9455         Dmask &= ~(1 << Comp);
9456       }
9457 
9458       // Abort if we have more than one user per component.
9459       if (Users[Lane])
9460         return Node;
9461 
9462       Users[Lane] = *I;
9463       NewDmask |= 1 << Comp;
9464     }
9465   }
9466 
9467   // Don't allow 0 dmask, as hardware assumes one channel enabled.
9468   bool NoChannels = !NewDmask;
9469   if (NoChannels) {
9470     if (!UsesTFC) {
9471       // No uses of the result and not using TFC. Then do nothing.
9472       return Node;
9473     }
9474     // If the original dmask has one channel - then nothing to do
9475     if (OldBitsSet == 1)
9476       return Node;
9477     // Use an arbitrary dmask - required for the instruction to work
9478     NewDmask = 1;
9479   }
9480   // Abort if there's no change
9481   if (NewDmask == OldDmask)
9482     return Node;
9483 
9484   unsigned BitsSet = countPopulation(NewDmask);
9485 
9486   // Check for TFE or LWE - increase the number of channels by one to account
9487   // for the extra return value
9488   // This will need adjustment for D16 if this is also included in
9489   // adjustWriteMask (this function) but at present D16 are excluded.
9490   unsigned NewChannels = BitsSet + UsesTFC;
9491 
9492   int NewOpcode =
9493       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
9494   assert(NewOpcode != -1 &&
9495          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
9496          "failed to find equivalent MIMG op");
9497 
9498   // Adjust the writemask in the node
9499   SmallVector<SDValue, 12> Ops;
9500   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
9501   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
9502   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
9503 
9504   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
9505 
9506   MVT ResultVT = NewChannels == 1 ?
9507     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
9508                            NewChannels == 5 ? 8 : NewChannels);
9509   SDVTList NewVTList = HasChain ?
9510     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
9511 
9512 
9513   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
9514                                               NewVTList, Ops);
9515 
9516   if (HasChain) {
9517     // Update chain.
9518     DAG.setNodeMemRefs(NewNode, Node->memoperands());
9519     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
9520   }
9521 
9522   if (NewChannels == 1) {
9523     assert(Node->hasNUsesOfValue(1, 0));
9524     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
9525                                       SDLoc(Node), Users[Lane]->getValueType(0),
9526                                       SDValue(NewNode, 0));
9527     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
9528     return nullptr;
9529   }
9530 
9531   // Update the users of the node with the new indices
9532   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
9533     SDNode *User = Users[i];
9534     if (!User) {
9535       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
9536       // Users[0] is still nullptr because channel 0 doesn't really have a use.
9537       if (i || !NoChannels)
9538         continue;
9539     } else {
9540       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
9541       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
9542     }
9543 
9544     switch (Idx) {
9545     default: break;
9546     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
9547     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
9548     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
9549     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
9550     }
9551   }
9552 
9553   DAG.RemoveDeadNode(Node);
9554   return nullptr;
9555 }
9556 
9557 static bool isFrameIndexOp(SDValue Op) {
9558   if (Op.getOpcode() == ISD::AssertZext)
9559     Op = Op.getOperand(0);
9560 
9561   return isa<FrameIndexSDNode>(Op);
9562 }
9563 
9564 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
9565 /// with frame index operands.
9566 /// LLVM assumes that inputs are to these instructions are registers.
9567 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
9568                                                         SelectionDAG &DAG) const {
9569   if (Node->getOpcode() == ISD::CopyToReg) {
9570     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
9571     SDValue SrcVal = Node->getOperand(2);
9572 
9573     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
9574     // to try understanding copies to physical registers.
9575     if (SrcVal.getValueType() == MVT::i1 &&
9576         TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
9577       SDLoc SL(Node);
9578       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
9579       SDValue VReg = DAG.getRegister(
9580         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
9581 
9582       SDNode *Glued = Node->getGluedNode();
9583       SDValue ToVReg
9584         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
9585                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
9586       SDValue ToResultReg
9587         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
9588                            VReg, ToVReg.getValue(1));
9589       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
9590       DAG.RemoveDeadNode(Node);
9591       return ToResultReg.getNode();
9592     }
9593   }
9594 
9595   SmallVector<SDValue, 8> Ops;
9596   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
9597     if (!isFrameIndexOp(Node->getOperand(i))) {
9598       Ops.push_back(Node->getOperand(i));
9599       continue;
9600     }
9601 
9602     SDLoc DL(Node);
9603     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
9604                                      Node->getOperand(i).getValueType(),
9605                                      Node->getOperand(i)), 0));
9606   }
9607 
9608   return DAG.UpdateNodeOperands(Node, Ops);
9609 }
9610 
9611 /// Fold the instructions after selecting them.
9612 /// Returns null if users were already updated.
9613 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
9614                                           SelectionDAG &DAG) const {
9615   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9616   unsigned Opcode = Node->getMachineOpcode();
9617 
9618   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
9619       !TII->isGather4(Opcode)) {
9620     return adjustWritemask(Node, DAG);
9621   }
9622 
9623   if (Opcode == AMDGPU::INSERT_SUBREG ||
9624       Opcode == AMDGPU::REG_SEQUENCE) {
9625     legalizeTargetIndependentNode(Node, DAG);
9626     return Node;
9627   }
9628 
9629   switch (Opcode) {
9630   case AMDGPU::V_DIV_SCALE_F32:
9631   case AMDGPU::V_DIV_SCALE_F64: {
9632     // Satisfy the operand register constraint when one of the inputs is
9633     // undefined. Ordinarily each undef value will have its own implicit_def of
9634     // a vreg, so force these to use a single register.
9635     SDValue Src0 = Node->getOperand(0);
9636     SDValue Src1 = Node->getOperand(1);
9637     SDValue Src2 = Node->getOperand(2);
9638 
9639     if ((Src0.isMachineOpcode() &&
9640          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
9641         (Src0 == Src1 || Src0 == Src2))
9642       break;
9643 
9644     MVT VT = Src0.getValueType().getSimpleVT();
9645     const TargetRegisterClass *RC = getRegClassFor(VT);
9646 
9647     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
9648     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
9649 
9650     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
9651                                       UndefReg, Src0, SDValue());
9652 
9653     // src0 must be the same register as src1 or src2, even if the value is
9654     // undefined, so make sure we don't violate this constraint.
9655     if (Src0.isMachineOpcode() &&
9656         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
9657       if (Src1.isMachineOpcode() &&
9658           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
9659         Src0 = Src1;
9660       else if (Src2.isMachineOpcode() &&
9661                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
9662         Src0 = Src2;
9663       else {
9664         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
9665         Src0 = UndefReg;
9666         Src1 = UndefReg;
9667       }
9668     } else
9669       break;
9670 
9671     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
9672     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
9673       Ops.push_back(Node->getOperand(I));
9674 
9675     Ops.push_back(ImpDef.getValue(1));
9676     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
9677   }
9678   default:
9679     break;
9680   }
9681 
9682   return Node;
9683 }
9684 
9685 /// Assign the register class depending on the number of
9686 /// bits set in the writemask
9687 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9688                                                      SDNode *Node) const {
9689   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9690 
9691   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
9692 
9693   if (TII->isVOP3(MI.getOpcode())) {
9694     // Make sure constant bus requirements are respected.
9695     TII->legalizeOperandsVOP3(MRI, MI);
9696     return;
9697   }
9698 
9699   // Replace unused atomics with the no return version.
9700   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
9701   if (NoRetAtomicOp != -1) {
9702     if (!Node->hasAnyUseOfValue(0)) {
9703       MI.setDesc(TII->get(NoRetAtomicOp));
9704       MI.RemoveOperand(0);
9705       return;
9706     }
9707 
9708     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
9709     // instruction, because the return type of these instructions is a vec2 of
9710     // the memory type, so it can be tied to the input operand.
9711     // This means these instructions always have a use, so we need to add a
9712     // special case to check if the atomic has only one extract_subreg use,
9713     // which itself has no uses.
9714     if ((Node->hasNUsesOfValue(1, 0) &&
9715          Node->use_begin()->isMachineOpcode() &&
9716          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
9717          !Node->use_begin()->hasAnyUseOfValue(0))) {
9718       unsigned Def = MI.getOperand(0).getReg();
9719 
9720       // Change this into a noret atomic.
9721       MI.setDesc(TII->get(NoRetAtomicOp));
9722       MI.RemoveOperand(0);
9723 
9724       // If we only remove the def operand from the atomic instruction, the
9725       // extract_subreg will be left with a use of a vreg without a def.
9726       // So we need to insert an implicit_def to avoid machine verifier
9727       // errors.
9728       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
9729               TII->get(AMDGPU::IMPLICIT_DEF), Def);
9730     }
9731     return;
9732   }
9733 }
9734 
9735 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
9736                               uint64_t Val) {
9737   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
9738   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
9739 }
9740 
9741 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
9742                                                 const SDLoc &DL,
9743                                                 SDValue Ptr) const {
9744   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9745 
9746   // Build the half of the subregister with the constants before building the
9747   // full 128-bit register. If we are building multiple resource descriptors,
9748   // this will allow CSEing of the 2-component register.
9749   const SDValue Ops0[] = {
9750     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
9751     buildSMovImm32(DAG, DL, 0),
9752     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
9753     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
9754     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
9755   };
9756 
9757   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
9758                                                 MVT::v2i32, Ops0), 0);
9759 
9760   // Combine the constants and the pointer.
9761   const SDValue Ops1[] = {
9762     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
9763     Ptr,
9764     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
9765     SubRegHi,
9766     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
9767   };
9768 
9769   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
9770 }
9771 
9772 /// Return a resource descriptor with the 'Add TID' bit enabled
9773 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
9774 ///        of the resource descriptor) to create an offset, which is added to
9775 ///        the resource pointer.
9776 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
9777                                            SDValue Ptr, uint32_t RsrcDword1,
9778                                            uint64_t RsrcDword2And3) const {
9779   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
9780   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
9781   if (RsrcDword1) {
9782     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
9783                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
9784                     0);
9785   }
9786 
9787   SDValue DataLo = buildSMovImm32(DAG, DL,
9788                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
9789   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
9790 
9791   const SDValue Ops[] = {
9792     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
9793     PtrLo,
9794     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
9795     PtrHi,
9796     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
9797     DataLo,
9798     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
9799     DataHi,
9800     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
9801   };
9802 
9803   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
9804 }
9805 
9806 //===----------------------------------------------------------------------===//
9807 //                         SI Inline Assembly Support
9808 //===----------------------------------------------------------------------===//
9809 
9810 std::pair<unsigned, const TargetRegisterClass *>
9811 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9812                                                StringRef Constraint,
9813                                                MVT VT) const {
9814   const TargetRegisterClass *RC = nullptr;
9815   if (Constraint.size() == 1) {
9816     switch (Constraint[0]) {
9817     default:
9818       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9819     case 's':
9820     case 'r':
9821       switch (VT.getSizeInBits()) {
9822       default:
9823         return std::make_pair(0U, nullptr);
9824       case 32:
9825       case 16:
9826         RC = &AMDGPU::SReg_32_XM0RegClass;
9827         break;
9828       case 64:
9829         RC = &AMDGPU::SGPR_64RegClass;
9830         break;
9831       case 96:
9832         RC = &AMDGPU::SReg_96RegClass;
9833         break;
9834       case 128:
9835         RC = &AMDGPU::SReg_128RegClass;
9836         break;
9837       case 160:
9838         RC = &AMDGPU::SReg_160RegClass;
9839         break;
9840       case 256:
9841         RC = &AMDGPU::SReg_256RegClass;
9842         break;
9843       case 512:
9844         RC = &AMDGPU::SReg_512RegClass;
9845         break;
9846       }
9847       break;
9848     case 'v':
9849       switch (VT.getSizeInBits()) {
9850       default:
9851         return std::make_pair(0U, nullptr);
9852       case 32:
9853       case 16:
9854         RC = &AMDGPU::VGPR_32RegClass;
9855         break;
9856       case 64:
9857         RC = &AMDGPU::VReg_64RegClass;
9858         break;
9859       case 96:
9860         RC = &AMDGPU::VReg_96RegClass;
9861         break;
9862       case 128:
9863         RC = &AMDGPU::VReg_128RegClass;
9864         break;
9865       case 160:
9866         RC = &AMDGPU::VReg_160RegClass;
9867         break;
9868       case 256:
9869         RC = &AMDGPU::VReg_256RegClass;
9870         break;
9871       case 512:
9872         RC = &AMDGPU::VReg_512RegClass;
9873         break;
9874       }
9875       break;
9876     }
9877     // We actually support i128, i16 and f16 as inline parameters
9878     // even if they are not reported as legal
9879     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
9880                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
9881       return std::make_pair(0U, RC);
9882   }
9883 
9884   if (Constraint.size() > 1) {
9885     if (Constraint[1] == 'v') {
9886       RC = &AMDGPU::VGPR_32RegClass;
9887     } else if (Constraint[1] == 's') {
9888       RC = &AMDGPU::SGPR_32RegClass;
9889     }
9890 
9891     if (RC) {
9892       uint32_t Idx;
9893       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
9894       if (!Failed && Idx < RC->getNumRegs())
9895         return std::make_pair(RC->getRegister(Idx), RC);
9896     }
9897   }
9898   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9899 }
9900 
9901 SITargetLowering::ConstraintType
9902 SITargetLowering::getConstraintType(StringRef Constraint) const {
9903   if (Constraint.size() == 1) {
9904     switch (Constraint[0]) {
9905     default: break;
9906     case 's':
9907     case 'v':
9908       return C_RegisterClass;
9909     }
9910   }
9911   return TargetLowering::getConstraintType(Constraint);
9912 }
9913 
9914 // Figure out which registers should be reserved for stack access. Only after
9915 // the function is legalized do we know all of the non-spill stack objects or if
9916 // calls are present.
9917 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
9918   MachineRegisterInfo &MRI = MF.getRegInfo();
9919   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9920   const MachineFrameInfo &MFI = MF.getFrameInfo();
9921   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
9922 
9923   if (Info->isEntryFunction()) {
9924     // Callable functions have fixed registers used for stack access.
9925     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
9926   }
9927 
9928   // We have to assume the SP is needed in case there are calls in the function
9929   // during lowering. Calls are only detected after the function is
9930   // lowered. We're about to reserve registers, so don't bother using it if we
9931   // aren't really going to use it.
9932   bool NeedSP = !Info->isEntryFunction() ||
9933     MFI.hasVarSizedObjects() ||
9934     MFI.hasCalls();
9935 
9936   if (NeedSP) {
9937     unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
9938     Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
9939 
9940     assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
9941     assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
9942                                Info->getStackPtrOffsetReg()));
9943     if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
9944       MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
9945   }
9946 
9947   // We need to worry about replacing the default register with itself in case
9948   // of MIR testcases missing the MFI.
9949   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
9950     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
9951 
9952   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
9953     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
9954 
9955   if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
9956     MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
9957                        Info->getScratchWaveOffsetReg());
9958   }
9959 
9960   Info->limitOccupancy(MF);
9961 
9962   TargetLoweringBase::finalizeLowering(MF);
9963 }
9964 
9965 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
9966                                                      KnownBits &Known,
9967                                                      const APInt &DemandedElts,
9968                                                      const SelectionDAG &DAG,
9969                                                      unsigned Depth) const {
9970   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
9971                                                 DAG, Depth);
9972 
9973   if (getSubtarget()->enableHugePrivateBuffer())
9974     return;
9975 
9976   // Technically it may be possible to have a dispatch with a single workitem
9977   // that uses the full private memory size, but that's not really useful. We
9978   // can't use vaddr in MUBUF instructions if we don't know the address
9979   // calculation won't overflow, so assume the sign bit is never set.
9980   Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);
9981 }
9982 
9983 unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9984   const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
9985   const unsigned CacheLineAlign = 6; // log2(64)
9986 
9987   // Pre-GFX10 target did not benefit from loop alignment
9988   if (!ML || DisableLoopAlignment ||
9989       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
9990       getSubtarget()->hasInstFwdPrefetchBug())
9991     return PrefAlign;
9992 
9993   // On GFX10 I$ is 4 x 64 bytes cache lines.
9994   // By default prefetcher keeps one cache line behind and reads two ahead.
9995   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
9996   // behind and one ahead.
9997   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
9998   // If loop fits 64 bytes it always spans no more than two cache lines and
9999   // does not need an alignment.
10000   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10001   // Else if loop is less or equal 192 bytes we need two lines behind.
10002 
10003   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10004   const MachineBasicBlock *Header = ML->getHeader();
10005   if (Header->getAlignment() != PrefAlign)
10006     return Header->getAlignment(); // Already processed.
10007 
10008   unsigned LoopSize = 0;
10009   for (const MachineBasicBlock *MBB : ML->blocks()) {
10010     // If inner loop block is aligned assume in average half of the alignment
10011     // size to be added as nops.
10012     if (MBB != Header)
10013       LoopSize += (1 << MBB->getAlignment()) / 2;
10014 
10015     for (const MachineInstr &MI : *MBB) {
10016       LoopSize += TII->getInstSizeInBytes(MI);
10017       if (LoopSize > 192)
10018         return PrefAlign;
10019     }
10020   }
10021 
10022   if (LoopSize <= 64)
10023     return PrefAlign;
10024 
10025   if (LoopSize <= 128)
10026     return CacheLineAlign;
10027 
10028   // If any of parent loops is surrounded by prefetch instructions do not
10029   // insert new for inner loop, which would reset parent's settings.
10030   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10031     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10032       auto I = Exit->getFirstNonDebugInstr();
10033       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10034         return CacheLineAlign;
10035     }
10036   }
10037 
10038   MachineBasicBlock *Pre = ML->getLoopPreheader();
10039   MachineBasicBlock *Exit = ML->getExitBlock();
10040 
10041   if (Pre && Exit) {
10042     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10043             TII->get(AMDGPU::S_INST_PREFETCH))
10044       .addImm(1); // prefetch 2 lines behind PC
10045 
10046     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10047             TII->get(AMDGPU::S_INST_PREFETCH))
10048       .addImm(2); // prefetch 1 line behind PC
10049   }
10050 
10051   return CacheLineAlign;
10052 }
10053 
10054 LLVM_ATTRIBUTE_UNUSED
10055 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10056   assert(N->getOpcode() == ISD::CopyFromReg);
10057   do {
10058     // Follow the chain until we find an INLINEASM node.
10059     N = N->getOperand(0).getNode();
10060     if (N->getOpcode() == ISD::INLINEASM ||
10061         N->getOpcode() == ISD::INLINEASM_BR)
10062       return true;
10063   } while (N->getOpcode() == ISD::CopyFromReg);
10064   return false;
10065 }
10066 
10067 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10068   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10069 {
10070   switch (N->getOpcode()) {
10071     case ISD::CopyFromReg:
10072     {
10073       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10074       const MachineFunction * MF = FLI->MF;
10075       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10076       const MachineRegisterInfo &MRI = MF->getRegInfo();
10077       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10078       unsigned Reg = R->getReg();
10079       if (TRI.isPhysicalRegister(Reg))
10080         return !TRI.isSGPRReg(MRI, Reg);
10081 
10082       if (MRI.isLiveIn(Reg)) {
10083         // workitem.id.x workitem.id.y workitem.id.z
10084         // Any VGPR formal argument is also considered divergent
10085         if (!TRI.isSGPRReg(MRI, Reg))
10086           return true;
10087         // Formal arguments of non-entry functions
10088         // are conservatively considered divergent
10089         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10090           return true;
10091         return false;
10092       }
10093       const Value *V = FLI->getValueFromVirtualReg(Reg);
10094       if (V)
10095         return KDA->isDivergent(V);
10096       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10097       return !TRI.isSGPRReg(MRI, Reg);
10098     }
10099     break;
10100     case ISD::LOAD: {
10101       const LoadSDNode *L = cast<LoadSDNode>(N);
10102       unsigned AS = L->getAddressSpace();
10103       // A flat load may access private memory.
10104       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10105     } break;
10106     case ISD::CALLSEQ_END:
10107     return true;
10108     break;
10109     case ISD::INTRINSIC_WO_CHAIN:
10110     {
10111 
10112     }
10113       return AMDGPU::isIntrinsicSourceOfDivergence(
10114       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10115     case ISD::INTRINSIC_W_CHAIN:
10116       return AMDGPU::isIntrinsicSourceOfDivergence(
10117       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10118     // In some cases intrinsics that are a source of divergence have been
10119     // lowered to AMDGPUISD so we also need to check those too.
10120     case AMDGPUISD::INTERP_MOV:
10121     case AMDGPUISD::INTERP_P1:
10122     case AMDGPUISD::INTERP_P2:
10123       return true;
10124   }
10125   return false;
10126 }
10127 
10128 bool SITargetLowering::denormalsEnabledForType(EVT VT) const {
10129   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10130   case MVT::f32:
10131     return Subtarget->hasFP32Denormals();
10132   case MVT::f64:
10133     return Subtarget->hasFP64Denormals();
10134   case MVT::f16:
10135     return Subtarget->hasFP16Denormals();
10136   default:
10137     return false;
10138   }
10139 }
10140 
10141 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10142                                                     const SelectionDAG &DAG,
10143                                                     bool SNaN,
10144                                                     unsigned Depth) const {
10145   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10146     const MachineFunction &MF = DAG.getMachineFunction();
10147     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10148 
10149     if (Info->getMode().DX10Clamp)
10150       return true; // Clamped to 0.
10151     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10152   }
10153 
10154   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10155                                                             SNaN, Depth);
10156 }
10157 
10158 TargetLowering::AtomicExpansionKind
10159 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10160   switch (RMW->getOperation()) {
10161   case AtomicRMWInst::FAdd: {
10162     Type *Ty = RMW->getType();
10163 
10164     // We don't have a way to support 16-bit atomics now, so just leave them
10165     // as-is.
10166     if (Ty->isHalfTy())
10167       return AtomicExpansionKind::None;
10168 
10169     if (!Ty->isFloatTy())
10170       return AtomicExpansionKind::CmpXChg;
10171 
10172     // TODO: Do have these for flat. Older targets also had them for buffers.
10173     unsigned AS = RMW->getPointerAddressSpace();
10174     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10175       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10176   }
10177   default:
10178     break;
10179   }
10180 
10181   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10182 }
10183