1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #if defined(_MSC_VER) || defined(__MINGW32__)
15 // Provide M_PI.
16 #define _USE_MATH_DEFINES
17 #endif
18 
19 #include "SIISelLowering.h"
20 #include "AMDGPU.h"
21 #include "AMDGPUSubtarget.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
24 #include "SIDefines.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "Utils/AMDGPUBaseInfo.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/CallingConvLower.h"
41 #include "llvm/CodeGen/DAGCombine.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineLoopInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
93 static cl::opt<bool> DisableLoopAlignment(
94   "amdgpu-disable-loop-alignment",
95   cl::desc("Do not align and prefetch loops"),
96   cl::init(false));
97 
98 static cl::opt<bool> VGPRReserveforSGPRSpill(
99     "amdgpu-reserve-vgpr-for-sgpr-spill",
100     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
101 
102 static bool hasFP32Denormals(const MachineFunction &MF) {
103   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
104   return Info->getMode().allFP32Denormals();
105 }
106 
107 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
108   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
109   return Info->getMode().allFP64FP16Denormals();
110 }
111 
112 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
113   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
114   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
115     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
116       return AMDGPU::SGPR0 + Reg;
117     }
118   }
119   llvm_unreachable("Cannot allocate sgpr");
120 }
121 
122 SITargetLowering::SITargetLowering(const TargetMachine &TM,
123                                    const GCNSubtarget &STI)
124     : AMDGPUTargetLowering(TM, STI),
125       Subtarget(&STI) {
126   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
127   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
128 
129   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
130   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
131 
132   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
133   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
134   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
135 
136   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
137   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
138 
139   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
140   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
141 
142   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
143   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
144 
145   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
146   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
147 
148   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
149   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
150 
151   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
152   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
153 
154   if (Subtarget->has16BitInsts()) {
155     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
156     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
157 
158     // Unless there are also VOP3P operations, not operations are really legal.
159     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
160     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
161     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
162     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
163   }
164 
165   if (Subtarget->hasMAIInsts()) {
166     addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
167     addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
168   }
169 
170   computeRegisterProperties(Subtarget->getRegisterInfo());
171 
172   // The boolean content concept here is too inflexible. Compares only ever
173   // really produce a 1-bit result. Any copy/extend from these will turn into a
174   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
175   // it's what most targets use.
176   setBooleanContents(ZeroOrOneBooleanContent);
177   setBooleanVectorContents(ZeroOrOneBooleanContent);
178 
179   // We need to custom lower vector stores from local memory
180   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
181   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
182   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
183   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
184   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
185   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
186   setOperationAction(ISD::LOAD, MVT::i1, Custom);
187   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
188 
189   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
190   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
191   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
192   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
193   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
194   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
195   setOperationAction(ISD::STORE, MVT::i1, Custom);
196   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
197 
198   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
199   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
200   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
201   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
202   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
203   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
204   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
205   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
206   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
207   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
208   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
209   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
210   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
211   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
212   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
213   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
214 
215   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
216   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
217 
218   setOperationAction(ISD::SELECT, MVT::i1, Promote);
219   setOperationAction(ISD::SELECT, MVT::i64, Custom);
220   setOperationAction(ISD::SELECT, MVT::f64, Promote);
221   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
222 
223   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
224   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
225   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
226   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
227   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
228 
229   setOperationAction(ISD::SETCC, MVT::i1, Promote);
230   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
231   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
232   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
233 
234   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
235   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
236 
237   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
245 
246   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
247   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
248   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
249   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
250   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
251   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
252 
253   setOperationAction(ISD::UADDO, MVT::i32, Legal);
254   setOperationAction(ISD::USUBO, MVT::i32, Legal);
255 
256   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
257   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
258 
259   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
260   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
261   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
262 
263 #if 0
264   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
265   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
266 #endif
267 
268   // We only support LOAD/STORE and vector manipulation ops for vectors
269   // with > 4 elements.
270   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
271                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
272                   MVT::v32i32, MVT::v32f32 }) {
273     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
274       switch (Op) {
275       case ISD::LOAD:
276       case ISD::STORE:
277       case ISD::BUILD_VECTOR:
278       case ISD::BITCAST:
279       case ISD::EXTRACT_VECTOR_ELT:
280       case ISD::INSERT_VECTOR_ELT:
281       case ISD::INSERT_SUBVECTOR:
282       case ISD::EXTRACT_SUBVECTOR:
283       case ISD::SCALAR_TO_VECTOR:
284         break;
285       case ISD::CONCAT_VECTORS:
286         setOperationAction(Op, VT, Custom);
287         break;
288       default:
289         setOperationAction(Op, VT, Expand);
290         break;
291       }
292     }
293   }
294 
295   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
296 
297   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
298   // is expanded to avoid having two separate loops in case the index is a VGPR.
299 
300   // Most operations are naturally 32-bit vector operations. We only support
301   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
302   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
303     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
305 
306     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
307     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
308 
309     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
310     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
311 
312     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
313     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
314   }
315 
316   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
317   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
318   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
319   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
320 
321   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
322   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
323 
324   // Avoid stack access for these.
325   // TODO: Generalize to more vector types.
326   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
327   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
328   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
329   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
330 
331   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
332   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
333   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
334   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
335   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
336 
337   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
338   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
339   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
340 
341   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
342   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
343   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
344   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
345 
346   // Deal with vec3 vector operations when widened to vec4.
347   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
348   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
349   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
350   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
351 
352   // Deal with vec5 vector operations when widened to vec8.
353   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
354   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
355   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
356   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
357 
358   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
359   // and output demarshalling
360   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
361   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
362 
363   // We can't return success/failure, only the old value,
364   // let LLVM add the comparison
365   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
366   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
367 
368   if (Subtarget->hasFlatAddressSpace()) {
369     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
370     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
371   }
372 
373   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
374 
375   // FIXME: This should be narrowed to i32, but that only happens if i64 is
376   // illegal.
377   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
378   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
379   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
380 
381   // On SI this is s_memtime and s_memrealtime on VI.
382   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
383   setOperationAction(ISD::TRAP, MVT::Other, Custom);
384   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
385 
386   if (Subtarget->has16BitInsts()) {
387     setOperationAction(ISD::FPOW, MVT::f16, Promote);
388     setOperationAction(ISD::FLOG, MVT::f16, Custom);
389     setOperationAction(ISD::FEXP, MVT::f16, Custom);
390     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
391   }
392 
393   // v_mad_f32 does not support denormals. We report it as unconditionally
394   // legal, and the context where it is formed will disallow it when fp32
395   // denormals are enabled.
396   setOperationAction(ISD::FMAD, MVT::f32, Legal);
397 
398   if (!Subtarget->hasBFI()) {
399     // fcopysign can be done in a single instruction with BFI.
400     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
401     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
402   }
403 
404   if (!Subtarget->hasBCNT(32))
405     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
406 
407   if (!Subtarget->hasBCNT(64))
408     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
409 
410   if (Subtarget->hasFFBH())
411     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
412 
413   if (Subtarget->hasFFBL())
414     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
415 
416   // We only really have 32-bit BFE instructions (and 16-bit on VI).
417   //
418   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
419   // effort to match them now. We want this to be false for i64 cases when the
420   // extraction isn't restricted to the upper or lower half. Ideally we would
421   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
422   // span the midpoint are probably relatively rare, so don't worry about them
423   // for now.
424   if (Subtarget->hasBFE())
425     setHasExtractBitsInsn(true);
426 
427   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
428   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
429   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
430   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
431 
432 
433   // These are really only legal for ieee_mode functions. We should be avoiding
434   // them for functions that don't have ieee_mode enabled, so just say they are
435   // legal.
436   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
437   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
438   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
439   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
440 
441 
442   if (Subtarget->haveRoundOpsF64()) {
443     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
444     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
445     setOperationAction(ISD::FRINT, MVT::f64, Legal);
446   } else {
447     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
448     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
449     setOperationAction(ISD::FRINT, MVT::f64, Custom);
450     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
451   }
452 
453   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
454 
455   setOperationAction(ISD::FSIN, MVT::f32, Custom);
456   setOperationAction(ISD::FCOS, MVT::f32, Custom);
457   setOperationAction(ISD::FDIV, MVT::f32, Custom);
458   setOperationAction(ISD::FDIV, MVT::f64, Custom);
459 
460   if (Subtarget->has16BitInsts()) {
461     setOperationAction(ISD::Constant, MVT::i16, Legal);
462 
463     setOperationAction(ISD::SMIN, MVT::i16, Legal);
464     setOperationAction(ISD::SMAX, MVT::i16, Legal);
465 
466     setOperationAction(ISD::UMIN, MVT::i16, Legal);
467     setOperationAction(ISD::UMAX, MVT::i16, Legal);
468 
469     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
470     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
471 
472     setOperationAction(ISD::ROTR, MVT::i16, Promote);
473     setOperationAction(ISD::ROTL, MVT::i16, Promote);
474 
475     setOperationAction(ISD::SDIV, MVT::i16, Promote);
476     setOperationAction(ISD::UDIV, MVT::i16, Promote);
477     setOperationAction(ISD::SREM, MVT::i16, Promote);
478     setOperationAction(ISD::UREM, MVT::i16, Promote);
479 
480     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
481 
482     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
484     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
485     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
486     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
487 
488     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
489 
490     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
491 
492     setOperationAction(ISD::LOAD, MVT::i16, Custom);
493 
494     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
495 
496     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
497     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
498     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
499     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
500 
501     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
502     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
503 
504     // F16 - Constant Actions.
505     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
506 
507     // F16 - Load/Store Actions.
508     setOperationAction(ISD::LOAD, MVT::f16, Promote);
509     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
510     setOperationAction(ISD::STORE, MVT::f16, Promote);
511     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
512 
513     // F16 - VOP1 Actions.
514     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
515     setOperationAction(ISD::FCOS, MVT::f16, Custom);
516     setOperationAction(ISD::FSIN, MVT::f16, Custom);
517 
518     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
519     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
520 
521     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
522     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
523     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
524     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
525     setOperationAction(ISD::FROUND, MVT::f16, Custom);
526 
527     // F16 - VOP2 Actions.
528     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
529     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
530 
531     setOperationAction(ISD::FDIV, MVT::f16, Custom);
532 
533     // F16 - VOP3 Actions.
534     setOperationAction(ISD::FMA, MVT::f16, Legal);
535     if (STI.hasMadF16())
536       setOperationAction(ISD::FMAD, MVT::f16, Legal);
537 
538     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
539       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
540         switch (Op) {
541         case ISD::LOAD:
542         case ISD::STORE:
543         case ISD::BUILD_VECTOR:
544         case ISD::BITCAST:
545         case ISD::EXTRACT_VECTOR_ELT:
546         case ISD::INSERT_VECTOR_ELT:
547         case ISD::INSERT_SUBVECTOR:
548         case ISD::EXTRACT_SUBVECTOR:
549         case ISD::SCALAR_TO_VECTOR:
550           break;
551         case ISD::CONCAT_VECTORS:
552           setOperationAction(Op, VT, Custom);
553           break;
554         default:
555           setOperationAction(Op, VT, Expand);
556           break;
557         }
558       }
559     }
560 
561     // v_perm_b32 can handle either of these.
562     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
563     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
564     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
565 
566     // XXX - Do these do anything? Vector constants turn into build_vector.
567     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
568     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
569 
570     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
571     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
572 
573     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
574     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
575     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
576     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
577 
578     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
579     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
580     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
581     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
582 
583     setOperationAction(ISD::AND, MVT::v2i16, Promote);
584     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
585     setOperationAction(ISD::OR, MVT::v2i16, Promote);
586     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
587     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
588     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
589 
590     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
591     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
592     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
593     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
594 
595     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
596     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
597     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
598     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
599 
600     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
601     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
602     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
603     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
604 
605     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
606     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
607     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
608 
609     if (!Subtarget->hasVOP3PInsts()) {
610       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
611       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
612     }
613 
614     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
615     // This isn't really legal, but this avoids the legalizer unrolling it (and
616     // allows matching fneg (fabs x) patterns)
617     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
618 
619     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
620     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
621     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
622     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
623 
624     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
625     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
626 
627     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
628     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
629   }
630 
631   if (Subtarget->hasVOP3PInsts()) {
632     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
633     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
634     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
635     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
636     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
637     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
638     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
639     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
640     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
641     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
642 
643     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
644     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
645     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
646 
647     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
648     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
649 
650     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
653     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
654 
655     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
656     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
657 
658     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
659     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
660     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
661     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
662     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
663     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
664 
665     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
666     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
667     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
668     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
669 
670     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
671     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
672     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
673 
674     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
675     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
676 
677     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
678     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
679     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
680 
681     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
682     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
683     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
684   }
685 
686   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
687   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
688 
689   if (Subtarget->has16BitInsts()) {
690     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
691     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
692     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
693     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
694   } else {
695     // Legalization hack.
696     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
697     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
698 
699     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
700     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
701   }
702 
703   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
704     setOperationAction(ISD::SELECT, VT, Custom);
705   }
706 
707   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
708   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
709   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
710   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
711   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
712   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
713   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
714 
715   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
716   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
717   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
718   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
719   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
720   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
721   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
722   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
723   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
724 
725   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
726   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
727   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
728   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
729   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
730   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
731   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
732   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
733 
734   setTargetDAGCombine(ISD::ADD);
735   setTargetDAGCombine(ISD::ADDCARRY);
736   setTargetDAGCombine(ISD::SUB);
737   setTargetDAGCombine(ISD::SUBCARRY);
738   setTargetDAGCombine(ISD::FADD);
739   setTargetDAGCombine(ISD::FSUB);
740   setTargetDAGCombine(ISD::FMINNUM);
741   setTargetDAGCombine(ISD::FMAXNUM);
742   setTargetDAGCombine(ISD::FMINNUM_IEEE);
743   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
744   setTargetDAGCombine(ISD::FMA);
745   setTargetDAGCombine(ISD::SMIN);
746   setTargetDAGCombine(ISD::SMAX);
747   setTargetDAGCombine(ISD::UMIN);
748   setTargetDAGCombine(ISD::UMAX);
749   setTargetDAGCombine(ISD::SETCC);
750   setTargetDAGCombine(ISD::AND);
751   setTargetDAGCombine(ISD::OR);
752   setTargetDAGCombine(ISD::XOR);
753   setTargetDAGCombine(ISD::SINT_TO_FP);
754   setTargetDAGCombine(ISD::UINT_TO_FP);
755   setTargetDAGCombine(ISD::FCANONICALIZE);
756   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
757   setTargetDAGCombine(ISD::ZERO_EXTEND);
758   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
759   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
760   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
761 
762   // All memory operations. Some folding on the pointer operand is done to help
763   // matching the constant offsets in the addressing modes.
764   setTargetDAGCombine(ISD::LOAD);
765   setTargetDAGCombine(ISD::STORE);
766   setTargetDAGCombine(ISD::ATOMIC_LOAD);
767   setTargetDAGCombine(ISD::ATOMIC_STORE);
768   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
769   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
770   setTargetDAGCombine(ISD::ATOMIC_SWAP);
771   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
772   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
773   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
774   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
775   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
776   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
777   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
778   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
779   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
780   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
781   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
782 
783   setSchedulingPreference(Sched::RegPressure);
784 }
785 
786 const GCNSubtarget *SITargetLowering::getSubtarget() const {
787   return Subtarget;
788 }
789 
790 //===----------------------------------------------------------------------===//
791 // TargetLowering queries
792 //===----------------------------------------------------------------------===//
793 
794 // v_mad_mix* support a conversion from f16 to f32.
795 //
796 // There is only one special case when denormals are enabled we don't currently,
797 // where this is OK to use.
798 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
799                                        EVT DestVT, EVT SrcVT) const {
800   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
801           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
802     DestVT.getScalarType() == MVT::f32 &&
803     SrcVT.getScalarType() == MVT::f16 &&
804     // TODO: This probably only requires no input flushing?
805     !hasFP32Denormals(DAG.getMachineFunction());
806 }
807 
808 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
809   // SI has some legal vector types, but no legal vector operations. Say no
810   // shuffles are legal in order to prefer scalarizing some vector operations.
811   return false;
812 }
813 
814 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
815                                                     CallingConv::ID CC,
816                                                     EVT VT) const {
817   if (CC == CallingConv::AMDGPU_KERNEL)
818     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
819 
820   if (VT.isVector()) {
821     EVT ScalarVT = VT.getScalarType();
822     unsigned Size = ScalarVT.getSizeInBits();
823     if (Size == 32)
824       return ScalarVT.getSimpleVT();
825 
826     if (Size > 32)
827       return MVT::i32;
828 
829     if (Size == 16 && Subtarget->has16BitInsts())
830       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
831   } else if (VT.getSizeInBits() > 32)
832     return MVT::i32;
833 
834   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
835 }
836 
837 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
838                                                          CallingConv::ID CC,
839                                                          EVT VT) const {
840   if (CC == CallingConv::AMDGPU_KERNEL)
841     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
842 
843   if (VT.isVector()) {
844     unsigned NumElts = VT.getVectorNumElements();
845     EVT ScalarVT = VT.getScalarType();
846     unsigned Size = ScalarVT.getSizeInBits();
847 
848     if (Size == 32)
849       return NumElts;
850 
851     if (Size > 32)
852       return NumElts * ((Size + 31) / 32);
853 
854     if (Size == 16 && Subtarget->has16BitInsts())
855       return (NumElts + 1) / 2;
856   } else if (VT.getSizeInBits() > 32)
857     return (VT.getSizeInBits() + 31) / 32;
858 
859   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
860 }
861 
862 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
863   LLVMContext &Context, CallingConv::ID CC,
864   EVT VT, EVT &IntermediateVT,
865   unsigned &NumIntermediates, MVT &RegisterVT) const {
866   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
867     unsigned NumElts = VT.getVectorNumElements();
868     EVT ScalarVT = VT.getScalarType();
869     unsigned Size = ScalarVT.getSizeInBits();
870     if (Size == 32) {
871       RegisterVT = ScalarVT.getSimpleVT();
872       IntermediateVT = RegisterVT;
873       NumIntermediates = NumElts;
874       return NumIntermediates;
875     }
876 
877     if (Size > 32) {
878       RegisterVT = MVT::i32;
879       IntermediateVT = RegisterVT;
880       NumIntermediates = NumElts * ((Size + 31) / 32);
881       return NumIntermediates;
882     }
883 
884     // FIXME: We should fix the ABI to be the same on targets without 16-bit
885     // support, but unless we can properly handle 3-vectors, it will be still be
886     // inconsistent.
887     if (Size == 16 && Subtarget->has16BitInsts()) {
888       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
889       IntermediateVT = RegisterVT;
890       NumIntermediates = (NumElts + 1) / 2;
891       return NumIntermediates;
892     }
893   }
894 
895   return TargetLowering::getVectorTypeBreakdownForCallingConv(
896     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
897 }
898 
899 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
900   assert(DMaskLanes != 0);
901 
902   if (auto *VT = dyn_cast<VectorType>(Ty)) {
903     unsigned NumElts = std::min(DMaskLanes,
904                                 static_cast<unsigned>(VT->getNumElements()));
905     return EVT::getVectorVT(Ty->getContext(),
906                             EVT::getEVT(VT->getElementType()),
907                             NumElts);
908   }
909 
910   return EVT::getEVT(Ty);
911 }
912 
913 // Peek through TFE struct returns to only use the data size.
914 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
915   auto *ST = dyn_cast<StructType>(Ty);
916   if (!ST)
917     return memVTFromImageData(Ty, DMaskLanes);
918 
919   // Some intrinsics return an aggregate type - special case to work out the
920   // correct memVT.
921   //
922   // Only limited forms of aggregate type currently expected.
923   if (ST->getNumContainedTypes() != 2 ||
924       !ST->getContainedType(1)->isIntegerTy(32))
925     return EVT();
926   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
927 }
928 
929 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
930                                           const CallInst &CI,
931                                           MachineFunction &MF,
932                                           unsigned IntrID) const {
933   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
934           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
935     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
936                                                   (Intrinsic::ID)IntrID);
937     if (Attr.hasFnAttribute(Attribute::ReadNone))
938       return false;
939 
940     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
941 
942     if (RsrcIntr->IsImage) {
943       Info.ptrVal = MFI->getImagePSV(
944         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
945         CI.getArgOperand(RsrcIntr->RsrcArg));
946       Info.align.reset();
947     } else {
948       Info.ptrVal = MFI->getBufferPSV(
949         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
950         CI.getArgOperand(RsrcIntr->RsrcArg));
951     }
952 
953     Info.flags = MachineMemOperand::MODereferenceable;
954     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
955       unsigned DMaskLanes = 4;
956 
957       if (RsrcIntr->IsImage) {
958         const AMDGPU::ImageDimIntrinsicInfo *Intr
959           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
960         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
961           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
962 
963         if (!BaseOpcode->Gather4) {
964           // If this isn't a gather, we may have excess loaded elements in the
965           // IR type. Check the dmask for the real number of elements loaded.
966           unsigned DMask
967             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
968           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
969         }
970 
971         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
972       } else
973         Info.memVT = EVT::getEVT(CI.getType());
974 
975       // FIXME: What does alignment mean for an image?
976       Info.opc = ISD::INTRINSIC_W_CHAIN;
977       Info.flags |= MachineMemOperand::MOLoad;
978     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
979       Info.opc = ISD::INTRINSIC_VOID;
980 
981       Type *DataTy = CI.getArgOperand(0)->getType();
982       if (RsrcIntr->IsImage) {
983         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
984         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
985         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
986       } else
987         Info.memVT = EVT::getEVT(DataTy);
988 
989       Info.flags |= MachineMemOperand::MOStore;
990     } else {
991       // Atomic
992       Info.opc = ISD::INTRINSIC_W_CHAIN;
993       Info.memVT = MVT::getVT(CI.getType());
994       Info.flags = MachineMemOperand::MOLoad |
995                    MachineMemOperand::MOStore |
996                    MachineMemOperand::MODereferenceable;
997 
998       // XXX - Should this be volatile without known ordering?
999       Info.flags |= MachineMemOperand::MOVolatile;
1000     }
1001     return true;
1002   }
1003 
1004   switch (IntrID) {
1005   case Intrinsic::amdgcn_atomic_inc:
1006   case Intrinsic::amdgcn_atomic_dec:
1007   case Intrinsic::amdgcn_ds_ordered_add:
1008   case Intrinsic::amdgcn_ds_ordered_swap:
1009   case Intrinsic::amdgcn_ds_fadd:
1010   case Intrinsic::amdgcn_ds_fmin:
1011   case Intrinsic::amdgcn_ds_fmax: {
1012     Info.opc = ISD::INTRINSIC_W_CHAIN;
1013     Info.memVT = MVT::getVT(CI.getType());
1014     Info.ptrVal = CI.getOperand(0);
1015     Info.align.reset();
1016     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1017 
1018     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1019     if (!Vol->isZero())
1020       Info.flags |= MachineMemOperand::MOVolatile;
1021 
1022     return true;
1023   }
1024   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1025     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1026 
1027     Info.opc = ISD::INTRINSIC_VOID;
1028     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1029     Info.ptrVal = MFI->getBufferPSV(
1030       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1031       CI.getArgOperand(1));
1032     Info.align.reset();
1033     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1034 
1035     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1036     if (!Vol || !Vol->isZero())
1037       Info.flags |= MachineMemOperand::MOVolatile;
1038 
1039     return true;
1040   }
1041   case Intrinsic::amdgcn_global_atomic_fadd: {
1042     Info.opc = ISD::INTRINSIC_VOID;
1043     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1044                             ->getPointerElementType());
1045     Info.ptrVal = CI.getOperand(0);
1046     Info.align.reset();
1047     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1048 
1049     return true;
1050   }
1051   case Intrinsic::amdgcn_ds_append:
1052   case Intrinsic::amdgcn_ds_consume: {
1053     Info.opc = ISD::INTRINSIC_W_CHAIN;
1054     Info.memVT = MVT::getVT(CI.getType());
1055     Info.ptrVal = CI.getOperand(0);
1056     Info.align.reset();
1057     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1058 
1059     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1060     if (!Vol->isZero())
1061       Info.flags |= MachineMemOperand::MOVolatile;
1062 
1063     return true;
1064   }
1065   case Intrinsic::amdgcn_ds_gws_init:
1066   case Intrinsic::amdgcn_ds_gws_barrier:
1067   case Intrinsic::amdgcn_ds_gws_sema_v:
1068   case Intrinsic::amdgcn_ds_gws_sema_br:
1069   case Intrinsic::amdgcn_ds_gws_sema_p:
1070   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1071     Info.opc = ISD::INTRINSIC_VOID;
1072 
1073     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1074     Info.ptrVal =
1075         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1076 
1077     // This is an abstract access, but we need to specify a type and size.
1078     Info.memVT = MVT::i32;
1079     Info.size = 4;
1080     Info.align = Align(4);
1081 
1082     Info.flags = MachineMemOperand::MOStore;
1083     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1084       Info.flags = MachineMemOperand::MOLoad;
1085     return true;
1086   }
1087   default:
1088     return false;
1089   }
1090 }
1091 
1092 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1093                                             SmallVectorImpl<Value*> &Ops,
1094                                             Type *&AccessTy) const {
1095   switch (II->getIntrinsicID()) {
1096   case Intrinsic::amdgcn_atomic_inc:
1097   case Intrinsic::amdgcn_atomic_dec:
1098   case Intrinsic::amdgcn_ds_ordered_add:
1099   case Intrinsic::amdgcn_ds_ordered_swap:
1100   case Intrinsic::amdgcn_ds_fadd:
1101   case Intrinsic::amdgcn_ds_fmin:
1102   case Intrinsic::amdgcn_ds_fmax: {
1103     Value *Ptr = II->getArgOperand(0);
1104     AccessTy = II->getType();
1105     Ops.push_back(Ptr);
1106     return true;
1107   }
1108   default:
1109     return false;
1110   }
1111 }
1112 
1113 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1114   if (!Subtarget->hasFlatInstOffsets()) {
1115     // Flat instructions do not have offsets, and only have the register
1116     // address.
1117     return AM.BaseOffs == 0 && AM.Scale == 0;
1118   }
1119 
1120   return AM.Scale == 0 &&
1121          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1122                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1123                                   /*Signed=*/false));
1124 }
1125 
1126 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1127   if (Subtarget->hasFlatGlobalInsts())
1128     return AM.Scale == 0 &&
1129            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1130                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1131                                     /*Signed=*/true));
1132 
1133   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1134       // Assume the we will use FLAT for all global memory accesses
1135       // on VI.
1136       // FIXME: This assumption is currently wrong.  On VI we still use
1137       // MUBUF instructions for the r + i addressing mode.  As currently
1138       // implemented, the MUBUF instructions only work on buffer < 4GB.
1139       // It may be possible to support > 4GB buffers with MUBUF instructions,
1140       // by setting the stride value in the resource descriptor which would
1141       // increase the size limit to (stride * 4GB).  However, this is risky,
1142       // because it has never been validated.
1143     return isLegalFlatAddressingMode(AM);
1144   }
1145 
1146   return isLegalMUBUFAddressingMode(AM);
1147 }
1148 
1149 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1150   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1151   // additionally can do r + r + i with addr64. 32-bit has more addressing
1152   // mode options. Depending on the resource constant, it can also do
1153   // (i64 r0) + (i32 r1) * (i14 i).
1154   //
1155   // Private arrays end up using a scratch buffer most of the time, so also
1156   // assume those use MUBUF instructions. Scratch loads / stores are currently
1157   // implemented as mubuf instructions with offen bit set, so slightly
1158   // different than the normal addr64.
1159   if (!isUInt<12>(AM.BaseOffs))
1160     return false;
1161 
1162   // FIXME: Since we can split immediate into soffset and immediate offset,
1163   // would it make sense to allow any immediate?
1164 
1165   switch (AM.Scale) {
1166   case 0: // r + i or just i, depending on HasBaseReg.
1167     return true;
1168   case 1:
1169     return true; // We have r + r or r + i.
1170   case 2:
1171     if (AM.HasBaseReg) {
1172       // Reject 2 * r + r.
1173       return false;
1174     }
1175 
1176     // Allow 2 * r as r + r
1177     // Or  2 * r + i is allowed as r + r + i.
1178     return true;
1179   default: // Don't allow n * r
1180     return false;
1181   }
1182 }
1183 
1184 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1185                                              const AddrMode &AM, Type *Ty,
1186                                              unsigned AS, Instruction *I) const {
1187   // No global is ever allowed as a base.
1188   if (AM.BaseGV)
1189     return false;
1190 
1191   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1192     return isLegalGlobalAddressingMode(AM);
1193 
1194   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1195       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1196       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1197     // If the offset isn't a multiple of 4, it probably isn't going to be
1198     // correctly aligned.
1199     // FIXME: Can we get the real alignment here?
1200     if (AM.BaseOffs % 4 != 0)
1201       return isLegalMUBUFAddressingMode(AM);
1202 
1203     // There are no SMRD extloads, so if we have to do a small type access we
1204     // will use a MUBUF load.
1205     // FIXME?: We also need to do this if unaligned, but we don't know the
1206     // alignment here.
1207     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1208       return isLegalGlobalAddressingMode(AM);
1209 
1210     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1211       // SMRD instructions have an 8-bit, dword offset on SI.
1212       if (!isUInt<8>(AM.BaseOffs / 4))
1213         return false;
1214     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1215       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1216       // in 8-bits, it can use a smaller encoding.
1217       if (!isUInt<32>(AM.BaseOffs / 4))
1218         return false;
1219     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1220       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1221       if (!isUInt<20>(AM.BaseOffs))
1222         return false;
1223     } else
1224       llvm_unreachable("unhandled generation");
1225 
1226     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1227       return true;
1228 
1229     if (AM.Scale == 1 && AM.HasBaseReg)
1230       return true;
1231 
1232     return false;
1233 
1234   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1235     return isLegalMUBUFAddressingMode(AM);
1236   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1237              AS == AMDGPUAS::REGION_ADDRESS) {
1238     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1239     // field.
1240     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1241     // an 8-bit dword offset but we don't know the alignment here.
1242     if (!isUInt<16>(AM.BaseOffs))
1243       return false;
1244 
1245     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1246       return true;
1247 
1248     if (AM.Scale == 1 && AM.HasBaseReg)
1249       return true;
1250 
1251     return false;
1252   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1253              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1254     // For an unknown address space, this usually means that this is for some
1255     // reason being used for pure arithmetic, and not based on some addressing
1256     // computation. We don't have instructions that compute pointers with any
1257     // addressing modes, so treat them as having no offset like flat
1258     // instructions.
1259     return isLegalFlatAddressingMode(AM);
1260   }
1261 
1262   // Assume a user alias of global for unknown address spaces.
1263   return isLegalGlobalAddressingMode(AM);
1264 }
1265 
1266 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1267                                         const SelectionDAG &DAG) const {
1268   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1269     return (MemVT.getSizeInBits() <= 4 * 32);
1270   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1271     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1272     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1273   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1274     return (MemVT.getSizeInBits() <= 2 * 32);
1275   }
1276   return true;
1277 }
1278 
1279 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1280     unsigned Size, unsigned AddrSpace, unsigned Align,
1281     MachineMemOperand::Flags Flags, bool *IsFast) const {
1282   if (IsFast)
1283     *IsFast = false;
1284 
1285   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1286       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1287     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1288     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1289     // with adjacent offsets.
1290     bool AlignedBy4 = (Align % 4 == 0);
1291     if (IsFast)
1292       *IsFast = AlignedBy4;
1293 
1294     return AlignedBy4;
1295   }
1296 
1297   // FIXME: We have to be conservative here and assume that flat operations
1298   // will access scratch.  If we had access to the IR function, then we
1299   // could determine if any private memory was used in the function.
1300   if (!Subtarget->hasUnalignedScratchAccess() &&
1301       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1302        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1303     bool AlignedBy4 = Align >= 4;
1304     if (IsFast)
1305       *IsFast = AlignedBy4;
1306 
1307     return AlignedBy4;
1308   }
1309 
1310   if (Subtarget->hasUnalignedBufferAccess()) {
1311     // If we have an uniform constant load, it still requires using a slow
1312     // buffer instruction if unaligned.
1313     if (IsFast) {
1314       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1315       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1316       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1317                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1318         Align >= 4 : Align != 2;
1319     }
1320 
1321     return true;
1322   }
1323 
1324   // Smaller than dword value must be aligned.
1325   if (Size < 32)
1326     return false;
1327 
1328   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1329   // byte-address are ignored, thus forcing Dword alignment.
1330   // This applies to private, global, and constant memory.
1331   if (IsFast)
1332     *IsFast = true;
1333 
1334   return Size >= 32 && Align >= 4;
1335 }
1336 
1337 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1338     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1339     bool *IsFast) const {
1340   if (IsFast)
1341     *IsFast = false;
1342 
1343   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1344   // which isn't a simple VT.
1345   // Until MVT is extended to handle this, simply check for the size and
1346   // rely on the condition below: allow accesses if the size is a multiple of 4.
1347   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1348                            VT.getStoreSize() > 16)) {
1349     return false;
1350   }
1351 
1352   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1353                                             Align, Flags, IsFast);
1354 }
1355 
1356 EVT SITargetLowering::getOptimalMemOpType(
1357     const MemOp &Op, const AttributeList &FuncAttributes) const {
1358   // FIXME: Should account for address space here.
1359 
1360   // The default fallback uses the private pointer size as a guess for a type to
1361   // use. Make sure we switch these to 64-bit accesses.
1362 
1363   if (Op.size() >= 16 &&
1364       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1365     return MVT::v4i32;
1366 
1367   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1368     return MVT::v2i32;
1369 
1370   // Use the default.
1371   return MVT::Other;
1372 }
1373 
1374 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1375                                            unsigned DestAS) const {
1376   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1377 }
1378 
1379 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1380   const MemSDNode *MemNode = cast<MemSDNode>(N);
1381   const Value *Ptr = MemNode->getMemOperand()->getValue();
1382   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1383   return I && I->getMetadata("amdgpu.noclobber");
1384 }
1385 
1386 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1387                                            unsigned DestAS) const {
1388   // Flat -> private/local is a simple truncate.
1389   // Flat -> global is no-op
1390   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1391     return true;
1392 
1393   return isNoopAddrSpaceCast(SrcAS, DestAS);
1394 }
1395 
1396 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1397   const MemSDNode *MemNode = cast<MemSDNode>(N);
1398 
1399   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1400 }
1401 
1402 TargetLoweringBase::LegalizeTypeAction
1403 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1404   int NumElts = VT.getVectorNumElements();
1405   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1406     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1407   return TargetLoweringBase::getPreferredVectorAction(VT);
1408 }
1409 
1410 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1411                                                          Type *Ty) const {
1412   // FIXME: Could be smarter if called for vector constants.
1413   return true;
1414 }
1415 
1416 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1417   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1418     switch (Op) {
1419     case ISD::LOAD:
1420     case ISD::STORE:
1421 
1422     // These operations are done with 32-bit instructions anyway.
1423     case ISD::AND:
1424     case ISD::OR:
1425     case ISD::XOR:
1426     case ISD::SELECT:
1427       // TODO: Extensions?
1428       return true;
1429     default:
1430       return false;
1431     }
1432   }
1433 
1434   // SimplifySetCC uses this function to determine whether or not it should
1435   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1436   if (VT == MVT::i1 && Op == ISD::SETCC)
1437     return false;
1438 
1439   return TargetLowering::isTypeDesirableForOp(Op, VT);
1440 }
1441 
1442 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1443                                                    const SDLoc &SL,
1444                                                    SDValue Chain,
1445                                                    uint64_t Offset) const {
1446   const DataLayout &DL = DAG.getDataLayout();
1447   MachineFunction &MF = DAG.getMachineFunction();
1448   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1449 
1450   const ArgDescriptor *InputPtrReg;
1451   const TargetRegisterClass *RC;
1452 
1453   std::tie(InputPtrReg, RC)
1454     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1455 
1456   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1457   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1458   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1459     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1460 
1461   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1462 }
1463 
1464 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1465                                             const SDLoc &SL) const {
1466   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1467                                                FIRST_IMPLICIT);
1468   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1469 }
1470 
1471 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1472                                          const SDLoc &SL, SDValue Val,
1473                                          bool Signed,
1474                                          const ISD::InputArg *Arg) const {
1475   // First, if it is a widened vector, narrow it.
1476   if (VT.isVector() &&
1477       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1478     EVT NarrowedVT =
1479         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1480                          VT.getVectorNumElements());
1481     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1482                       DAG.getConstant(0, SL, MVT::i32));
1483   }
1484 
1485   // Then convert the vector elements or scalar value.
1486   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1487       VT.bitsLT(MemVT)) {
1488     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1489     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1490   }
1491 
1492   if (MemVT.isFloatingPoint())
1493     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1494   else if (Signed)
1495     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1496   else
1497     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1498 
1499   return Val;
1500 }
1501 
1502 SDValue SITargetLowering::lowerKernargMemParameter(
1503   SelectionDAG &DAG, EVT VT, EVT MemVT,
1504   const SDLoc &SL, SDValue Chain,
1505   uint64_t Offset, unsigned Align, bool Signed,
1506   const ISD::InputArg *Arg) const {
1507   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1508 
1509   // Try to avoid using an extload by loading earlier than the argument address,
1510   // and extracting the relevant bits. The load should hopefully be merged with
1511   // the previous argument.
1512   if (MemVT.getStoreSize() < 4 && Align < 4) {
1513     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1514     int64_t AlignDownOffset = alignDown(Offset, 4);
1515     int64_t OffsetDiff = Offset - AlignDownOffset;
1516 
1517     EVT IntVT = MemVT.changeTypeToInteger();
1518 
1519     // TODO: If we passed in the base kernel offset we could have a better
1520     // alignment than 4, but we don't really need it.
1521     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1522     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1523                                MachineMemOperand::MODereferenceable |
1524                                MachineMemOperand::MOInvariant);
1525 
1526     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1527     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1528 
1529     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1530     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1531     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1532 
1533 
1534     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1535   }
1536 
1537   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1538   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1539                              MachineMemOperand::MODereferenceable |
1540                              MachineMemOperand::MOInvariant);
1541 
1542   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1543   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1544 }
1545 
1546 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1547                                               const SDLoc &SL, SDValue Chain,
1548                                               const ISD::InputArg &Arg) const {
1549   MachineFunction &MF = DAG.getMachineFunction();
1550   MachineFrameInfo &MFI = MF.getFrameInfo();
1551 
1552   if (Arg.Flags.isByVal()) {
1553     unsigned Size = Arg.Flags.getByValSize();
1554     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1555     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1556   }
1557 
1558   unsigned ArgOffset = VA.getLocMemOffset();
1559   unsigned ArgSize = VA.getValVT().getStoreSize();
1560 
1561   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1562 
1563   // Create load nodes to retrieve arguments from the stack.
1564   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1565   SDValue ArgValue;
1566 
1567   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1568   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1569   MVT MemVT = VA.getValVT();
1570 
1571   switch (VA.getLocInfo()) {
1572   default:
1573     break;
1574   case CCValAssign::BCvt:
1575     MemVT = VA.getLocVT();
1576     break;
1577   case CCValAssign::SExt:
1578     ExtType = ISD::SEXTLOAD;
1579     break;
1580   case CCValAssign::ZExt:
1581     ExtType = ISD::ZEXTLOAD;
1582     break;
1583   case CCValAssign::AExt:
1584     ExtType = ISD::EXTLOAD;
1585     break;
1586   }
1587 
1588   ArgValue = DAG.getExtLoad(
1589     ExtType, SL, VA.getLocVT(), Chain, FIN,
1590     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1591     MemVT);
1592   return ArgValue;
1593 }
1594 
1595 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1596   const SIMachineFunctionInfo &MFI,
1597   EVT VT,
1598   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1599   const ArgDescriptor *Reg;
1600   const TargetRegisterClass *RC;
1601 
1602   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1603   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1604 }
1605 
1606 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1607                                    CallingConv::ID CallConv,
1608                                    ArrayRef<ISD::InputArg> Ins,
1609                                    BitVector &Skipped,
1610                                    FunctionType *FType,
1611                                    SIMachineFunctionInfo *Info) {
1612   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1613     const ISD::InputArg *Arg = &Ins[I];
1614 
1615     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1616            "vector type argument should have been split");
1617 
1618     // First check if it's a PS input addr.
1619     if (CallConv == CallingConv::AMDGPU_PS &&
1620         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1621       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1622 
1623       // Inconveniently only the first part of the split is marked as isSplit,
1624       // so skip to the end. We only want to increment PSInputNum once for the
1625       // entire split argument.
1626       if (Arg->Flags.isSplit()) {
1627         while (!Arg->Flags.isSplitEnd()) {
1628           assert((!Arg->VT.isVector() ||
1629                   Arg->VT.getScalarSizeInBits() == 16) &&
1630                  "unexpected vector split in ps argument type");
1631           if (!SkipArg)
1632             Splits.push_back(*Arg);
1633           Arg = &Ins[++I];
1634         }
1635       }
1636 
1637       if (SkipArg) {
1638         // We can safely skip PS inputs.
1639         Skipped.set(Arg->getOrigArgIndex());
1640         ++PSInputNum;
1641         continue;
1642       }
1643 
1644       Info->markPSInputAllocated(PSInputNum);
1645       if (Arg->Used)
1646         Info->markPSInputEnabled(PSInputNum);
1647 
1648       ++PSInputNum;
1649     }
1650 
1651     Splits.push_back(*Arg);
1652   }
1653 }
1654 
1655 // Allocate special inputs passed in VGPRs.
1656 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1657                                                       MachineFunction &MF,
1658                                                       const SIRegisterInfo &TRI,
1659                                                       SIMachineFunctionInfo &Info) const {
1660   const LLT S32 = LLT::scalar(32);
1661   MachineRegisterInfo &MRI = MF.getRegInfo();
1662 
1663   if (Info.hasWorkItemIDX()) {
1664     Register Reg = AMDGPU::VGPR0;
1665     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1666 
1667     CCInfo.AllocateReg(Reg);
1668     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1669   }
1670 
1671   if (Info.hasWorkItemIDY()) {
1672     Register Reg = AMDGPU::VGPR1;
1673     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1674 
1675     CCInfo.AllocateReg(Reg);
1676     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1677   }
1678 
1679   if (Info.hasWorkItemIDZ()) {
1680     Register Reg = AMDGPU::VGPR2;
1681     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1682 
1683     CCInfo.AllocateReg(Reg);
1684     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1685   }
1686 }
1687 
1688 // Try to allocate a VGPR at the end of the argument list, or if no argument
1689 // VGPRs are left allocating a stack slot.
1690 // If \p Mask is is given it indicates bitfield position in the register.
1691 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1692 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1693                                          ArgDescriptor Arg = ArgDescriptor()) {
1694   if (Arg.isSet())
1695     return ArgDescriptor::createArg(Arg, Mask);
1696 
1697   ArrayRef<MCPhysReg> ArgVGPRs
1698     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1699   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1700   if (RegIdx == ArgVGPRs.size()) {
1701     // Spill to stack required.
1702     int64_t Offset = CCInfo.AllocateStack(4, 4);
1703 
1704     return ArgDescriptor::createStack(Offset, Mask);
1705   }
1706 
1707   unsigned Reg = ArgVGPRs[RegIdx];
1708   Reg = CCInfo.AllocateReg(Reg);
1709   assert(Reg != AMDGPU::NoRegister);
1710 
1711   MachineFunction &MF = CCInfo.getMachineFunction();
1712   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1713   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1714   return ArgDescriptor::createRegister(Reg, Mask);
1715 }
1716 
1717 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1718                                              const TargetRegisterClass *RC,
1719                                              unsigned NumArgRegs) {
1720   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1721   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1722   if (RegIdx == ArgSGPRs.size())
1723     report_fatal_error("ran out of SGPRs for arguments");
1724 
1725   unsigned Reg = ArgSGPRs[RegIdx];
1726   Reg = CCInfo.AllocateReg(Reg);
1727   assert(Reg != AMDGPU::NoRegister);
1728 
1729   MachineFunction &MF = CCInfo.getMachineFunction();
1730   MF.addLiveIn(Reg, RC);
1731   return ArgDescriptor::createRegister(Reg);
1732 }
1733 
1734 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1735   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1736 }
1737 
1738 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1739   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1740 }
1741 
1742 /// Allocate implicit function VGPR arguments at the end of allocated user
1743 /// arguments.
1744 void SITargetLowering::allocateSpecialInputVGPRs(
1745   CCState &CCInfo, MachineFunction &MF,
1746   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1747   const unsigned Mask = 0x3ff;
1748   ArgDescriptor Arg;
1749 
1750   if (Info.hasWorkItemIDX()) {
1751     Arg = allocateVGPR32Input(CCInfo, Mask);
1752     Info.setWorkItemIDX(Arg);
1753   }
1754 
1755   if (Info.hasWorkItemIDY()) {
1756     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1757     Info.setWorkItemIDY(Arg);
1758   }
1759 
1760   if (Info.hasWorkItemIDZ())
1761     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1762 }
1763 
1764 /// Allocate implicit function VGPR arguments in fixed registers.
1765 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1766   CCState &CCInfo, MachineFunction &MF,
1767   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1768   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1769   if (!Reg)
1770     report_fatal_error("failed to allocated VGPR for implicit arguments");
1771 
1772   const unsigned Mask = 0x3ff;
1773   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1774   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1775   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1776 }
1777 
1778 void SITargetLowering::allocateSpecialInputSGPRs(
1779   CCState &CCInfo,
1780   MachineFunction &MF,
1781   const SIRegisterInfo &TRI,
1782   SIMachineFunctionInfo &Info) const {
1783   auto &ArgInfo = Info.getArgInfo();
1784 
1785   // TODO: Unify handling with private memory pointers.
1786 
1787   if (Info.hasDispatchPtr())
1788     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1789 
1790   if (Info.hasQueuePtr())
1791     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1792 
1793   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1794   // constant offset from the kernarg segment.
1795   if (Info.hasImplicitArgPtr())
1796     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1797 
1798   if (Info.hasDispatchID())
1799     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1800 
1801   // flat_scratch_init is not applicable for non-kernel functions.
1802 
1803   if (Info.hasWorkGroupIDX())
1804     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1805 
1806   if (Info.hasWorkGroupIDY())
1807     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1808 
1809   if (Info.hasWorkGroupIDZ())
1810     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1811 }
1812 
1813 // Allocate special inputs passed in user SGPRs.
1814 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1815                                             MachineFunction &MF,
1816                                             const SIRegisterInfo &TRI,
1817                                             SIMachineFunctionInfo &Info) const {
1818   if (Info.hasImplicitBufferPtr()) {
1819     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1820     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1821     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1822   }
1823 
1824   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1825   if (Info.hasPrivateSegmentBuffer()) {
1826     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1827     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1828     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1829   }
1830 
1831   if (Info.hasDispatchPtr()) {
1832     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1833     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1834     CCInfo.AllocateReg(DispatchPtrReg);
1835   }
1836 
1837   if (Info.hasQueuePtr()) {
1838     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1839     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1840     CCInfo.AllocateReg(QueuePtrReg);
1841   }
1842 
1843   if (Info.hasKernargSegmentPtr()) {
1844     MachineRegisterInfo &MRI = MF.getRegInfo();
1845     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1846     CCInfo.AllocateReg(InputPtrReg);
1847 
1848     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1849     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1850   }
1851 
1852   if (Info.hasDispatchID()) {
1853     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1854     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1855     CCInfo.AllocateReg(DispatchIDReg);
1856   }
1857 
1858   if (Info.hasFlatScratchInit()) {
1859     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1860     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1861     CCInfo.AllocateReg(FlatScratchInitReg);
1862   }
1863 
1864   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1865   // these from the dispatch pointer.
1866 }
1867 
1868 // Allocate special input registers that are initialized per-wave.
1869 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1870                                            MachineFunction &MF,
1871                                            SIMachineFunctionInfo &Info,
1872                                            CallingConv::ID CallConv,
1873                                            bool IsShader) const {
1874   if (Info.hasWorkGroupIDX()) {
1875     unsigned Reg = Info.addWorkGroupIDX();
1876     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1877     CCInfo.AllocateReg(Reg);
1878   }
1879 
1880   if (Info.hasWorkGroupIDY()) {
1881     unsigned Reg = Info.addWorkGroupIDY();
1882     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1883     CCInfo.AllocateReg(Reg);
1884   }
1885 
1886   if (Info.hasWorkGroupIDZ()) {
1887     unsigned Reg = Info.addWorkGroupIDZ();
1888     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1889     CCInfo.AllocateReg(Reg);
1890   }
1891 
1892   if (Info.hasWorkGroupInfo()) {
1893     unsigned Reg = Info.addWorkGroupInfo();
1894     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1895     CCInfo.AllocateReg(Reg);
1896   }
1897 
1898   if (Info.hasPrivateSegmentWaveByteOffset()) {
1899     // Scratch wave offset passed in system SGPR.
1900     unsigned PrivateSegmentWaveByteOffsetReg;
1901 
1902     if (IsShader) {
1903       PrivateSegmentWaveByteOffsetReg =
1904         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1905 
1906       // This is true if the scratch wave byte offset doesn't have a fixed
1907       // location.
1908       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1909         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1910         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1911       }
1912     } else
1913       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1914 
1915     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1916     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1917   }
1918 }
1919 
1920 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1921                                      MachineFunction &MF,
1922                                      const SIRegisterInfo &TRI,
1923                                      SIMachineFunctionInfo &Info) {
1924   // Now that we've figured out where the scratch register inputs are, see if
1925   // should reserve the arguments and use them directly.
1926   MachineFrameInfo &MFI = MF.getFrameInfo();
1927   bool HasStackObjects = MFI.hasStackObjects();
1928   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1929 
1930   // Record that we know we have non-spill stack objects so we don't need to
1931   // check all stack objects later.
1932   if (HasStackObjects)
1933     Info.setHasNonSpillStackObjects(true);
1934 
1935   // Everything live out of a block is spilled with fast regalloc, so it's
1936   // almost certain that spilling will be required.
1937   if (TM.getOptLevel() == CodeGenOpt::None)
1938     HasStackObjects = true;
1939 
1940   // For now assume stack access is needed in any callee functions, so we need
1941   // the scratch registers to pass in.
1942   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1943 
1944   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1945     // If we have stack objects, we unquestionably need the private buffer
1946     // resource. For the Code Object V2 ABI, this will be the first 4 user
1947     // SGPR inputs. We can reserve those and use them directly.
1948 
1949     Register PrivateSegmentBufferReg =
1950         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1951     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1952   } else {
1953     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1954     // We tentatively reserve the last registers (skipping the last registers
1955     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1956     // we'll replace these with the ones immediately after those which were
1957     // really allocated. In the prologue copies will be inserted from the
1958     // argument to these reserved registers.
1959 
1960     // Without HSA, relocations are used for the scratch pointer and the
1961     // buffer resource setup is always inserted in the prologue. Scratch wave
1962     // offset is still in an input SGPR.
1963     Info.setScratchRSrcReg(ReservedBufferReg);
1964   }
1965 
1966   MachineRegisterInfo &MRI = MF.getRegInfo();
1967 
1968   // For entry functions we have to set up the stack pointer if we use it,
1969   // whereas non-entry functions get this "for free". This means there is no
1970   // intrinsic advantage to using S32 over S34 in cases where we do not have
1971   // calls but do need a frame pointer (i.e. if we are requested to have one
1972   // because frame pointer elimination is disabled). To keep things simple we
1973   // only ever use S32 as the call ABI stack pointer, and so using it does not
1974   // imply we need a separate frame pointer.
1975   //
1976   // Try to use s32 as the SP, but move it if it would interfere with input
1977   // arguments. This won't work with calls though.
1978   //
1979   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1980   // registers.
1981   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1982     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1983   } else {
1984     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1985 
1986     if (MFI.hasCalls())
1987       report_fatal_error("call in graphics shader with too many input SGPRs");
1988 
1989     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1990       if (!MRI.isLiveIn(Reg)) {
1991         Info.setStackPtrOffsetReg(Reg);
1992         break;
1993       }
1994     }
1995 
1996     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1997       report_fatal_error("failed to find register for SP");
1998   }
1999 
2000   // hasFP should be accurate for entry functions even before the frame is
2001   // finalized, because it does not rely on the known stack size, only
2002   // properties like whether variable sized objects are present.
2003   if (ST.getFrameLowering()->hasFP(MF)) {
2004     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2005   }
2006 }
2007 
2008 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2009   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2010   return !Info->isEntryFunction();
2011 }
2012 
2013 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2014 
2015 }
2016 
2017 void SITargetLowering::insertCopiesSplitCSR(
2018   MachineBasicBlock *Entry,
2019   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2020   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2021 
2022   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2023   if (!IStart)
2024     return;
2025 
2026   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2027   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2028   MachineBasicBlock::iterator MBBI = Entry->begin();
2029   for (const MCPhysReg *I = IStart; *I; ++I) {
2030     const TargetRegisterClass *RC = nullptr;
2031     if (AMDGPU::SReg_64RegClass.contains(*I))
2032       RC = &AMDGPU::SGPR_64RegClass;
2033     else if (AMDGPU::SReg_32RegClass.contains(*I))
2034       RC = &AMDGPU::SGPR_32RegClass;
2035     else
2036       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2037 
2038     Register NewVR = MRI->createVirtualRegister(RC);
2039     // Create copy from CSR to a virtual register.
2040     Entry->addLiveIn(*I);
2041     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2042       .addReg(*I);
2043 
2044     // Insert the copy-back instructions right before the terminator.
2045     for (auto *Exit : Exits)
2046       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2047               TII->get(TargetOpcode::COPY), *I)
2048         .addReg(NewVR);
2049   }
2050 }
2051 
2052 SDValue SITargetLowering::LowerFormalArguments(
2053     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2054     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2055     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2056   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2057 
2058   MachineFunction &MF = DAG.getMachineFunction();
2059   const Function &Fn = MF.getFunction();
2060   FunctionType *FType = MF.getFunction().getFunctionType();
2061   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2062 
2063   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2064     DiagnosticInfoUnsupported NoGraphicsHSA(
2065         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2066     DAG.getContext()->diagnose(NoGraphicsHSA);
2067     return DAG.getEntryNode();
2068   }
2069 
2070   SmallVector<ISD::InputArg, 16> Splits;
2071   SmallVector<CCValAssign, 16> ArgLocs;
2072   BitVector Skipped(Ins.size());
2073   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2074                  *DAG.getContext());
2075 
2076   bool IsShader = AMDGPU::isShader(CallConv);
2077   bool IsKernel = AMDGPU::isKernel(CallConv);
2078   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2079 
2080   if (IsShader) {
2081     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2082 
2083     // At least one interpolation mode must be enabled or else the GPU will
2084     // hang.
2085     //
2086     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2087     // set PSInputAddr, the user wants to enable some bits after the compilation
2088     // based on run-time states. Since we can't know what the final PSInputEna
2089     // will look like, so we shouldn't do anything here and the user should take
2090     // responsibility for the correct programming.
2091     //
2092     // Otherwise, the following restrictions apply:
2093     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2094     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2095     //   enabled too.
2096     if (CallConv == CallingConv::AMDGPU_PS) {
2097       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2098            ((Info->getPSInputAddr() & 0xF) == 0 &&
2099             Info->isPSInputAllocated(11))) {
2100         CCInfo.AllocateReg(AMDGPU::VGPR0);
2101         CCInfo.AllocateReg(AMDGPU::VGPR1);
2102         Info->markPSInputAllocated(0);
2103         Info->markPSInputEnabled(0);
2104       }
2105       if (Subtarget->isAmdPalOS()) {
2106         // For isAmdPalOS, the user does not enable some bits after compilation
2107         // based on run-time states; the register values being generated here are
2108         // the final ones set in hardware. Therefore we need to apply the
2109         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2110         // a bit is set in PSInputAddr but not PSInputEnable is where the
2111         // frontend set up an input arg for a particular interpolation mode, but
2112         // nothing uses that input arg. Really we should have an earlier pass
2113         // that removes such an arg.)
2114         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2115         if ((PsInputBits & 0x7F) == 0 ||
2116             ((PsInputBits & 0xF) == 0 &&
2117              (PsInputBits >> 11 & 1)))
2118           Info->markPSInputEnabled(
2119               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2120       }
2121     }
2122 
2123     assert(!Info->hasDispatchPtr() &&
2124            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2125            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2126            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2127            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2128            !Info->hasWorkItemIDZ());
2129   } else if (IsKernel) {
2130     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2131   } else {
2132     Splits.append(Ins.begin(), Ins.end());
2133   }
2134 
2135   if (IsEntryFunc) {
2136     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2137     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2138   } else {
2139     // For the fixed ABI, pass workitem IDs in the last argument register.
2140     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2141       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2142   }
2143 
2144   if (IsKernel) {
2145     analyzeFormalArgumentsCompute(CCInfo, Ins);
2146   } else {
2147     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2148     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2149   }
2150 
2151   SmallVector<SDValue, 16> Chains;
2152 
2153   // FIXME: This is the minimum kernel argument alignment. We should improve
2154   // this to the maximum alignment of the arguments.
2155   //
2156   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2157   // kern arg offset.
2158   const unsigned KernelArgBaseAlign = 16;
2159 
2160    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2161     const ISD::InputArg &Arg = Ins[i];
2162     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2163       InVals.push_back(DAG.getUNDEF(Arg.VT));
2164       continue;
2165     }
2166 
2167     CCValAssign &VA = ArgLocs[ArgIdx++];
2168     MVT VT = VA.getLocVT();
2169 
2170     if (IsEntryFunc && VA.isMemLoc()) {
2171       VT = Ins[i].VT;
2172       EVT MemVT = VA.getLocVT();
2173 
2174       const uint64_t Offset = VA.getLocMemOffset();
2175       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2176 
2177       SDValue Arg = lowerKernargMemParameter(
2178         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2179       Chains.push_back(Arg.getValue(1));
2180 
2181       auto *ParamTy =
2182         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2183       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2184           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2185                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2186         // On SI local pointers are just offsets into LDS, so they are always
2187         // less than 16-bits.  On CI and newer they could potentially be
2188         // real pointers, so we can't guarantee their size.
2189         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2190                           DAG.getValueType(MVT::i16));
2191       }
2192 
2193       InVals.push_back(Arg);
2194       continue;
2195     } else if (!IsEntryFunc && VA.isMemLoc()) {
2196       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2197       InVals.push_back(Val);
2198       if (!Arg.Flags.isByVal())
2199         Chains.push_back(Val.getValue(1));
2200       continue;
2201     }
2202 
2203     assert(VA.isRegLoc() && "Parameter must be in a register!");
2204 
2205     Register Reg = VA.getLocReg();
2206     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2207     EVT ValVT = VA.getValVT();
2208 
2209     Reg = MF.addLiveIn(Reg, RC);
2210     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2211 
2212     if (Arg.Flags.isSRet()) {
2213       // The return object should be reasonably addressable.
2214 
2215       // FIXME: This helps when the return is a real sret. If it is a
2216       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2217       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2218       unsigned NumBits
2219         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2220       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2221         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2222     }
2223 
2224     // If this is an 8 or 16-bit value, it is really passed promoted
2225     // to 32 bits. Insert an assert[sz]ext to capture this, then
2226     // truncate to the right size.
2227     switch (VA.getLocInfo()) {
2228     case CCValAssign::Full:
2229       break;
2230     case CCValAssign::BCvt:
2231       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2232       break;
2233     case CCValAssign::SExt:
2234       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2235                         DAG.getValueType(ValVT));
2236       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2237       break;
2238     case CCValAssign::ZExt:
2239       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2240                         DAG.getValueType(ValVT));
2241       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2242       break;
2243     case CCValAssign::AExt:
2244       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2245       break;
2246     default:
2247       llvm_unreachable("Unknown loc info!");
2248     }
2249 
2250     InVals.push_back(Val);
2251   }
2252 
2253   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2254     // Special inputs come after user arguments.
2255     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2256   }
2257 
2258   // Start adding system SGPRs.
2259   if (IsEntryFunc) {
2260     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2261   } else {
2262     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2263     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2264   }
2265 
2266   auto &ArgUsageInfo =
2267     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2268   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2269 
2270   unsigned StackArgSize = CCInfo.getNextStackOffset();
2271   Info->setBytesInStackArgArea(StackArgSize);
2272 
2273   return Chains.empty() ? Chain :
2274     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2275 }
2276 
2277 // TODO: If return values can't fit in registers, we should return as many as
2278 // possible in registers before passing on stack.
2279 bool SITargetLowering::CanLowerReturn(
2280   CallingConv::ID CallConv,
2281   MachineFunction &MF, bool IsVarArg,
2282   const SmallVectorImpl<ISD::OutputArg> &Outs,
2283   LLVMContext &Context) const {
2284   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2285   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2286   // for shaders. Vector types should be explicitly handled by CC.
2287   if (AMDGPU::isEntryFunctionCC(CallConv))
2288     return true;
2289 
2290   SmallVector<CCValAssign, 16> RVLocs;
2291   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2292   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2293 }
2294 
2295 SDValue
2296 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2297                               bool isVarArg,
2298                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2299                               const SmallVectorImpl<SDValue> &OutVals,
2300                               const SDLoc &DL, SelectionDAG &DAG) const {
2301   MachineFunction &MF = DAG.getMachineFunction();
2302   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2303 
2304   if (AMDGPU::isKernel(CallConv)) {
2305     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2306                                              OutVals, DL, DAG);
2307   }
2308 
2309   bool IsShader = AMDGPU::isShader(CallConv);
2310 
2311   Info->setIfReturnsVoid(Outs.empty());
2312   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2313 
2314   // CCValAssign - represent the assignment of the return value to a location.
2315   SmallVector<CCValAssign, 48> RVLocs;
2316   SmallVector<ISD::OutputArg, 48> Splits;
2317 
2318   // CCState - Info about the registers and stack slots.
2319   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2320                  *DAG.getContext());
2321 
2322   // Analyze outgoing return values.
2323   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2324 
2325   SDValue Flag;
2326   SmallVector<SDValue, 48> RetOps;
2327   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2328 
2329   // Add return address for callable functions.
2330   if (!Info->isEntryFunction()) {
2331     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2332     SDValue ReturnAddrReg = CreateLiveInRegister(
2333       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2334 
2335     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2336         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2337         MVT::i64);
2338     Chain =
2339         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2340     Flag = Chain.getValue(1);
2341     RetOps.push_back(ReturnAddrVirtualReg);
2342   }
2343 
2344   // Copy the result values into the output registers.
2345   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2346        ++I, ++RealRVLocIdx) {
2347     CCValAssign &VA = RVLocs[I];
2348     assert(VA.isRegLoc() && "Can only return in registers!");
2349     // TODO: Partially return in registers if return values don't fit.
2350     SDValue Arg = OutVals[RealRVLocIdx];
2351 
2352     // Copied from other backends.
2353     switch (VA.getLocInfo()) {
2354     case CCValAssign::Full:
2355       break;
2356     case CCValAssign::BCvt:
2357       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2358       break;
2359     case CCValAssign::SExt:
2360       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2361       break;
2362     case CCValAssign::ZExt:
2363       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2364       break;
2365     case CCValAssign::AExt:
2366       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2367       break;
2368     default:
2369       llvm_unreachable("Unknown loc info!");
2370     }
2371 
2372     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2373     Flag = Chain.getValue(1);
2374     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2375   }
2376 
2377   // FIXME: Does sret work properly?
2378   if (!Info->isEntryFunction()) {
2379     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2380     const MCPhysReg *I =
2381       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2382     if (I) {
2383       for (; *I; ++I) {
2384         if (AMDGPU::SReg_64RegClass.contains(*I))
2385           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2386         else if (AMDGPU::SReg_32RegClass.contains(*I))
2387           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2388         else
2389           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2390       }
2391     }
2392   }
2393 
2394   // Update chain and glue.
2395   RetOps[0] = Chain;
2396   if (Flag.getNode())
2397     RetOps.push_back(Flag);
2398 
2399   unsigned Opc = AMDGPUISD::ENDPGM;
2400   if (!IsWaveEnd)
2401     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2402   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2403 }
2404 
2405 SDValue SITargetLowering::LowerCallResult(
2406     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2407     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2408     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2409     SDValue ThisVal) const {
2410   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2411 
2412   // Assign locations to each value returned by this call.
2413   SmallVector<CCValAssign, 16> RVLocs;
2414   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2415                  *DAG.getContext());
2416   CCInfo.AnalyzeCallResult(Ins, RetCC);
2417 
2418   // Copy all of the result registers out of their specified physreg.
2419   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2420     CCValAssign VA = RVLocs[i];
2421     SDValue Val;
2422 
2423     if (VA.isRegLoc()) {
2424       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2425       Chain = Val.getValue(1);
2426       InFlag = Val.getValue(2);
2427     } else if (VA.isMemLoc()) {
2428       report_fatal_error("TODO: return values in memory");
2429     } else
2430       llvm_unreachable("unknown argument location type");
2431 
2432     switch (VA.getLocInfo()) {
2433     case CCValAssign::Full:
2434       break;
2435     case CCValAssign::BCvt:
2436       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2437       break;
2438     case CCValAssign::ZExt:
2439       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2440                         DAG.getValueType(VA.getValVT()));
2441       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2442       break;
2443     case CCValAssign::SExt:
2444       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2445                         DAG.getValueType(VA.getValVT()));
2446       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2447       break;
2448     case CCValAssign::AExt:
2449       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2450       break;
2451     default:
2452       llvm_unreachable("Unknown loc info!");
2453     }
2454 
2455     InVals.push_back(Val);
2456   }
2457 
2458   return Chain;
2459 }
2460 
2461 // Add code to pass special inputs required depending on used features separate
2462 // from the explicit user arguments present in the IR.
2463 void SITargetLowering::passSpecialInputs(
2464     CallLoweringInfo &CLI,
2465     CCState &CCInfo,
2466     const SIMachineFunctionInfo &Info,
2467     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2468     SmallVectorImpl<SDValue> &MemOpChains,
2469     SDValue Chain) const {
2470   // If we don't have a call site, this was a call inserted by
2471   // legalization. These can never use special inputs.
2472   if (!CLI.CB)
2473     return;
2474 
2475   SelectionDAG &DAG = CLI.DAG;
2476   const SDLoc &DL = CLI.DL;
2477 
2478   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2479   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2480 
2481   const AMDGPUFunctionArgInfo *CalleeArgInfo
2482     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2483   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2484     auto &ArgUsageInfo =
2485       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2486     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2487   }
2488 
2489   // TODO: Unify with private memory register handling. This is complicated by
2490   // the fact that at least in kernels, the input argument is not necessarily
2491   // in the same location as the input.
2492   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2493     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2494     AMDGPUFunctionArgInfo::QUEUE_PTR,
2495     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2496     AMDGPUFunctionArgInfo::DISPATCH_ID,
2497     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2498     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2499     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2500   };
2501 
2502   for (auto InputID : InputRegs) {
2503     const ArgDescriptor *OutgoingArg;
2504     const TargetRegisterClass *ArgRC;
2505 
2506     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2507     if (!OutgoingArg)
2508       continue;
2509 
2510     const ArgDescriptor *IncomingArg;
2511     const TargetRegisterClass *IncomingArgRC;
2512     std::tie(IncomingArg, IncomingArgRC)
2513       = CallerArgInfo.getPreloadedValue(InputID);
2514     assert(IncomingArgRC == ArgRC);
2515 
2516     // All special arguments are ints for now.
2517     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2518     SDValue InputReg;
2519 
2520     if (IncomingArg) {
2521       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2522     } else {
2523       // The implicit arg ptr is special because it doesn't have a corresponding
2524       // input for kernels, and is computed from the kernarg segment pointer.
2525       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2526       InputReg = getImplicitArgPtr(DAG, DL);
2527     }
2528 
2529     if (OutgoingArg->isRegister()) {
2530       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2531       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2532         report_fatal_error("failed to allocate implicit input argument");
2533     } else {
2534       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2535       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2536                                               SpecialArgOffset);
2537       MemOpChains.push_back(ArgStore);
2538     }
2539   }
2540 
2541   // Pack workitem IDs into a single register or pass it as is if already
2542   // packed.
2543   const ArgDescriptor *OutgoingArg;
2544   const TargetRegisterClass *ArgRC;
2545 
2546   std::tie(OutgoingArg, ArgRC) =
2547     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2548   if (!OutgoingArg)
2549     std::tie(OutgoingArg, ArgRC) =
2550       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2551   if (!OutgoingArg)
2552     std::tie(OutgoingArg, ArgRC) =
2553       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2554   if (!OutgoingArg)
2555     return;
2556 
2557   const ArgDescriptor *IncomingArgX
2558     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2559   const ArgDescriptor *IncomingArgY
2560     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2561   const ArgDescriptor *IncomingArgZ
2562     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2563 
2564   SDValue InputReg;
2565   SDLoc SL;
2566 
2567   // If incoming ids are not packed we need to pack them.
2568   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2569     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2570 
2571   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2572     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2573     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2574                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2575     InputReg = InputReg.getNode() ?
2576                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2577   }
2578 
2579   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2580     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2581     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2582                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2583     InputReg = InputReg.getNode() ?
2584                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2585   }
2586 
2587   if (!InputReg.getNode()) {
2588     // Workitem ids are already packed, any of present incoming arguments
2589     // will carry all required fields.
2590     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2591       IncomingArgX ? *IncomingArgX :
2592       IncomingArgY ? *IncomingArgY :
2593                      *IncomingArgZ, ~0u);
2594     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2595   }
2596 
2597   if (OutgoingArg->isRegister()) {
2598     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2599     CCInfo.AllocateReg(OutgoingArg->getRegister());
2600   } else {
2601     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2602     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2603                                             SpecialArgOffset);
2604     MemOpChains.push_back(ArgStore);
2605   }
2606 }
2607 
2608 static bool canGuaranteeTCO(CallingConv::ID CC) {
2609   return CC == CallingConv::Fast;
2610 }
2611 
2612 /// Return true if we might ever do TCO for calls with this calling convention.
2613 static bool mayTailCallThisCC(CallingConv::ID CC) {
2614   switch (CC) {
2615   case CallingConv::C:
2616     return true;
2617   default:
2618     return canGuaranteeTCO(CC);
2619   }
2620 }
2621 
2622 bool SITargetLowering::isEligibleForTailCallOptimization(
2623     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2624     const SmallVectorImpl<ISD::OutputArg> &Outs,
2625     const SmallVectorImpl<SDValue> &OutVals,
2626     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2627   if (!mayTailCallThisCC(CalleeCC))
2628     return false;
2629 
2630   MachineFunction &MF = DAG.getMachineFunction();
2631   const Function &CallerF = MF.getFunction();
2632   CallingConv::ID CallerCC = CallerF.getCallingConv();
2633   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2634   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2635 
2636   // Kernels aren't callable, and don't have a live in return address so it
2637   // doesn't make sense to do a tail call with entry functions.
2638   if (!CallerPreserved)
2639     return false;
2640 
2641   bool CCMatch = CallerCC == CalleeCC;
2642 
2643   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2644     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2645       return true;
2646     return false;
2647   }
2648 
2649   // TODO: Can we handle var args?
2650   if (IsVarArg)
2651     return false;
2652 
2653   for (const Argument &Arg : CallerF.args()) {
2654     if (Arg.hasByValAttr())
2655       return false;
2656   }
2657 
2658   LLVMContext &Ctx = *DAG.getContext();
2659 
2660   // Check that the call results are passed in the same way.
2661   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2662                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2663                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2664     return false;
2665 
2666   // The callee has to preserve all registers the caller needs to preserve.
2667   if (!CCMatch) {
2668     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2669     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2670       return false;
2671   }
2672 
2673   // Nothing more to check if the callee is taking no arguments.
2674   if (Outs.empty())
2675     return true;
2676 
2677   SmallVector<CCValAssign, 16> ArgLocs;
2678   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2679 
2680   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2681 
2682   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2683   // If the stack arguments for this call do not fit into our own save area then
2684   // the call cannot be made tail.
2685   // TODO: Is this really necessary?
2686   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2687     return false;
2688 
2689   const MachineRegisterInfo &MRI = MF.getRegInfo();
2690   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2691 }
2692 
2693 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2694   if (!CI->isTailCall())
2695     return false;
2696 
2697   const Function *ParentFn = CI->getParent()->getParent();
2698   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2699     return false;
2700   return true;
2701 }
2702 
2703 // The wave scratch offset register is used as the global base pointer.
2704 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2705                                     SmallVectorImpl<SDValue> &InVals) const {
2706   SelectionDAG &DAG = CLI.DAG;
2707   const SDLoc &DL = CLI.DL;
2708   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2709   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2710   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2711   SDValue Chain = CLI.Chain;
2712   SDValue Callee = CLI.Callee;
2713   bool &IsTailCall = CLI.IsTailCall;
2714   CallingConv::ID CallConv = CLI.CallConv;
2715   bool IsVarArg = CLI.IsVarArg;
2716   bool IsSibCall = false;
2717   bool IsThisReturn = false;
2718   MachineFunction &MF = DAG.getMachineFunction();
2719 
2720   if (Callee.isUndef() || isNullConstant(Callee)) {
2721     if (!CLI.IsTailCall) {
2722       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2723         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2724     }
2725 
2726     return Chain;
2727   }
2728 
2729   if (IsVarArg) {
2730     return lowerUnhandledCall(CLI, InVals,
2731                               "unsupported call to variadic function ");
2732   }
2733 
2734   if (!CLI.CB)
2735     report_fatal_error("unsupported libcall legalization");
2736 
2737   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2738       !CLI.CB->getCalledFunction()) {
2739     return lowerUnhandledCall(CLI, InVals,
2740                               "unsupported indirect call to function ");
2741   }
2742 
2743   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2744     return lowerUnhandledCall(CLI, InVals,
2745                               "unsupported required tail call to function ");
2746   }
2747 
2748   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2749     // Note the issue is with the CC of the calling function, not of the call
2750     // itself.
2751     return lowerUnhandledCall(CLI, InVals,
2752                           "unsupported call from graphics shader of function ");
2753   }
2754 
2755   if (IsTailCall) {
2756     IsTailCall = isEligibleForTailCallOptimization(
2757       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2758     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2759       report_fatal_error("failed to perform tail call elimination on a call "
2760                          "site marked musttail");
2761     }
2762 
2763     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2764 
2765     // A sibling call is one where we're under the usual C ABI and not planning
2766     // to change that but can still do a tail call:
2767     if (!TailCallOpt && IsTailCall)
2768       IsSibCall = true;
2769 
2770     if (IsTailCall)
2771       ++NumTailCalls;
2772   }
2773 
2774   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2775   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2776   SmallVector<SDValue, 8> MemOpChains;
2777 
2778   // Analyze operands of the call, assigning locations to each operand.
2779   SmallVector<CCValAssign, 16> ArgLocs;
2780   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2781   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2782 
2783   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2784     // With a fixed ABI, allocate fixed registers before user arguments.
2785     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2786   }
2787 
2788   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2789 
2790   // Get a count of how many bytes are to be pushed on the stack.
2791   unsigned NumBytes = CCInfo.getNextStackOffset();
2792 
2793   if (IsSibCall) {
2794     // Since we're not changing the ABI to make this a tail call, the memory
2795     // operands are already available in the caller's incoming argument space.
2796     NumBytes = 0;
2797   }
2798 
2799   // FPDiff is the byte offset of the call's argument area from the callee's.
2800   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2801   // by this amount for a tail call. In a sibling call it must be 0 because the
2802   // caller will deallocate the entire stack and the callee still expects its
2803   // arguments to begin at SP+0. Completely unused for non-tail calls.
2804   int32_t FPDiff = 0;
2805   MachineFrameInfo &MFI = MF.getFrameInfo();
2806 
2807   // Adjust the stack pointer for the new arguments...
2808   // These operations are automatically eliminated by the prolog/epilog pass
2809   if (!IsSibCall) {
2810     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2811 
2812     SmallVector<SDValue, 4> CopyFromChains;
2813 
2814     // In the HSA case, this should be an identity copy.
2815     SDValue ScratchRSrcReg
2816       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2817     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2818     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2819     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2820   }
2821 
2822   MVT PtrVT = MVT::i32;
2823 
2824   // Walk the register/memloc assignments, inserting copies/loads.
2825   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2826     CCValAssign &VA = ArgLocs[i];
2827     SDValue Arg = OutVals[i];
2828 
2829     // Promote the value if needed.
2830     switch (VA.getLocInfo()) {
2831     case CCValAssign::Full:
2832       break;
2833     case CCValAssign::BCvt:
2834       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2835       break;
2836     case CCValAssign::ZExt:
2837       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2838       break;
2839     case CCValAssign::SExt:
2840       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2841       break;
2842     case CCValAssign::AExt:
2843       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2844       break;
2845     case CCValAssign::FPExt:
2846       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2847       break;
2848     default:
2849       llvm_unreachable("Unknown loc info!");
2850     }
2851 
2852     if (VA.isRegLoc()) {
2853       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2854     } else {
2855       assert(VA.isMemLoc());
2856 
2857       SDValue DstAddr;
2858       MachinePointerInfo DstInfo;
2859 
2860       unsigned LocMemOffset = VA.getLocMemOffset();
2861       int32_t Offset = LocMemOffset;
2862 
2863       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2864       MaybeAlign Alignment;
2865 
2866       if (IsTailCall) {
2867         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2868         unsigned OpSize = Flags.isByVal() ?
2869           Flags.getByValSize() : VA.getValVT().getStoreSize();
2870 
2871         // FIXME: We can have better than the minimum byval required alignment.
2872         Alignment =
2873             Flags.isByVal()
2874                 ? Flags.getNonZeroByValAlign()
2875                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2876 
2877         Offset = Offset + FPDiff;
2878         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2879 
2880         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2881         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2882 
2883         // Make sure any stack arguments overlapping with where we're storing
2884         // are loaded before this eventual operation. Otherwise they'll be
2885         // clobbered.
2886 
2887         // FIXME: Why is this really necessary? This seems to just result in a
2888         // lot of code to copy the stack and write them back to the same
2889         // locations, which are supposed to be immutable?
2890         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2891       } else {
2892         DstAddr = PtrOff;
2893         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2894         Alignment =
2895             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2896       }
2897 
2898       if (Outs[i].Flags.isByVal()) {
2899         SDValue SizeNode =
2900             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2901         SDValue Cpy =
2902             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2903                           Outs[i].Flags.getNonZeroByValAlign(),
2904                           /*isVol = */ false, /*AlwaysInline = */ true,
2905                           /*isTailCall = */ false, DstInfo,
2906                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2907 
2908         MemOpChains.push_back(Cpy);
2909       } else {
2910         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2911                                      Alignment ? Alignment->value() : 0);
2912         MemOpChains.push_back(Store);
2913       }
2914     }
2915   }
2916 
2917   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2918     // Copy special input registers after user input arguments.
2919     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2920   }
2921 
2922   if (!MemOpChains.empty())
2923     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2924 
2925   // Build a sequence of copy-to-reg nodes chained together with token chain
2926   // and flag operands which copy the outgoing args into the appropriate regs.
2927   SDValue InFlag;
2928   for (auto &RegToPass : RegsToPass) {
2929     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2930                              RegToPass.second, InFlag);
2931     InFlag = Chain.getValue(1);
2932   }
2933 
2934 
2935   SDValue PhysReturnAddrReg;
2936   if (IsTailCall) {
2937     // Since the return is being combined with the call, we need to pass on the
2938     // return address.
2939 
2940     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2941     SDValue ReturnAddrReg = CreateLiveInRegister(
2942       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2943 
2944     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2945                                         MVT::i64);
2946     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2947     InFlag = Chain.getValue(1);
2948   }
2949 
2950   // We don't usually want to end the call-sequence here because we would tidy
2951   // the frame up *after* the call, however in the ABI-changing tail-call case
2952   // we've carefully laid out the parameters so that when sp is reset they'll be
2953   // in the correct location.
2954   if (IsTailCall && !IsSibCall) {
2955     Chain = DAG.getCALLSEQ_END(Chain,
2956                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2957                                DAG.getTargetConstant(0, DL, MVT::i32),
2958                                InFlag, DL);
2959     InFlag = Chain.getValue(1);
2960   }
2961 
2962   std::vector<SDValue> Ops;
2963   Ops.push_back(Chain);
2964   Ops.push_back(Callee);
2965   // Add a redundant copy of the callee global which will not be legalized, as
2966   // we need direct access to the callee later.
2967   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
2968     const GlobalValue *GV = GSD->getGlobal();
2969     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2970   } else {
2971     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
2972   }
2973 
2974   if (IsTailCall) {
2975     // Each tail call may have to adjust the stack by a different amount, so
2976     // this information must travel along with the operation for eventual
2977     // consumption by emitEpilogue.
2978     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2979 
2980     Ops.push_back(PhysReturnAddrReg);
2981   }
2982 
2983   // Add argument registers to the end of the list so that they are known live
2984   // into the call.
2985   for (auto &RegToPass : RegsToPass) {
2986     Ops.push_back(DAG.getRegister(RegToPass.first,
2987                                   RegToPass.second.getValueType()));
2988   }
2989 
2990   // Add a register mask operand representing the call-preserved registers.
2991 
2992   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2993   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2994   assert(Mask && "Missing call preserved mask for calling convention");
2995   Ops.push_back(DAG.getRegisterMask(Mask));
2996 
2997   if (InFlag.getNode())
2998     Ops.push_back(InFlag);
2999 
3000   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3001 
3002   // If we're doing a tall call, use a TC_RETURN here rather than an
3003   // actual call instruction.
3004   if (IsTailCall) {
3005     MFI.setHasTailCall();
3006     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3007   }
3008 
3009   // Returns a chain and a flag for retval copy to use.
3010   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3011   Chain = Call.getValue(0);
3012   InFlag = Call.getValue(1);
3013 
3014   uint64_t CalleePopBytes = NumBytes;
3015   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3016                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3017                              InFlag, DL);
3018   if (!Ins.empty())
3019     InFlag = Chain.getValue(1);
3020 
3021   // Handle result values, copying them out of physregs into vregs that we
3022   // return.
3023   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3024                          InVals, IsThisReturn,
3025                          IsThisReturn ? OutVals[0] : SDValue());
3026 }
3027 
3028 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3029                                              const MachineFunction &MF) const {
3030   Register Reg = StringSwitch<Register>(RegName)
3031     .Case("m0", AMDGPU::M0)
3032     .Case("exec", AMDGPU::EXEC)
3033     .Case("exec_lo", AMDGPU::EXEC_LO)
3034     .Case("exec_hi", AMDGPU::EXEC_HI)
3035     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3036     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3037     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3038     .Default(Register());
3039 
3040   if (Reg == AMDGPU::NoRegister) {
3041     report_fatal_error(Twine("invalid register name \""
3042                              + StringRef(RegName)  + "\"."));
3043 
3044   }
3045 
3046   if (!Subtarget->hasFlatScrRegister() &&
3047        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3048     report_fatal_error(Twine("invalid register \""
3049                              + StringRef(RegName)  + "\" for subtarget."));
3050   }
3051 
3052   switch (Reg) {
3053   case AMDGPU::M0:
3054   case AMDGPU::EXEC_LO:
3055   case AMDGPU::EXEC_HI:
3056   case AMDGPU::FLAT_SCR_LO:
3057   case AMDGPU::FLAT_SCR_HI:
3058     if (VT.getSizeInBits() == 32)
3059       return Reg;
3060     break;
3061   case AMDGPU::EXEC:
3062   case AMDGPU::FLAT_SCR:
3063     if (VT.getSizeInBits() == 64)
3064       return Reg;
3065     break;
3066   default:
3067     llvm_unreachable("missing register type checking");
3068   }
3069 
3070   report_fatal_error(Twine("invalid type for register \""
3071                            + StringRef(RegName) + "\"."));
3072 }
3073 
3074 // If kill is not the last instruction, split the block so kill is always a
3075 // proper terminator.
3076 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3077                                                     MachineBasicBlock *BB) const {
3078   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3079 
3080   MachineBasicBlock::iterator SplitPoint(&MI);
3081   ++SplitPoint;
3082 
3083   if (SplitPoint == BB->end()) {
3084     // Don't bother with a new block.
3085     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3086     return BB;
3087   }
3088 
3089   MachineFunction *MF = BB->getParent();
3090   MachineBasicBlock *SplitBB
3091     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3092 
3093   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3094   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3095 
3096   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3097   BB->addSuccessor(SplitBB);
3098 
3099   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3100   return SplitBB;
3101 }
3102 
3103 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3104 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3105 // be the first instruction in the remainder block.
3106 //
3107 /// \returns { LoopBody, Remainder }
3108 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3109 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3110   MachineFunction *MF = MBB.getParent();
3111   MachineBasicBlock::iterator I(&MI);
3112 
3113   // To insert the loop we need to split the block. Move everything after this
3114   // point to a new block, and insert a new empty block between the two.
3115   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3116   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3117   MachineFunction::iterator MBBI(MBB);
3118   ++MBBI;
3119 
3120   MF->insert(MBBI, LoopBB);
3121   MF->insert(MBBI, RemainderBB);
3122 
3123   LoopBB->addSuccessor(LoopBB);
3124   LoopBB->addSuccessor(RemainderBB);
3125 
3126   // Move the rest of the block into a new block.
3127   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3128 
3129   if (InstInLoop) {
3130     auto Next = std::next(I);
3131 
3132     // Move instruction to loop body.
3133     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3134 
3135     // Move the rest of the block.
3136     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3137   } else {
3138     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3139   }
3140 
3141   MBB.addSuccessor(LoopBB);
3142 
3143   return std::make_pair(LoopBB, RemainderBB);
3144 }
3145 
3146 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3147 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3148   MachineBasicBlock *MBB = MI.getParent();
3149   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3150   auto I = MI.getIterator();
3151   auto E = std::next(I);
3152 
3153   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3154     .addImm(0);
3155 
3156   MIBundleBuilder Bundler(*MBB, I, E);
3157   finalizeBundle(*MBB, Bundler.begin());
3158 }
3159 
3160 MachineBasicBlock *
3161 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3162                                          MachineBasicBlock *BB) const {
3163   const DebugLoc &DL = MI.getDebugLoc();
3164 
3165   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3166 
3167   MachineBasicBlock *LoopBB;
3168   MachineBasicBlock *RemainderBB;
3169   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3170 
3171   // Apparently kill flags are only valid if the def is in the same block?
3172   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3173     Src->setIsKill(false);
3174 
3175   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3176 
3177   MachineBasicBlock::iterator I = LoopBB->end();
3178 
3179   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3180     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3181 
3182   // Clear TRAP_STS.MEM_VIOL
3183   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3184     .addImm(0)
3185     .addImm(EncodedReg);
3186 
3187   bundleInstWithWaitcnt(MI);
3188 
3189   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3190 
3191   // Load and check TRAP_STS.MEM_VIOL
3192   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3193     .addImm(EncodedReg);
3194 
3195   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3196   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3197     .addReg(Reg, RegState::Kill)
3198     .addImm(0);
3199   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3200     .addMBB(LoopBB);
3201 
3202   return RemainderBB;
3203 }
3204 
3205 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3206 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3207 // will only do one iteration. In the worst case, this will loop 64 times.
3208 //
3209 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3210 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3211   const SIInstrInfo *TII,
3212   MachineRegisterInfo &MRI,
3213   MachineBasicBlock &OrigBB,
3214   MachineBasicBlock &LoopBB,
3215   const DebugLoc &DL,
3216   const MachineOperand &IdxReg,
3217   unsigned InitReg,
3218   unsigned ResultReg,
3219   unsigned PhiReg,
3220   unsigned InitSaveExecReg,
3221   int Offset,
3222   bool UseGPRIdxMode,
3223   bool IsIndirectSrc) {
3224   MachineFunction *MF = OrigBB.getParent();
3225   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3226   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3227   MachineBasicBlock::iterator I = LoopBB.begin();
3228 
3229   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3230   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3231   Register NewExec = MRI.createVirtualRegister(BoolRC);
3232   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3233   Register CondReg = MRI.createVirtualRegister(BoolRC);
3234 
3235   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3236     .addReg(InitReg)
3237     .addMBB(&OrigBB)
3238     .addReg(ResultReg)
3239     .addMBB(&LoopBB);
3240 
3241   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3242     .addReg(InitSaveExecReg)
3243     .addMBB(&OrigBB)
3244     .addReg(NewExec)
3245     .addMBB(&LoopBB);
3246 
3247   // Read the next variant <- also loop target.
3248   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3249     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3250 
3251   // Compare the just read M0 value to all possible Idx values.
3252   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3253     .addReg(CurrentIdxReg)
3254     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3255 
3256   // Update EXEC, save the original EXEC value to VCC.
3257   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3258                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3259           NewExec)
3260     .addReg(CondReg, RegState::Kill);
3261 
3262   MRI.setSimpleHint(NewExec, CondReg);
3263 
3264   if (UseGPRIdxMode) {
3265     unsigned IdxReg;
3266     if (Offset == 0) {
3267       IdxReg = CurrentIdxReg;
3268     } else {
3269       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3270       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3271         .addReg(CurrentIdxReg, RegState::Kill)
3272         .addImm(Offset);
3273     }
3274     unsigned IdxMode = IsIndirectSrc ?
3275       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3276     MachineInstr *SetOn =
3277       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3278       .addReg(IdxReg, RegState::Kill)
3279       .addImm(IdxMode);
3280     SetOn->getOperand(3).setIsUndef();
3281   } else {
3282     // Move index from VCC into M0
3283     if (Offset == 0) {
3284       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3285         .addReg(CurrentIdxReg, RegState::Kill);
3286     } else {
3287       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3288         .addReg(CurrentIdxReg, RegState::Kill)
3289         .addImm(Offset);
3290     }
3291   }
3292 
3293   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3294   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3295   MachineInstr *InsertPt =
3296     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3297                                                   : AMDGPU::S_XOR_B64_term), Exec)
3298       .addReg(Exec)
3299       .addReg(NewExec);
3300 
3301   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3302   // s_cbranch_scc0?
3303 
3304   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3305   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3306     .addMBB(&LoopBB);
3307 
3308   return InsertPt->getIterator();
3309 }
3310 
3311 // This has slightly sub-optimal regalloc when the source vector is killed by
3312 // the read. The register allocator does not understand that the kill is
3313 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3314 // subregister from it, using 1 more VGPR than necessary. This was saved when
3315 // this was expanded after register allocation.
3316 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3317                                                   MachineBasicBlock &MBB,
3318                                                   MachineInstr &MI,
3319                                                   unsigned InitResultReg,
3320                                                   unsigned PhiReg,
3321                                                   int Offset,
3322                                                   bool UseGPRIdxMode,
3323                                                   bool IsIndirectSrc) {
3324   MachineFunction *MF = MBB.getParent();
3325   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3326   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3327   MachineRegisterInfo &MRI = MF->getRegInfo();
3328   const DebugLoc &DL = MI.getDebugLoc();
3329   MachineBasicBlock::iterator I(&MI);
3330 
3331   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3332   Register DstReg = MI.getOperand(0).getReg();
3333   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3334   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3335   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3336   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3337 
3338   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3339 
3340   // Save the EXEC mask
3341   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3342     .addReg(Exec);
3343 
3344   MachineBasicBlock *LoopBB;
3345   MachineBasicBlock *RemainderBB;
3346   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3347 
3348   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3349 
3350   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3351                                       InitResultReg, DstReg, PhiReg, TmpExec,
3352                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3353   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3354   MachineFunction::iterator MBBI(LoopBB);
3355   ++MBBI;
3356   MF->insert(MBBI, LandingPad);
3357   LoopBB->removeSuccessor(RemainderBB);
3358   LandingPad->addSuccessor(RemainderBB);
3359   LoopBB->addSuccessor(LandingPad);
3360   MachineBasicBlock::iterator First = LandingPad->begin();
3361   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3362     .addReg(SaveExec);
3363 
3364   return InsPt;
3365 }
3366 
3367 // Returns subreg index, offset
3368 static std::pair<unsigned, int>
3369 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3370                             const TargetRegisterClass *SuperRC,
3371                             unsigned VecReg,
3372                             int Offset) {
3373   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3374 
3375   // Skip out of bounds offsets, or else we would end up using an undefined
3376   // register.
3377   if (Offset >= NumElts || Offset < 0)
3378     return std::make_pair(AMDGPU::sub0, Offset);
3379 
3380   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3381 }
3382 
3383 // Return true if the index is an SGPR and was set.
3384 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3385                                  MachineRegisterInfo &MRI,
3386                                  MachineInstr &MI,
3387                                  int Offset,
3388                                  bool UseGPRIdxMode,
3389                                  bool IsIndirectSrc) {
3390   MachineBasicBlock *MBB = MI.getParent();
3391   const DebugLoc &DL = MI.getDebugLoc();
3392   MachineBasicBlock::iterator I(&MI);
3393 
3394   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3395   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3396 
3397   assert(Idx->getReg() != AMDGPU::NoRegister);
3398 
3399   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3400     return false;
3401 
3402   if (UseGPRIdxMode) {
3403     unsigned IdxMode = IsIndirectSrc ?
3404       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3405     if (Offset == 0) {
3406       MachineInstr *SetOn =
3407           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3408               .add(*Idx)
3409               .addImm(IdxMode);
3410 
3411       SetOn->getOperand(3).setIsUndef();
3412     } else {
3413       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3414       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3415           .add(*Idx)
3416           .addImm(Offset);
3417       MachineInstr *SetOn =
3418         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3419         .addReg(Tmp, RegState::Kill)
3420         .addImm(IdxMode);
3421 
3422       SetOn->getOperand(3).setIsUndef();
3423     }
3424 
3425     return true;
3426   }
3427 
3428   if (Offset == 0) {
3429     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3430       .add(*Idx);
3431   } else {
3432     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3433       .add(*Idx)
3434       .addImm(Offset);
3435   }
3436 
3437   return true;
3438 }
3439 
3440 // Control flow needs to be inserted if indexing with a VGPR.
3441 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3442                                           MachineBasicBlock &MBB,
3443                                           const GCNSubtarget &ST) {
3444   const SIInstrInfo *TII = ST.getInstrInfo();
3445   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3446   MachineFunction *MF = MBB.getParent();
3447   MachineRegisterInfo &MRI = MF->getRegInfo();
3448 
3449   Register Dst = MI.getOperand(0).getReg();
3450   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3451   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3452 
3453   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3454 
3455   unsigned SubReg;
3456   std::tie(SubReg, Offset)
3457     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3458 
3459   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3460 
3461   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3462     MachineBasicBlock::iterator I(&MI);
3463     const DebugLoc &DL = MI.getDebugLoc();
3464 
3465     if (UseGPRIdxMode) {
3466       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3467       // to avoid interfering with other uses, so probably requires a new
3468       // optimization pass.
3469       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3470         .addReg(SrcReg, RegState::Undef, SubReg)
3471         .addReg(SrcReg, RegState::Implicit)
3472         .addReg(AMDGPU::M0, RegState::Implicit);
3473       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3474     } else {
3475       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3476         .addReg(SrcReg, RegState::Undef, SubReg)
3477         .addReg(SrcReg, RegState::Implicit);
3478     }
3479 
3480     MI.eraseFromParent();
3481 
3482     return &MBB;
3483   }
3484 
3485   const DebugLoc &DL = MI.getDebugLoc();
3486   MachineBasicBlock::iterator I(&MI);
3487 
3488   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3489   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3490 
3491   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3492 
3493   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3494                               Offset, UseGPRIdxMode, true);
3495   MachineBasicBlock *LoopBB = InsPt->getParent();
3496 
3497   if (UseGPRIdxMode) {
3498     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3499       .addReg(SrcReg, RegState::Undef, SubReg)
3500       .addReg(SrcReg, RegState::Implicit)
3501       .addReg(AMDGPU::M0, RegState::Implicit);
3502     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3503   } else {
3504     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3505       .addReg(SrcReg, RegState::Undef, SubReg)
3506       .addReg(SrcReg, RegState::Implicit);
3507   }
3508 
3509   MI.eraseFromParent();
3510 
3511   return LoopBB;
3512 }
3513 
3514 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3515                                           MachineBasicBlock &MBB,
3516                                           const GCNSubtarget &ST) {
3517   const SIInstrInfo *TII = ST.getInstrInfo();
3518   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3519   MachineFunction *MF = MBB.getParent();
3520   MachineRegisterInfo &MRI = MF->getRegInfo();
3521 
3522   Register Dst = MI.getOperand(0).getReg();
3523   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3524   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3525   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3526   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3527   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3528 
3529   // This can be an immediate, but will be folded later.
3530   assert(Val->getReg());
3531 
3532   unsigned SubReg;
3533   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3534                                                          SrcVec->getReg(),
3535                                                          Offset);
3536   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3537 
3538   if (Idx->getReg() == AMDGPU::NoRegister) {
3539     MachineBasicBlock::iterator I(&MI);
3540     const DebugLoc &DL = MI.getDebugLoc();
3541 
3542     assert(Offset == 0);
3543 
3544     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3545         .add(*SrcVec)
3546         .add(*Val)
3547         .addImm(SubReg);
3548 
3549     MI.eraseFromParent();
3550     return &MBB;
3551   }
3552 
3553   const MCInstrDesc &MovRelDesc
3554     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3555 
3556   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3557     MachineBasicBlock::iterator I(&MI);
3558     const DebugLoc &DL = MI.getDebugLoc();
3559     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3560       .addReg(SrcVec->getReg())
3561       .add(*Val)
3562       .addImm(SubReg);
3563     if (UseGPRIdxMode)
3564       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3565 
3566     MI.eraseFromParent();
3567     return &MBB;
3568   }
3569 
3570   if (Val->isReg())
3571     MRI.clearKillFlags(Val->getReg());
3572 
3573   const DebugLoc &DL = MI.getDebugLoc();
3574 
3575   Register PhiReg = MRI.createVirtualRegister(VecRC);
3576 
3577   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3578                               Offset, UseGPRIdxMode, false);
3579   MachineBasicBlock *LoopBB = InsPt->getParent();
3580 
3581   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3582     .addReg(PhiReg)
3583     .add(*Val)
3584     .addImm(AMDGPU::sub0);
3585   if (UseGPRIdxMode)
3586     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3587 
3588   MI.eraseFromParent();
3589   return LoopBB;
3590 }
3591 
3592 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3593   MachineInstr &MI, MachineBasicBlock *BB) const {
3594 
3595   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3596   MachineFunction *MF = BB->getParent();
3597   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3598 
3599   if (TII->isMIMG(MI)) {
3600     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3601       report_fatal_error("missing mem operand from MIMG instruction");
3602     }
3603     // Add a memoperand for mimg instructions so that they aren't assumed to
3604     // be ordered memory instuctions.
3605 
3606     return BB;
3607   }
3608 
3609   switch (MI.getOpcode()) {
3610   case AMDGPU::S_UADDO_PSEUDO:
3611   case AMDGPU::S_USUBO_PSEUDO: {
3612     const DebugLoc &DL = MI.getDebugLoc();
3613     MachineOperand &Dest0 = MI.getOperand(0);
3614     MachineOperand &Dest1 = MI.getOperand(1);
3615     MachineOperand &Src0 = MI.getOperand(2);
3616     MachineOperand &Src1 = MI.getOperand(3);
3617 
3618     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3619                        ? AMDGPU::S_ADD_I32
3620                        : AMDGPU::S_SUB_I32;
3621     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3622 
3623     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3624         .addImm(1)
3625         .addImm(0);
3626 
3627     MI.eraseFromParent();
3628     return BB;
3629   }
3630   case AMDGPU::S_ADD_U64_PSEUDO:
3631   case AMDGPU::S_SUB_U64_PSEUDO: {
3632     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3633     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3634     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3635     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3636     const DebugLoc &DL = MI.getDebugLoc();
3637 
3638     MachineOperand &Dest = MI.getOperand(0);
3639     MachineOperand &Src0 = MI.getOperand(1);
3640     MachineOperand &Src1 = MI.getOperand(2);
3641 
3642     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3643     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3644 
3645     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3646         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3647     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3648         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3649 
3650     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3651         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3652     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3653         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3654 
3655     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3656 
3657     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3658     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3659     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3660     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3661     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3662         .addReg(DestSub0)
3663         .addImm(AMDGPU::sub0)
3664         .addReg(DestSub1)
3665         .addImm(AMDGPU::sub1);
3666     MI.eraseFromParent();
3667     return BB;
3668   }
3669   case AMDGPU::V_ADD_U64_PSEUDO:
3670   case AMDGPU::V_SUB_U64_PSEUDO: {
3671     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3672     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3673     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3674     const DebugLoc &DL = MI.getDebugLoc();
3675 
3676     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3677 
3678     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3679 
3680     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3681     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3682 
3683     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3684     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3685 
3686     MachineOperand &Dest = MI.getOperand(0);
3687     MachineOperand &Src0 = MI.getOperand(1);
3688     MachineOperand &Src1 = MI.getOperand(2);
3689 
3690     const TargetRegisterClass *Src0RC = Src0.isReg()
3691                                             ? MRI.getRegClass(Src0.getReg())
3692                                             : &AMDGPU::VReg_64RegClass;
3693     const TargetRegisterClass *Src1RC = Src1.isReg()
3694                                             ? MRI.getRegClass(Src1.getReg())
3695                                             : &AMDGPU::VReg_64RegClass;
3696 
3697     const TargetRegisterClass *Src0SubRC =
3698         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3699     const TargetRegisterClass *Src1SubRC =
3700         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3701 
3702     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3703         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3704     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3705         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3706 
3707     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3708         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3709     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3710         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3711 
3712     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
3713     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3714                                .addReg(CarryReg, RegState::Define)
3715                                .add(SrcReg0Sub0)
3716                                .add(SrcReg1Sub0)
3717                                .addImm(0); // clamp bit
3718 
3719     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3720     MachineInstr *HiHalf =
3721         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3722             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3723             .add(SrcReg0Sub1)
3724             .add(SrcReg1Sub1)
3725             .addReg(CarryReg, RegState::Kill)
3726             .addImm(0); // clamp bit
3727 
3728     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3729         .addReg(DestSub0)
3730         .addImm(AMDGPU::sub0)
3731         .addReg(DestSub1)
3732         .addImm(AMDGPU::sub1);
3733     TII->legalizeOperands(*LoHalf);
3734     TII->legalizeOperands(*HiHalf);
3735     MI.eraseFromParent();
3736     return BB;
3737   }
3738   case AMDGPU::S_ADD_CO_PSEUDO:
3739   case AMDGPU::S_SUB_CO_PSEUDO: {
3740     // This pseudo has a chance to be selected
3741     // only from uniform add/subcarry node. All the VGPR operands
3742     // therefore assumed to be splat vectors.
3743     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3744     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3745     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3746     MachineBasicBlock::iterator MII = MI;
3747     const DebugLoc &DL = MI.getDebugLoc();
3748     MachineOperand &Dest = MI.getOperand(0);
3749     MachineOperand &Src0 = MI.getOperand(2);
3750     MachineOperand &Src1 = MI.getOperand(3);
3751     MachineOperand &Src2 = MI.getOperand(4);
3752     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3753                        ? AMDGPU::S_ADDC_U32
3754                        : AMDGPU::S_SUBB_U32;
3755     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3756       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3757       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3758           .addReg(Src0.getReg());
3759       Src0.setReg(RegOp0);
3760     }
3761     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3762       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3763       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3764           .addReg(Src1.getReg());
3765       Src1.setReg(RegOp1);
3766     }
3767     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3768     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3769       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3770           .addReg(Src2.getReg());
3771       Src2.setReg(RegOp2);
3772     }
3773 
3774     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3775       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3776           .addReg(Src2.getReg())
3777           .addImm(0);
3778     } else {
3779       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3780           .addReg(Src2.getReg())
3781           .addImm(0);
3782     }
3783 
3784     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3785     MI.eraseFromParent();
3786     return BB;
3787   }
3788   case AMDGPU::SI_INIT_M0: {
3789     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3790             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3791         .add(MI.getOperand(0));
3792     MI.eraseFromParent();
3793     return BB;
3794   }
3795   case AMDGPU::SI_INIT_EXEC:
3796     // This should be before all vector instructions.
3797     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3798             AMDGPU::EXEC)
3799         .addImm(MI.getOperand(0).getImm());
3800     MI.eraseFromParent();
3801     return BB;
3802 
3803   case AMDGPU::SI_INIT_EXEC_LO:
3804     // This should be before all vector instructions.
3805     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3806             AMDGPU::EXEC_LO)
3807         .addImm(MI.getOperand(0).getImm());
3808     MI.eraseFromParent();
3809     return BB;
3810 
3811   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3812     // Extract the thread count from an SGPR input and set EXEC accordingly.
3813     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3814     //
3815     // S_BFE_U32 count, input, {shift, 7}
3816     // S_BFM_B64 exec, count, 0
3817     // S_CMP_EQ_U32 count, 64
3818     // S_CMOV_B64 exec, -1
3819     MachineInstr *FirstMI = &*BB->begin();
3820     MachineRegisterInfo &MRI = MF->getRegInfo();
3821     Register InputReg = MI.getOperand(0).getReg();
3822     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3823     bool Found = false;
3824 
3825     // Move the COPY of the input reg to the beginning, so that we can use it.
3826     for (auto I = BB->begin(); I != &MI; I++) {
3827       if (I->getOpcode() != TargetOpcode::COPY ||
3828           I->getOperand(0).getReg() != InputReg)
3829         continue;
3830 
3831       if (I == FirstMI) {
3832         FirstMI = &*++BB->begin();
3833       } else {
3834         I->removeFromParent();
3835         BB->insert(FirstMI, &*I);
3836       }
3837       Found = true;
3838       break;
3839     }
3840     assert(Found);
3841     (void)Found;
3842 
3843     // This should be before all vector instructions.
3844     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3845     bool isWave32 = getSubtarget()->isWave32();
3846     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3847     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3848         .addReg(InputReg)
3849         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3850     BuildMI(*BB, FirstMI, DebugLoc(),
3851             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3852             Exec)
3853         .addReg(CountReg)
3854         .addImm(0);
3855     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3856         .addReg(CountReg, RegState::Kill)
3857         .addImm(getSubtarget()->getWavefrontSize());
3858     BuildMI(*BB, FirstMI, DebugLoc(),
3859             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3860             Exec)
3861         .addImm(-1);
3862     MI.eraseFromParent();
3863     return BB;
3864   }
3865 
3866   case AMDGPU::GET_GROUPSTATICSIZE: {
3867     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3868            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3869     DebugLoc DL = MI.getDebugLoc();
3870     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3871         .add(MI.getOperand(0))
3872         .addImm(MFI->getLDSSize());
3873     MI.eraseFromParent();
3874     return BB;
3875   }
3876   case AMDGPU::SI_INDIRECT_SRC_V1:
3877   case AMDGPU::SI_INDIRECT_SRC_V2:
3878   case AMDGPU::SI_INDIRECT_SRC_V4:
3879   case AMDGPU::SI_INDIRECT_SRC_V8:
3880   case AMDGPU::SI_INDIRECT_SRC_V16:
3881     return emitIndirectSrc(MI, *BB, *getSubtarget());
3882   case AMDGPU::SI_INDIRECT_DST_V1:
3883   case AMDGPU::SI_INDIRECT_DST_V2:
3884   case AMDGPU::SI_INDIRECT_DST_V4:
3885   case AMDGPU::SI_INDIRECT_DST_V8:
3886   case AMDGPU::SI_INDIRECT_DST_V16:
3887     return emitIndirectDst(MI, *BB, *getSubtarget());
3888   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3889   case AMDGPU::SI_KILL_I1_PSEUDO:
3890     return splitKillBlock(MI, BB);
3891   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3892     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3893     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3894     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3895 
3896     Register Dst = MI.getOperand(0).getReg();
3897     Register Src0 = MI.getOperand(1).getReg();
3898     Register Src1 = MI.getOperand(2).getReg();
3899     const DebugLoc &DL = MI.getDebugLoc();
3900     Register SrcCond = MI.getOperand(3).getReg();
3901 
3902     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3903     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3904     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3905     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3906 
3907     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3908       .addReg(SrcCond);
3909     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3910       .addImm(0)
3911       .addReg(Src0, 0, AMDGPU::sub0)
3912       .addImm(0)
3913       .addReg(Src1, 0, AMDGPU::sub0)
3914       .addReg(SrcCondCopy);
3915     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3916       .addImm(0)
3917       .addReg(Src0, 0, AMDGPU::sub1)
3918       .addImm(0)
3919       .addReg(Src1, 0, AMDGPU::sub1)
3920       .addReg(SrcCondCopy);
3921 
3922     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3923       .addReg(DstLo)
3924       .addImm(AMDGPU::sub0)
3925       .addReg(DstHi)
3926       .addImm(AMDGPU::sub1);
3927     MI.eraseFromParent();
3928     return BB;
3929   }
3930   case AMDGPU::SI_BR_UNDEF: {
3931     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3932     const DebugLoc &DL = MI.getDebugLoc();
3933     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3934                            .add(MI.getOperand(0));
3935     Br->getOperand(1).setIsUndef(true); // read undef SCC
3936     MI.eraseFromParent();
3937     return BB;
3938   }
3939   case AMDGPU::ADJCALLSTACKUP:
3940   case AMDGPU::ADJCALLSTACKDOWN: {
3941     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3942     MachineInstrBuilder MIB(*MF, &MI);
3943 
3944     // Add an implicit use of the frame offset reg to prevent the restore copy
3945     // inserted after the call from being reorderd after stack operations in the
3946     // the caller's frame.
3947     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3948         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3949         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3950     return BB;
3951   }
3952   case AMDGPU::SI_CALL_ISEL: {
3953     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3954     const DebugLoc &DL = MI.getDebugLoc();
3955 
3956     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3957 
3958     MachineInstrBuilder MIB;
3959     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3960 
3961     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3962       MIB.add(MI.getOperand(I));
3963 
3964     MIB.cloneMemRefs(MI);
3965     MI.eraseFromParent();
3966     return BB;
3967   }
3968   case AMDGPU::V_ADD_I32_e32:
3969   case AMDGPU::V_SUB_I32_e32:
3970   case AMDGPU::V_SUBREV_I32_e32: {
3971     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3972     const DebugLoc &DL = MI.getDebugLoc();
3973     unsigned Opc = MI.getOpcode();
3974 
3975     bool NeedClampOperand = false;
3976     if (TII->pseudoToMCOpcode(Opc) == -1) {
3977       Opc = AMDGPU::getVOPe64(Opc);
3978       NeedClampOperand = true;
3979     }
3980 
3981     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3982     if (TII->isVOP3(*I)) {
3983       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3984       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3985       I.addReg(TRI->getVCC(), RegState::Define);
3986     }
3987     I.add(MI.getOperand(1))
3988      .add(MI.getOperand(2));
3989     if (NeedClampOperand)
3990       I.addImm(0); // clamp bit for e64 encoding
3991 
3992     TII->legalizeOperands(*I);
3993 
3994     MI.eraseFromParent();
3995     return BB;
3996   }
3997   case AMDGPU::DS_GWS_INIT:
3998   case AMDGPU::DS_GWS_SEMA_V:
3999   case AMDGPU::DS_GWS_SEMA_BR:
4000   case AMDGPU::DS_GWS_SEMA_P:
4001   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4002   case AMDGPU::DS_GWS_BARRIER:
4003     // A s_waitcnt 0 is required to be the instruction immediately following.
4004     if (getSubtarget()->hasGWSAutoReplay()) {
4005       bundleInstWithWaitcnt(MI);
4006       return BB;
4007     }
4008 
4009     return emitGWSMemViolTestLoop(MI, BB);
4010   default:
4011     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4012   }
4013 }
4014 
4015 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4016   return isTypeLegal(VT.getScalarType());
4017 }
4018 
4019 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4020   // This currently forces unfolding various combinations of fsub into fma with
4021   // free fneg'd operands. As long as we have fast FMA (controlled by
4022   // isFMAFasterThanFMulAndFAdd), we should perform these.
4023 
4024   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4025   // most of these combines appear to be cycle neutral but save on instruction
4026   // count / code size.
4027   return true;
4028 }
4029 
4030 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4031                                          EVT VT) const {
4032   if (!VT.isVector()) {
4033     return MVT::i1;
4034   }
4035   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4036 }
4037 
4038 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4039   // TODO: Should i16 be used always if legal? For now it would force VALU
4040   // shifts.
4041   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4042 }
4043 
4044 // Answering this is somewhat tricky and depends on the specific device which
4045 // have different rates for fma or all f64 operations.
4046 //
4047 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4048 // regardless of which device (although the number of cycles differs between
4049 // devices), so it is always profitable for f64.
4050 //
4051 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4052 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4053 // which we can always do even without fused FP ops since it returns the same
4054 // result as the separate operations and since it is always full
4055 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4056 // however does not support denormals, so we do report fma as faster if we have
4057 // a fast fma device and require denormals.
4058 //
4059 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4060                                                   EVT VT) const {
4061   VT = VT.getScalarType();
4062 
4063   switch (VT.getSimpleVT().SimpleTy) {
4064   case MVT::f32: {
4065     // This is as fast on some subtargets. However, we always have full rate f32
4066     // mad available which returns the same result as the separate operations
4067     // which we should prefer over fma. We can't use this if we want to support
4068     // denormals, so only report this in these cases.
4069     if (hasFP32Denormals(MF))
4070       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4071 
4072     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4073     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4074   }
4075   case MVT::f64:
4076     return true;
4077   case MVT::f16:
4078     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4079   default:
4080     break;
4081   }
4082 
4083   return false;
4084 }
4085 
4086 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4087                                    const SDNode *N) const {
4088   // TODO: Check future ftz flag
4089   // v_mad_f32/v_mac_f32 do not support denormals.
4090   EVT VT = N->getValueType(0);
4091   if (VT == MVT::f32)
4092     return !hasFP32Denormals(DAG.getMachineFunction());
4093   if (VT == MVT::f16) {
4094     return Subtarget->hasMadF16() &&
4095            !hasFP64FP16Denormals(DAG.getMachineFunction());
4096   }
4097 
4098   return false;
4099 }
4100 
4101 //===----------------------------------------------------------------------===//
4102 // Custom DAG Lowering Operations
4103 //===----------------------------------------------------------------------===//
4104 
4105 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4106 // wider vector type is legal.
4107 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4108                                              SelectionDAG &DAG) const {
4109   unsigned Opc = Op.getOpcode();
4110   EVT VT = Op.getValueType();
4111   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4112 
4113   SDValue Lo, Hi;
4114   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4115 
4116   SDLoc SL(Op);
4117   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4118                              Op->getFlags());
4119   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4120                              Op->getFlags());
4121 
4122   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4123 }
4124 
4125 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4126 // wider vector type is legal.
4127 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4128                                               SelectionDAG &DAG) const {
4129   unsigned Opc = Op.getOpcode();
4130   EVT VT = Op.getValueType();
4131   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4132 
4133   SDValue Lo0, Hi0;
4134   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4135   SDValue Lo1, Hi1;
4136   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4137 
4138   SDLoc SL(Op);
4139 
4140   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4141                              Op->getFlags());
4142   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4143                              Op->getFlags());
4144 
4145   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4146 }
4147 
4148 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4149                                               SelectionDAG &DAG) const {
4150   unsigned Opc = Op.getOpcode();
4151   EVT VT = Op.getValueType();
4152   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4153 
4154   SDValue Lo0, Hi0;
4155   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4156   SDValue Lo1, Hi1;
4157   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4158   SDValue Lo2, Hi2;
4159   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4160 
4161   SDLoc SL(Op);
4162 
4163   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4164                              Op->getFlags());
4165   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4166                              Op->getFlags());
4167 
4168   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4169 }
4170 
4171 
4172 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4173   switch (Op.getOpcode()) {
4174   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4175   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4176   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4177   case ISD::LOAD: {
4178     SDValue Result = LowerLOAD(Op, DAG);
4179     assert((!Result.getNode() ||
4180             Result.getNode()->getNumValues() == 2) &&
4181            "Load should return a value and a chain");
4182     return Result;
4183   }
4184 
4185   case ISD::FSIN:
4186   case ISD::FCOS:
4187     return LowerTrig(Op, DAG);
4188   case ISD::SELECT: return LowerSELECT(Op, DAG);
4189   case ISD::FDIV: return LowerFDIV(Op, DAG);
4190   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4191   case ISD::STORE: return LowerSTORE(Op, DAG);
4192   case ISD::GlobalAddress: {
4193     MachineFunction &MF = DAG.getMachineFunction();
4194     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4195     return LowerGlobalAddress(MFI, Op, DAG);
4196   }
4197   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4198   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4199   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4200   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4201   case ISD::INSERT_SUBVECTOR:
4202     return lowerINSERT_SUBVECTOR(Op, DAG);
4203   case ISD::INSERT_VECTOR_ELT:
4204     return lowerINSERT_VECTOR_ELT(Op, DAG);
4205   case ISD::EXTRACT_VECTOR_ELT:
4206     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4207   case ISD::VECTOR_SHUFFLE:
4208     return lowerVECTOR_SHUFFLE(Op, DAG);
4209   case ISD::BUILD_VECTOR:
4210     return lowerBUILD_VECTOR(Op, DAG);
4211   case ISD::FP_ROUND:
4212     return lowerFP_ROUND(Op, DAG);
4213   case ISD::TRAP:
4214     return lowerTRAP(Op, DAG);
4215   case ISD::DEBUGTRAP:
4216     return lowerDEBUGTRAP(Op, DAG);
4217   case ISD::FABS:
4218   case ISD::FNEG:
4219   case ISD::FCANONICALIZE:
4220   case ISD::BSWAP:
4221     return splitUnaryVectorOp(Op, DAG);
4222   case ISD::FMINNUM:
4223   case ISD::FMAXNUM:
4224     return lowerFMINNUM_FMAXNUM(Op, DAG);
4225   case ISD::FMA:
4226     return splitTernaryVectorOp(Op, DAG);
4227   case ISD::SHL:
4228   case ISD::SRA:
4229   case ISD::SRL:
4230   case ISD::ADD:
4231   case ISD::SUB:
4232   case ISD::MUL:
4233   case ISD::SMIN:
4234   case ISD::SMAX:
4235   case ISD::UMIN:
4236   case ISD::UMAX:
4237   case ISD::FADD:
4238   case ISD::FMUL:
4239   case ISD::FMINNUM_IEEE:
4240   case ISD::FMAXNUM_IEEE:
4241     return splitBinaryVectorOp(Op, DAG);
4242   }
4243   return SDValue();
4244 }
4245 
4246 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4247                                        const SDLoc &DL,
4248                                        SelectionDAG &DAG, bool Unpacked) {
4249   if (!LoadVT.isVector())
4250     return Result;
4251 
4252   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4253     // Truncate to v2i16/v4i16.
4254     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4255 
4256     // Workaround legalizer not scalarizing truncate after vector op
4257     // legalization byt not creating intermediate vector trunc.
4258     SmallVector<SDValue, 4> Elts;
4259     DAG.ExtractVectorElements(Result, Elts);
4260     for (SDValue &Elt : Elts)
4261       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4262 
4263     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4264 
4265     // Bitcast to original type (v2f16/v4f16).
4266     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4267   }
4268 
4269   // Cast back to the original packed type.
4270   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4271 }
4272 
4273 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4274                                               MemSDNode *M,
4275                                               SelectionDAG &DAG,
4276                                               ArrayRef<SDValue> Ops,
4277                                               bool IsIntrinsic) const {
4278   SDLoc DL(M);
4279 
4280   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4281   EVT LoadVT = M->getValueType(0);
4282 
4283   EVT EquivLoadVT = LoadVT;
4284   if (Unpacked && LoadVT.isVector()) {
4285     EquivLoadVT = LoadVT.isVector() ?
4286       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4287                        LoadVT.getVectorNumElements()) : LoadVT;
4288   }
4289 
4290   // Change from v4f16/v2f16 to EquivLoadVT.
4291   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4292 
4293   SDValue Load
4294     = DAG.getMemIntrinsicNode(
4295       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4296       VTList, Ops, M->getMemoryVT(),
4297       M->getMemOperand());
4298   if (!Unpacked) // Just adjusted the opcode.
4299     return Load;
4300 
4301   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4302 
4303   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4304 }
4305 
4306 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4307                                              SelectionDAG &DAG,
4308                                              ArrayRef<SDValue> Ops) const {
4309   SDLoc DL(M);
4310   EVT LoadVT = M->getValueType(0);
4311   EVT EltType = LoadVT.getScalarType();
4312   EVT IntVT = LoadVT.changeTypeToInteger();
4313 
4314   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4315 
4316   unsigned Opc =
4317       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4318 
4319   if (IsD16) {
4320     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4321   }
4322 
4323   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4324   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4325     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4326 
4327   if (isTypeLegal(LoadVT)) {
4328     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4329                                M->getMemOperand(), DAG);
4330   }
4331 
4332   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4333   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4334   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4335                                         M->getMemOperand(), DAG);
4336   return DAG.getMergeValues(
4337       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4338       DL);
4339 }
4340 
4341 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4342                                   SDNode *N, SelectionDAG &DAG) {
4343   EVT VT = N->getValueType(0);
4344   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4345   int CondCode = CD->getSExtValue();
4346   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4347       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4348     return DAG.getUNDEF(VT);
4349 
4350   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4351 
4352   SDValue LHS = N->getOperand(1);
4353   SDValue RHS = N->getOperand(2);
4354 
4355   SDLoc DL(N);
4356 
4357   EVT CmpVT = LHS.getValueType();
4358   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4359     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4360       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4361     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4362     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4363   }
4364 
4365   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4366 
4367   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4368   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4369 
4370   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4371                               DAG.getCondCode(CCOpcode));
4372   if (VT.bitsEq(CCVT))
4373     return SetCC;
4374   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4375 }
4376 
4377 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4378                                   SDNode *N, SelectionDAG &DAG) {
4379   EVT VT = N->getValueType(0);
4380   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4381 
4382   int CondCode = CD->getSExtValue();
4383   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4384       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4385     return DAG.getUNDEF(VT);
4386   }
4387 
4388   SDValue Src0 = N->getOperand(1);
4389   SDValue Src1 = N->getOperand(2);
4390   EVT CmpVT = Src0.getValueType();
4391   SDLoc SL(N);
4392 
4393   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4394     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4395     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4396   }
4397 
4398   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4399   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4400   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4401   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4402   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4403                               Src1, DAG.getCondCode(CCOpcode));
4404   if (VT.bitsEq(CCVT))
4405     return SetCC;
4406   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4407 }
4408 
4409 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4410                                     SelectionDAG &DAG) {
4411   EVT VT = N->getValueType(0);
4412   SDValue Src = N->getOperand(1);
4413   SDLoc SL(N);
4414 
4415   if (Src.getOpcode() == ISD::SETCC) {
4416     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4417     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4418                        Src.getOperand(1), Src.getOperand(2));
4419   }
4420   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4421     // (ballot 0) -> 0
4422     if (Arg->isNullValue())
4423       return DAG.getConstant(0, SL, VT);
4424 
4425     // (ballot 1) -> EXEC/EXEC_LO
4426     if (Arg->isOne()) {
4427       Register Exec;
4428       if (VT.getScalarSizeInBits() == 32)
4429         Exec = AMDGPU::EXEC_LO;
4430       else if (VT.getScalarSizeInBits() == 64)
4431         Exec = AMDGPU::EXEC;
4432       else
4433         return SDValue();
4434 
4435       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4436     }
4437   }
4438 
4439   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4440   // ISD::SETNE)
4441   return DAG.getNode(
4442       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4443       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4444 }
4445 
4446 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4447                                           SmallVectorImpl<SDValue> &Results,
4448                                           SelectionDAG &DAG) const {
4449   switch (N->getOpcode()) {
4450   case ISD::INSERT_VECTOR_ELT: {
4451     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4452       Results.push_back(Res);
4453     return;
4454   }
4455   case ISD::EXTRACT_VECTOR_ELT: {
4456     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4457       Results.push_back(Res);
4458     return;
4459   }
4460   case ISD::INTRINSIC_WO_CHAIN: {
4461     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4462     switch (IID) {
4463     case Intrinsic::amdgcn_cvt_pkrtz: {
4464       SDValue Src0 = N->getOperand(1);
4465       SDValue Src1 = N->getOperand(2);
4466       SDLoc SL(N);
4467       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4468                                 Src0, Src1);
4469       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4470       return;
4471     }
4472     case Intrinsic::amdgcn_cvt_pknorm_i16:
4473     case Intrinsic::amdgcn_cvt_pknorm_u16:
4474     case Intrinsic::amdgcn_cvt_pk_i16:
4475     case Intrinsic::amdgcn_cvt_pk_u16: {
4476       SDValue Src0 = N->getOperand(1);
4477       SDValue Src1 = N->getOperand(2);
4478       SDLoc SL(N);
4479       unsigned Opcode;
4480 
4481       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4482         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4483       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4484         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4485       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4486         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4487       else
4488         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4489 
4490       EVT VT = N->getValueType(0);
4491       if (isTypeLegal(VT))
4492         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4493       else {
4494         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4495         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4496       }
4497       return;
4498     }
4499     }
4500     break;
4501   }
4502   case ISD::INTRINSIC_W_CHAIN: {
4503     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4504       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4505         // FIXME: Hacky
4506         Results.push_back(Res.getOperand(0));
4507         Results.push_back(Res.getOperand(1));
4508       } else {
4509         Results.push_back(Res);
4510         Results.push_back(Res.getValue(1));
4511       }
4512       return;
4513     }
4514 
4515     break;
4516   }
4517   case ISD::SELECT: {
4518     SDLoc SL(N);
4519     EVT VT = N->getValueType(0);
4520     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4521     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4522     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4523 
4524     EVT SelectVT = NewVT;
4525     if (NewVT.bitsLT(MVT::i32)) {
4526       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4527       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4528       SelectVT = MVT::i32;
4529     }
4530 
4531     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4532                                     N->getOperand(0), LHS, RHS);
4533 
4534     if (NewVT != SelectVT)
4535       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4536     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4537     return;
4538   }
4539   case ISD::FNEG: {
4540     if (N->getValueType(0) != MVT::v2f16)
4541       break;
4542 
4543     SDLoc SL(N);
4544     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4545 
4546     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4547                              BC,
4548                              DAG.getConstant(0x80008000, SL, MVT::i32));
4549     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4550     return;
4551   }
4552   case ISD::FABS: {
4553     if (N->getValueType(0) != MVT::v2f16)
4554       break;
4555 
4556     SDLoc SL(N);
4557     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4558 
4559     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4560                              BC,
4561                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4562     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4563     return;
4564   }
4565   default:
4566     break;
4567   }
4568 }
4569 
4570 /// Helper function for LowerBRCOND
4571 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4572 
4573   SDNode *Parent = Value.getNode();
4574   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4575        I != E; ++I) {
4576 
4577     if (I.getUse().get() != Value)
4578       continue;
4579 
4580     if (I->getOpcode() == Opcode)
4581       return *I;
4582   }
4583   return nullptr;
4584 }
4585 
4586 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4587   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4588     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4589     case Intrinsic::amdgcn_if:
4590       return AMDGPUISD::IF;
4591     case Intrinsic::amdgcn_else:
4592       return AMDGPUISD::ELSE;
4593     case Intrinsic::amdgcn_loop:
4594       return AMDGPUISD::LOOP;
4595     case Intrinsic::amdgcn_end_cf:
4596       llvm_unreachable("should not occur");
4597     default:
4598       return 0;
4599     }
4600   }
4601 
4602   // break, if_break, else_break are all only used as inputs to loop, not
4603   // directly as branch conditions.
4604   return 0;
4605 }
4606 
4607 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4608   const Triple &TT = getTargetMachine().getTargetTriple();
4609   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4610           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4611          AMDGPU::shouldEmitConstantsToTextSection(TT);
4612 }
4613 
4614 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4615   // FIXME: Either avoid relying on address space here or change the default
4616   // address space for functions to avoid the explicit check.
4617   return (GV->getValueType()->isFunctionTy() ||
4618           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4619          !shouldEmitFixup(GV) &&
4620          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4621 }
4622 
4623 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4624   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4625 }
4626 
4627 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4628   if (!GV->hasExternalLinkage())
4629     return true;
4630 
4631   const auto OS = getTargetMachine().getTargetTriple().getOS();
4632   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4633 }
4634 
4635 /// This transforms the control flow intrinsics to get the branch destination as
4636 /// last parameter, also switches branch target with BR if the need arise
4637 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4638                                       SelectionDAG &DAG) const {
4639   SDLoc DL(BRCOND);
4640 
4641   SDNode *Intr = BRCOND.getOperand(1).getNode();
4642   SDValue Target = BRCOND.getOperand(2);
4643   SDNode *BR = nullptr;
4644   SDNode *SetCC = nullptr;
4645 
4646   if (Intr->getOpcode() == ISD::SETCC) {
4647     // As long as we negate the condition everything is fine
4648     SetCC = Intr;
4649     Intr = SetCC->getOperand(0).getNode();
4650 
4651   } else {
4652     // Get the target from BR if we don't negate the condition
4653     BR = findUser(BRCOND, ISD::BR);
4654     Target = BR->getOperand(1);
4655   }
4656 
4657   // FIXME: This changes the types of the intrinsics instead of introducing new
4658   // nodes with the correct types.
4659   // e.g. llvm.amdgcn.loop
4660 
4661   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4662   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4663 
4664   unsigned CFNode = isCFIntrinsic(Intr);
4665   if (CFNode == 0) {
4666     // This is a uniform branch so we don't need to legalize.
4667     return BRCOND;
4668   }
4669 
4670   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4671                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4672 
4673   assert(!SetCC ||
4674         (SetCC->getConstantOperandVal(1) == 1 &&
4675          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4676                                                              ISD::SETNE));
4677 
4678   // operands of the new intrinsic call
4679   SmallVector<SDValue, 4> Ops;
4680   if (HaveChain)
4681     Ops.push_back(BRCOND.getOperand(0));
4682 
4683   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4684   Ops.push_back(Target);
4685 
4686   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4687 
4688   // build the new intrinsic call
4689   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4690 
4691   if (!HaveChain) {
4692     SDValue Ops[] =  {
4693       SDValue(Result, 0),
4694       BRCOND.getOperand(0)
4695     };
4696 
4697     Result = DAG.getMergeValues(Ops, DL).getNode();
4698   }
4699 
4700   if (BR) {
4701     // Give the branch instruction our target
4702     SDValue Ops[] = {
4703       BR->getOperand(0),
4704       BRCOND.getOperand(2)
4705     };
4706     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4707     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4708   }
4709 
4710   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4711 
4712   // Copy the intrinsic results to registers
4713   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4714     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4715     if (!CopyToReg)
4716       continue;
4717 
4718     Chain = DAG.getCopyToReg(
4719       Chain, DL,
4720       CopyToReg->getOperand(1),
4721       SDValue(Result, i - 1),
4722       SDValue());
4723 
4724     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4725   }
4726 
4727   // Remove the old intrinsic from the chain
4728   DAG.ReplaceAllUsesOfValueWith(
4729     SDValue(Intr, Intr->getNumValues() - 1),
4730     Intr->getOperand(0));
4731 
4732   return Chain;
4733 }
4734 
4735 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4736                                           SelectionDAG &DAG) const {
4737   MVT VT = Op.getSimpleValueType();
4738   SDLoc DL(Op);
4739   // Checking the depth
4740   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4741     return DAG.getConstant(0, DL, VT);
4742 
4743   MachineFunction &MF = DAG.getMachineFunction();
4744   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4745   // Check for kernel and shader functions
4746   if (Info->isEntryFunction())
4747     return DAG.getConstant(0, DL, VT);
4748 
4749   MachineFrameInfo &MFI = MF.getFrameInfo();
4750   // There is a call to @llvm.returnaddress in this function
4751   MFI.setReturnAddressIsTaken(true);
4752 
4753   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4754   // Get the return address reg and mark it as an implicit live-in
4755   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4756 
4757   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4758 }
4759 
4760 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4761                                             SDValue Op,
4762                                             const SDLoc &DL,
4763                                             EVT VT) const {
4764   return Op.getValueType().bitsLE(VT) ?
4765       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4766     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4767                 DAG.getTargetConstant(0, DL, MVT::i32));
4768 }
4769 
4770 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4771   assert(Op.getValueType() == MVT::f16 &&
4772          "Do not know how to custom lower FP_ROUND for non-f16 type");
4773 
4774   SDValue Src = Op.getOperand(0);
4775   EVT SrcVT = Src.getValueType();
4776   if (SrcVT != MVT::f64)
4777     return Op;
4778 
4779   SDLoc DL(Op);
4780 
4781   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4782   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4783   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4784 }
4785 
4786 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4787                                                SelectionDAG &DAG) const {
4788   EVT VT = Op.getValueType();
4789   const MachineFunction &MF = DAG.getMachineFunction();
4790   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4791   bool IsIEEEMode = Info->getMode().IEEE;
4792 
4793   // FIXME: Assert during selection that this is only selected for
4794   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4795   // mode functions, but this happens to be OK since it's only done in cases
4796   // where there is known no sNaN.
4797   if (IsIEEEMode)
4798     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4799 
4800   if (VT == MVT::v4f16)
4801     return splitBinaryVectorOp(Op, DAG);
4802   return Op;
4803 }
4804 
4805 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4806   SDLoc SL(Op);
4807   SDValue Chain = Op.getOperand(0);
4808 
4809   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4810       !Subtarget->isTrapHandlerEnabled())
4811     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4812 
4813   MachineFunction &MF = DAG.getMachineFunction();
4814   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4815   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4816   assert(UserSGPR != AMDGPU::NoRegister);
4817   SDValue QueuePtr = CreateLiveInRegister(
4818     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4819   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4820   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4821                                    QueuePtr, SDValue());
4822   SDValue Ops[] = {
4823     ToReg,
4824     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4825     SGPR01,
4826     ToReg.getValue(1)
4827   };
4828   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4829 }
4830 
4831 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4832   SDLoc SL(Op);
4833   SDValue Chain = Op.getOperand(0);
4834   MachineFunction &MF = DAG.getMachineFunction();
4835 
4836   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4837       !Subtarget->isTrapHandlerEnabled()) {
4838     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4839                                      "debugtrap handler not supported",
4840                                      Op.getDebugLoc(),
4841                                      DS_Warning);
4842     LLVMContext &Ctx = MF.getFunction().getContext();
4843     Ctx.diagnose(NoTrap);
4844     return Chain;
4845   }
4846 
4847   SDValue Ops[] = {
4848     Chain,
4849     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4850   };
4851   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4852 }
4853 
4854 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4855                                              SelectionDAG &DAG) const {
4856   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4857   if (Subtarget->hasApertureRegs()) {
4858     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4859         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4860         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4861     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4862         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4863         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4864     unsigned Encoding =
4865         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4866         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4867         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4868 
4869     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4870     SDValue ApertureReg = SDValue(
4871         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4872     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4873     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4874   }
4875 
4876   MachineFunction &MF = DAG.getMachineFunction();
4877   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4878   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4879   assert(UserSGPR != AMDGPU::NoRegister);
4880 
4881   SDValue QueuePtr = CreateLiveInRegister(
4882     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4883 
4884   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4885   // private_segment_aperture_base_hi.
4886   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4887 
4888   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4889 
4890   // TODO: Use custom target PseudoSourceValue.
4891   // TODO: We should use the value from the IR intrinsic call, but it might not
4892   // be available and how do we get it?
4893   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4894   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4895                      MinAlign(64, StructOffset),
4896                      MachineMemOperand::MODereferenceable |
4897                          MachineMemOperand::MOInvariant);
4898 }
4899 
4900 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4901                                              SelectionDAG &DAG) const {
4902   SDLoc SL(Op);
4903   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4904 
4905   SDValue Src = ASC->getOperand(0);
4906   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4907 
4908   const AMDGPUTargetMachine &TM =
4909     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4910 
4911   // flat -> local/private
4912   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4913     unsigned DestAS = ASC->getDestAddressSpace();
4914 
4915     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4916         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4917       unsigned NullVal = TM.getNullPointerValue(DestAS);
4918       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4919       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4920       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4921 
4922       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4923                          NonNull, Ptr, SegmentNullPtr);
4924     }
4925   }
4926 
4927   // local/private -> flat
4928   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4929     unsigned SrcAS = ASC->getSrcAddressSpace();
4930 
4931     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4932         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4933       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4934       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4935 
4936       SDValue NonNull
4937         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4938 
4939       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4940       SDValue CvtPtr
4941         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4942 
4943       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4944                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4945                          FlatNullPtr);
4946     }
4947   }
4948 
4949   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
4950       Src.getValueType() == MVT::i64)
4951     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4952 
4953   // global <-> flat are no-ops and never emitted.
4954 
4955   const MachineFunction &MF = DAG.getMachineFunction();
4956   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4957     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4958   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4959 
4960   return DAG.getUNDEF(ASC->getValueType(0));
4961 }
4962 
4963 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4964 // the small vector and inserting them into the big vector. That is better than
4965 // the default expansion of doing it via a stack slot. Even though the use of
4966 // the stack slot would be optimized away afterwards, the stack slot itself
4967 // remains.
4968 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4969                                                 SelectionDAG &DAG) const {
4970   SDValue Vec = Op.getOperand(0);
4971   SDValue Ins = Op.getOperand(1);
4972   SDValue Idx = Op.getOperand(2);
4973   EVT VecVT = Vec.getValueType();
4974   EVT InsVT = Ins.getValueType();
4975   EVT EltVT = VecVT.getVectorElementType();
4976   unsigned InsNumElts = InsVT.getVectorNumElements();
4977   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4978   SDLoc SL(Op);
4979 
4980   for (unsigned I = 0; I != InsNumElts; ++I) {
4981     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4982                               DAG.getConstant(I, SL, MVT::i32));
4983     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4984                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4985   }
4986   return Vec;
4987 }
4988 
4989 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4990                                                  SelectionDAG &DAG) const {
4991   SDValue Vec = Op.getOperand(0);
4992   SDValue InsVal = Op.getOperand(1);
4993   SDValue Idx = Op.getOperand(2);
4994   EVT VecVT = Vec.getValueType();
4995   EVT EltVT = VecVT.getVectorElementType();
4996   unsigned VecSize = VecVT.getSizeInBits();
4997   unsigned EltSize = EltVT.getSizeInBits();
4998 
4999 
5000   assert(VecSize <= 64);
5001 
5002   unsigned NumElts = VecVT.getVectorNumElements();
5003   SDLoc SL(Op);
5004   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5005 
5006   if (NumElts == 4 && EltSize == 16 && KIdx) {
5007     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5008 
5009     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5010                                  DAG.getConstant(0, SL, MVT::i32));
5011     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5012                                  DAG.getConstant(1, SL, MVT::i32));
5013 
5014     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5015     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5016 
5017     unsigned Idx = KIdx->getZExtValue();
5018     bool InsertLo = Idx < 2;
5019     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5020       InsertLo ? LoVec : HiVec,
5021       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5022       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5023 
5024     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5025 
5026     SDValue Concat = InsertLo ?
5027       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5028       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5029 
5030     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5031   }
5032 
5033   if (isa<ConstantSDNode>(Idx))
5034     return SDValue();
5035 
5036   MVT IntVT = MVT::getIntegerVT(VecSize);
5037 
5038   // Avoid stack access for dynamic indexing.
5039   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5040 
5041   // Create a congruent vector with the target value in each element so that
5042   // the required element can be masked and ORed into the target vector.
5043   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5044                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5045 
5046   assert(isPowerOf2_32(EltSize));
5047   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5048 
5049   // Convert vector index to bit-index.
5050   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5051 
5052   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5053   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5054                             DAG.getConstant(0xffff, SL, IntVT),
5055                             ScaledIdx);
5056 
5057   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5058   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5059                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5060 
5061   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5062   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5063 }
5064 
5065 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5066                                                   SelectionDAG &DAG) const {
5067   SDLoc SL(Op);
5068 
5069   EVT ResultVT = Op.getValueType();
5070   SDValue Vec = Op.getOperand(0);
5071   SDValue Idx = Op.getOperand(1);
5072   EVT VecVT = Vec.getValueType();
5073   unsigned VecSize = VecVT.getSizeInBits();
5074   EVT EltVT = VecVT.getVectorElementType();
5075   assert(VecSize <= 64);
5076 
5077   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5078 
5079   // Make sure we do any optimizations that will make it easier to fold
5080   // source modifiers before obscuring it with bit operations.
5081 
5082   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5083   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5084     return Combined;
5085 
5086   unsigned EltSize = EltVT.getSizeInBits();
5087   assert(isPowerOf2_32(EltSize));
5088 
5089   MVT IntVT = MVT::getIntegerVT(VecSize);
5090   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5091 
5092   // Convert vector index to bit-index (* EltSize)
5093   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5094 
5095   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5096   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5097 
5098   if (ResultVT == MVT::f16) {
5099     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5100     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5101   }
5102 
5103   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5104 }
5105 
5106 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5107   assert(Elt % 2 == 0);
5108   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5109 }
5110 
5111 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5112                                               SelectionDAG &DAG) const {
5113   SDLoc SL(Op);
5114   EVT ResultVT = Op.getValueType();
5115   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5116 
5117   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5118   EVT EltVT = PackVT.getVectorElementType();
5119   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5120 
5121   // vector_shuffle <0,1,6,7> lhs, rhs
5122   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5123   //
5124   // vector_shuffle <6,7,2,3> lhs, rhs
5125   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5126   //
5127   // vector_shuffle <6,7,0,1> lhs, rhs
5128   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5129 
5130   // Avoid scalarizing when both halves are reading from consecutive elements.
5131   SmallVector<SDValue, 4> Pieces;
5132   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5133     if (elementPairIsContiguous(SVN->getMask(), I)) {
5134       const int Idx = SVN->getMaskElt(I);
5135       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5136       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5137       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5138                                     PackVT, SVN->getOperand(VecIdx),
5139                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5140       Pieces.push_back(SubVec);
5141     } else {
5142       const int Idx0 = SVN->getMaskElt(I);
5143       const int Idx1 = SVN->getMaskElt(I + 1);
5144       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5145       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5146       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5147       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5148 
5149       SDValue Vec0 = SVN->getOperand(VecIdx0);
5150       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5151                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5152 
5153       SDValue Vec1 = SVN->getOperand(VecIdx1);
5154       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5155                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5156       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5157     }
5158   }
5159 
5160   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5161 }
5162 
5163 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5164                                             SelectionDAG &DAG) const {
5165   SDLoc SL(Op);
5166   EVT VT = Op.getValueType();
5167 
5168   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5169     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5170 
5171     // Turn into pair of packed build_vectors.
5172     // TODO: Special case for constants that can be materialized with s_mov_b64.
5173     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5174                                     { Op.getOperand(0), Op.getOperand(1) });
5175     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5176                                     { Op.getOperand(2), Op.getOperand(3) });
5177 
5178     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5179     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5180 
5181     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5182     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5183   }
5184 
5185   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5186   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5187 
5188   SDValue Lo = Op.getOperand(0);
5189   SDValue Hi = Op.getOperand(1);
5190 
5191   // Avoid adding defined bits with the zero_extend.
5192   if (Hi.isUndef()) {
5193     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5194     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5195     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5196   }
5197 
5198   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5199   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5200 
5201   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5202                               DAG.getConstant(16, SL, MVT::i32));
5203   if (Lo.isUndef())
5204     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5205 
5206   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5207   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5208 
5209   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5210   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5211 }
5212 
5213 bool
5214 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5215   // We can fold offsets for anything that doesn't require a GOT relocation.
5216   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5217           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5218           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5219          !shouldEmitGOTReloc(GA->getGlobal());
5220 }
5221 
5222 static SDValue
5223 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5224                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5225                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5226   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5227   // lowered to the following code sequence:
5228   //
5229   // For constant address space:
5230   //   s_getpc_b64 s[0:1]
5231   //   s_add_u32 s0, s0, $symbol
5232   //   s_addc_u32 s1, s1, 0
5233   //
5234   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5235   //   a fixup or relocation is emitted to replace $symbol with a literal
5236   //   constant, which is a pc-relative offset from the encoding of the $symbol
5237   //   operand to the global variable.
5238   //
5239   // For global address space:
5240   //   s_getpc_b64 s[0:1]
5241   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5242   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5243   //
5244   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5245   //   fixups or relocations are emitted to replace $symbol@*@lo and
5246   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5247   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5248   //   operand to the global variable.
5249   //
5250   // What we want here is an offset from the value returned by s_getpc
5251   // (which is the address of the s_add_u32 instruction) to the global
5252   // variable, but since the encoding of $symbol starts 4 bytes after the start
5253   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5254   // small. This requires us to add 4 to the global variable offset in order to
5255   // compute the correct address.
5256   SDValue PtrLo =
5257       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5258   SDValue PtrHi;
5259   if (GAFlags == SIInstrInfo::MO_NONE) {
5260     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5261   } else {
5262     PtrHi =
5263         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5264   }
5265   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5266 }
5267 
5268 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5269                                              SDValue Op,
5270                                              SelectionDAG &DAG) const {
5271   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5272   const GlobalValue *GV = GSD->getGlobal();
5273   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5274        shouldUseLDSConstAddress(GV)) ||
5275       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5276       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5277     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5278 
5279   SDLoc DL(GSD);
5280   EVT PtrVT = Op.getValueType();
5281 
5282   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5283     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5284                                             SIInstrInfo::MO_ABS32_LO);
5285     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5286   }
5287 
5288   if (shouldEmitFixup(GV))
5289     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5290   else if (shouldEmitPCReloc(GV))
5291     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5292                                    SIInstrInfo::MO_REL32);
5293 
5294   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5295                                             SIInstrInfo::MO_GOTPCREL32);
5296 
5297   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5298   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5299   const DataLayout &DataLayout = DAG.getDataLayout();
5300   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5301   MachinePointerInfo PtrInfo
5302     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5303 
5304   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5305                      MachineMemOperand::MODereferenceable |
5306                          MachineMemOperand::MOInvariant);
5307 }
5308 
5309 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5310                                    const SDLoc &DL, SDValue V) const {
5311   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5312   // the destination register.
5313   //
5314   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5315   // so we will end up with redundant moves to m0.
5316   //
5317   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5318 
5319   // A Null SDValue creates a glue result.
5320   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5321                                   V, Chain);
5322   return SDValue(M0, 0);
5323 }
5324 
5325 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5326                                                  SDValue Op,
5327                                                  MVT VT,
5328                                                  unsigned Offset) const {
5329   SDLoc SL(Op);
5330   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5331                                            DAG.getEntryNode(), Offset, 4, false);
5332   // The local size values will have the hi 16-bits as zero.
5333   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5334                      DAG.getValueType(VT));
5335 }
5336 
5337 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5338                                         EVT VT) {
5339   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5340                                       "non-hsa intrinsic with hsa target",
5341                                       DL.getDebugLoc());
5342   DAG.getContext()->diagnose(BadIntrin);
5343   return DAG.getUNDEF(VT);
5344 }
5345 
5346 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5347                                          EVT VT) {
5348   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5349                                       "intrinsic not supported on subtarget",
5350                                       DL.getDebugLoc());
5351   DAG.getContext()->diagnose(BadIntrin);
5352   return DAG.getUNDEF(VT);
5353 }
5354 
5355 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5356                                     ArrayRef<SDValue> Elts) {
5357   assert(!Elts.empty());
5358   MVT Type;
5359   unsigned NumElts;
5360 
5361   if (Elts.size() == 1) {
5362     Type = MVT::f32;
5363     NumElts = 1;
5364   } else if (Elts.size() == 2) {
5365     Type = MVT::v2f32;
5366     NumElts = 2;
5367   } else if (Elts.size() == 3) {
5368     Type = MVT::v3f32;
5369     NumElts = 3;
5370   } else if (Elts.size() <= 4) {
5371     Type = MVT::v4f32;
5372     NumElts = 4;
5373   } else if (Elts.size() <= 8) {
5374     Type = MVT::v8f32;
5375     NumElts = 8;
5376   } else {
5377     assert(Elts.size() <= 16);
5378     Type = MVT::v16f32;
5379     NumElts = 16;
5380   }
5381 
5382   SmallVector<SDValue, 16> VecElts(NumElts);
5383   for (unsigned i = 0; i < Elts.size(); ++i) {
5384     SDValue Elt = Elts[i];
5385     if (Elt.getValueType() != MVT::f32)
5386       Elt = DAG.getBitcast(MVT::f32, Elt);
5387     VecElts[i] = Elt;
5388   }
5389   for (unsigned i = Elts.size(); i < NumElts; ++i)
5390     VecElts[i] = DAG.getUNDEF(MVT::f32);
5391 
5392   if (NumElts == 1)
5393     return VecElts[0];
5394   return DAG.getBuildVector(Type, DL, VecElts);
5395 }
5396 
5397 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5398                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5399   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5400 
5401   uint64_t Value = CachePolicyConst->getZExtValue();
5402   SDLoc DL(CachePolicy);
5403   if (GLC) {
5404     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5405     Value &= ~(uint64_t)0x1;
5406   }
5407   if (SLC) {
5408     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5409     Value &= ~(uint64_t)0x2;
5410   }
5411   if (DLC) {
5412     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5413     Value &= ~(uint64_t)0x4;
5414   }
5415 
5416   return Value == 0;
5417 }
5418 
5419 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5420                               SDValue Src, int ExtraElts) {
5421   EVT SrcVT = Src.getValueType();
5422 
5423   SmallVector<SDValue, 8> Elts;
5424 
5425   if (SrcVT.isVector())
5426     DAG.ExtractVectorElements(Src, Elts);
5427   else
5428     Elts.push_back(Src);
5429 
5430   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5431   while (ExtraElts--)
5432     Elts.push_back(Undef);
5433 
5434   return DAG.getBuildVector(CastVT, DL, Elts);
5435 }
5436 
5437 // Re-construct the required return value for a image load intrinsic.
5438 // This is more complicated due to the optional use TexFailCtrl which means the required
5439 // return type is an aggregate
5440 static SDValue constructRetValue(SelectionDAG &DAG,
5441                                  MachineSDNode *Result,
5442                                  ArrayRef<EVT> ResultTypes,
5443                                  bool IsTexFail, bool Unpacked, bool IsD16,
5444                                  int DMaskPop, int NumVDataDwords,
5445                                  const SDLoc &DL, LLVMContext &Context) {
5446   // Determine the required return type. This is the same regardless of IsTexFail flag
5447   EVT ReqRetVT = ResultTypes[0];
5448   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5449   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5450     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5451 
5452   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5453     DMaskPop : (DMaskPop + 1) / 2;
5454 
5455   MVT DataDwordVT = NumDataDwords == 1 ?
5456     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5457 
5458   MVT MaskPopVT = MaskPopDwords == 1 ?
5459     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5460 
5461   SDValue Data(Result, 0);
5462   SDValue TexFail;
5463 
5464   if (IsTexFail) {
5465     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5466     if (MaskPopVT.isVector()) {
5467       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5468                          SDValue(Result, 0), ZeroIdx);
5469     } else {
5470       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5471                          SDValue(Result, 0), ZeroIdx);
5472     }
5473 
5474     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5475                           SDValue(Result, 0),
5476                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5477   }
5478 
5479   if (DataDwordVT.isVector())
5480     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5481                           NumDataDwords - MaskPopDwords);
5482 
5483   if (IsD16)
5484     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5485 
5486   if (!ReqRetVT.isVector())
5487     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5488 
5489   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5490 
5491   if (TexFail)
5492     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5493 
5494   if (Result->getNumValues() == 1)
5495     return Data;
5496 
5497   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5498 }
5499 
5500 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5501                          SDValue *LWE, bool &IsTexFail) {
5502   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5503 
5504   uint64_t Value = TexFailCtrlConst->getZExtValue();
5505   if (Value) {
5506     IsTexFail = true;
5507   }
5508 
5509   SDLoc DL(TexFailCtrlConst);
5510   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5511   Value &= ~(uint64_t)0x1;
5512   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5513   Value &= ~(uint64_t)0x2;
5514 
5515   return Value == 0;
5516 }
5517 
5518 SDValue SITargetLowering::lowerImage(SDValue Op,
5519                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5520                                      SelectionDAG &DAG) const {
5521   SDLoc DL(Op);
5522   MachineFunction &MF = DAG.getMachineFunction();
5523   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5524   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5525       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5526   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5527   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5528       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5529   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5530       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5531   unsigned IntrOpcode = Intr->BaseOpcode;
5532   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5533 
5534   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5535   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5536   bool IsD16 = false;
5537   bool IsA16 = false;
5538   SDValue VData;
5539   int NumVDataDwords;
5540   bool AdjustRetType = false;
5541 
5542   unsigned AddrIdx; // Index of first address argument
5543   unsigned DMask;
5544   unsigned DMaskLanes = 0;
5545 
5546   if (BaseOpcode->Atomic) {
5547     VData = Op.getOperand(2);
5548 
5549     bool Is64Bit = VData.getValueType() == MVT::i64;
5550     if (BaseOpcode->AtomicX2) {
5551       SDValue VData2 = Op.getOperand(3);
5552       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5553                                  {VData, VData2});
5554       if (Is64Bit)
5555         VData = DAG.getBitcast(MVT::v4i32, VData);
5556 
5557       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5558       DMask = Is64Bit ? 0xf : 0x3;
5559       NumVDataDwords = Is64Bit ? 4 : 2;
5560       AddrIdx = 4;
5561     } else {
5562       DMask = Is64Bit ? 0x3 : 0x1;
5563       NumVDataDwords = Is64Bit ? 2 : 1;
5564       AddrIdx = 3;
5565     }
5566   } else {
5567     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5568     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5569     DMask = DMaskConst->getZExtValue();
5570     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5571 
5572     if (BaseOpcode->Store) {
5573       VData = Op.getOperand(2);
5574 
5575       MVT StoreVT = VData.getSimpleValueType();
5576       if (StoreVT.getScalarType() == MVT::f16) {
5577         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5578           return Op; // D16 is unsupported for this instruction
5579 
5580         IsD16 = true;
5581         VData = handleD16VData(VData, DAG);
5582       }
5583 
5584       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5585     } else {
5586       // Work out the num dwords based on the dmask popcount and underlying type
5587       // and whether packing is supported.
5588       MVT LoadVT = ResultTypes[0].getSimpleVT();
5589       if (LoadVT.getScalarType() == MVT::f16) {
5590         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5591           return Op; // D16 is unsupported for this instruction
5592 
5593         IsD16 = true;
5594       }
5595 
5596       // Confirm that the return type is large enough for the dmask specified
5597       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5598           (!LoadVT.isVector() && DMaskLanes > 1))
5599           return Op;
5600 
5601       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5602         NumVDataDwords = (DMaskLanes + 1) / 2;
5603       else
5604         NumVDataDwords = DMaskLanes;
5605 
5606       AdjustRetType = true;
5607     }
5608 
5609     AddrIdx = DMaskIdx + 1;
5610   }
5611 
5612   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5613   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5614   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5615   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5616                        NumCoords + NumLCM;
5617   unsigned NumMIVAddrs = NumVAddrs;
5618 
5619   SmallVector<SDValue, 4> VAddrs;
5620 
5621   // Optimize _L to _LZ when _L is zero
5622   if (LZMappingInfo) {
5623     if (auto ConstantLod =
5624          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5625       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5626         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5627         NumMIVAddrs--;               // remove 'lod'
5628       }
5629     }
5630   }
5631 
5632   // Optimize _mip away, when 'lod' is zero
5633   if (MIPMappingInfo) {
5634     if (auto ConstantLod =
5635          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5636       if (ConstantLod->isNullValue()) {
5637         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5638         NumMIVAddrs--;               // remove 'lod'
5639       }
5640     }
5641   }
5642 
5643   // Check for 16 bit addresses and pack if true.
5644   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5645   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5646   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5647   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5648     // Illegal to use a16 images
5649     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5650       return Op;
5651 
5652     IsA16 = true;
5653     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5654     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5655       SDValue AddrLo;
5656       // Push back extra arguments.
5657       if (i < DimIdx) {
5658         AddrLo = Op.getOperand(i);
5659       } else {
5660         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5661         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5662         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5663             ((NumGradients / 2) % 2 == 1 &&
5664             (i == DimIdx + (NumGradients / 2) - 1 ||
5665              i == DimIdx + NumGradients - 1))) {
5666           AddrLo = Op.getOperand(i);
5667           if (AddrLo.getValueType() != MVT::i16)
5668             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5669           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5670         } else {
5671           AddrLo = DAG.getBuildVector(VectorVT, DL,
5672                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5673           i++;
5674         }
5675         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5676       }
5677       VAddrs.push_back(AddrLo);
5678     }
5679   } else {
5680     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5681       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5682   }
5683 
5684   // If the register allocator cannot place the address registers contiguously
5685   // without introducing moves, then using the non-sequential address encoding
5686   // is always preferable, since it saves VALU instructions and is usually a
5687   // wash in terms of code size or even better.
5688   //
5689   // However, we currently have no way of hinting to the register allocator that
5690   // MIMG addresses should be placed contiguously when it is possible to do so,
5691   // so force non-NSA for the common 2-address case as a heuristic.
5692   //
5693   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5694   // allocation when possible.
5695   bool UseNSA =
5696       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5697   SDValue VAddr;
5698   if (!UseNSA)
5699     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5700 
5701   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5702   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5703   unsigned CtrlIdx; // Index of texfailctrl argument
5704   SDValue Unorm;
5705   if (!BaseOpcode->Sampler) {
5706     Unorm = True;
5707     CtrlIdx = AddrIdx + NumVAddrs + 1;
5708   } else {
5709     auto UnormConst =
5710         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5711 
5712     Unorm = UnormConst->getZExtValue() ? True : False;
5713     CtrlIdx = AddrIdx + NumVAddrs + 3;
5714   }
5715 
5716   SDValue TFE;
5717   SDValue LWE;
5718   SDValue TexFail = Op.getOperand(CtrlIdx);
5719   bool IsTexFail = false;
5720   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5721     return Op;
5722 
5723   if (IsTexFail) {
5724     if (!DMaskLanes) {
5725       // Expecting to get an error flag since TFC is on - and dmask is 0
5726       // Force dmask to be at least 1 otherwise the instruction will fail
5727       DMask = 0x1;
5728       DMaskLanes = 1;
5729       NumVDataDwords = 1;
5730     }
5731     NumVDataDwords += 1;
5732     AdjustRetType = true;
5733   }
5734 
5735   // Has something earlier tagged that the return type needs adjusting
5736   // This happens if the instruction is a load or has set TexFailCtrl flags
5737   if (AdjustRetType) {
5738     // NumVDataDwords reflects the true number of dwords required in the return type
5739     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5740       // This is a no-op load. This can be eliminated
5741       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5742       if (isa<MemSDNode>(Op))
5743         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5744       return Undef;
5745     }
5746 
5747     EVT NewVT = NumVDataDwords > 1 ?
5748                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5749                 : MVT::i32;
5750 
5751     ResultTypes[0] = NewVT;
5752     if (ResultTypes.size() == 3) {
5753       // Original result was aggregate type used for TexFailCtrl results
5754       // The actual instruction returns as a vector type which has now been
5755       // created. Remove the aggregate result.
5756       ResultTypes.erase(&ResultTypes[1]);
5757     }
5758   }
5759 
5760   SDValue GLC;
5761   SDValue SLC;
5762   SDValue DLC;
5763   if (BaseOpcode->Atomic) {
5764     GLC = True; // TODO no-return optimization
5765     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5766                           IsGFX10 ? &DLC : nullptr))
5767       return Op;
5768   } else {
5769     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5770                           IsGFX10 ? &DLC : nullptr))
5771       return Op;
5772   }
5773 
5774   SmallVector<SDValue, 26> Ops;
5775   if (BaseOpcode->Store || BaseOpcode->Atomic)
5776     Ops.push_back(VData); // vdata
5777   if (UseNSA) {
5778     for (const SDValue &Addr : VAddrs)
5779       Ops.push_back(Addr);
5780   } else {
5781     Ops.push_back(VAddr);
5782   }
5783   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5784   if (BaseOpcode->Sampler)
5785     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5786   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5787   if (IsGFX10)
5788     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5789   Ops.push_back(Unorm);
5790   if (IsGFX10)
5791     Ops.push_back(DLC);
5792   Ops.push_back(GLC);
5793   Ops.push_back(SLC);
5794   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5795                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5796   if (IsGFX10)
5797     Ops.push_back(IsA16 ? True : False);
5798   Ops.push_back(TFE);
5799   Ops.push_back(LWE);
5800   if (!IsGFX10)
5801     Ops.push_back(DimInfo->DA ? True : False);
5802   if (BaseOpcode->HasD16)
5803     Ops.push_back(IsD16 ? True : False);
5804   if (isa<MemSDNode>(Op))
5805     Ops.push_back(Op.getOperand(0)); // chain
5806 
5807   int NumVAddrDwords =
5808       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5809   int Opcode = -1;
5810 
5811   if (IsGFX10) {
5812     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5813                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5814                                           : AMDGPU::MIMGEncGfx10Default,
5815                                    NumVDataDwords, NumVAddrDwords);
5816   } else {
5817     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5818       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5819                                      NumVDataDwords, NumVAddrDwords);
5820     if (Opcode == -1)
5821       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5822                                      NumVDataDwords, NumVAddrDwords);
5823   }
5824   assert(Opcode != -1);
5825 
5826   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5827   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5828     MachineMemOperand *MemRef = MemOp->getMemOperand();
5829     DAG.setNodeMemRefs(NewNode, {MemRef});
5830   }
5831 
5832   if (BaseOpcode->AtomicX2) {
5833     SmallVector<SDValue, 1> Elt;
5834     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5835     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5836   } else if (!BaseOpcode->Store) {
5837     return constructRetValue(DAG, NewNode,
5838                              OrigResultTypes, IsTexFail,
5839                              Subtarget->hasUnpackedD16VMem(), IsD16,
5840                              DMaskLanes, NumVDataDwords, DL,
5841                              *DAG.getContext());
5842   }
5843 
5844   return SDValue(NewNode, 0);
5845 }
5846 
5847 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5848                                        SDValue Offset, SDValue CachePolicy,
5849                                        SelectionDAG &DAG) const {
5850   MachineFunction &MF = DAG.getMachineFunction();
5851 
5852   const DataLayout &DataLayout = DAG.getDataLayout();
5853   Align Alignment =
5854       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
5855 
5856   MachineMemOperand *MMO = MF.getMachineMemOperand(
5857       MachinePointerInfo(),
5858       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5859           MachineMemOperand::MOInvariant,
5860       VT.getStoreSize(), Alignment);
5861 
5862   if (!Offset->isDivergent()) {
5863     SDValue Ops[] = {
5864         Rsrc,
5865         Offset, // Offset
5866         CachePolicy
5867     };
5868 
5869     // Widen vec3 load to vec4.
5870     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5871       EVT WidenedVT =
5872           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5873       auto WidenedOp = DAG.getMemIntrinsicNode(
5874           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5875           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5876       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5877                                    DAG.getVectorIdxConstant(0, DL));
5878       return Subvector;
5879     }
5880 
5881     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5882                                    DAG.getVTList(VT), Ops, VT, MMO);
5883   }
5884 
5885   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5886   // assume that the buffer is unswizzled.
5887   SmallVector<SDValue, 4> Loads;
5888   unsigned NumLoads = 1;
5889   MVT LoadVT = VT.getSimpleVT();
5890   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5891   assert((LoadVT.getScalarType() == MVT::i32 ||
5892           LoadVT.getScalarType() == MVT::f32));
5893 
5894   if (NumElts == 8 || NumElts == 16) {
5895     NumLoads = NumElts / 4;
5896     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5897   }
5898 
5899   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5900   SDValue Ops[] = {
5901       DAG.getEntryNode(),                               // Chain
5902       Rsrc,                                             // rsrc
5903       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5904       {},                                               // voffset
5905       {},                                               // soffset
5906       {},                                               // offset
5907       CachePolicy,                                      // cachepolicy
5908       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5909   };
5910 
5911   // Use the alignment to ensure that the required offsets will fit into the
5912   // immediate offsets.
5913   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5914 
5915   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5916   for (unsigned i = 0; i < NumLoads; ++i) {
5917     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5918     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5919                                         LoadVT, MMO, DAG));
5920   }
5921 
5922   if (NumElts == 8 || NumElts == 16)
5923     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5924 
5925   return Loads[0];
5926 }
5927 
5928 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5929                                                   SelectionDAG &DAG) const {
5930   MachineFunction &MF = DAG.getMachineFunction();
5931   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5932 
5933   EVT VT = Op.getValueType();
5934   SDLoc DL(Op);
5935   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5936 
5937   // TODO: Should this propagate fast-math-flags?
5938 
5939   switch (IntrinsicID) {
5940   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5941     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5942       return emitNonHSAIntrinsicError(DAG, DL, VT);
5943     return getPreloadedValue(DAG, *MFI, VT,
5944                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5945   }
5946   case Intrinsic::amdgcn_dispatch_ptr:
5947   case Intrinsic::amdgcn_queue_ptr: {
5948     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5949       DiagnosticInfoUnsupported BadIntrin(
5950           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5951           DL.getDebugLoc());
5952       DAG.getContext()->diagnose(BadIntrin);
5953       return DAG.getUNDEF(VT);
5954     }
5955 
5956     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5957       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5958     return getPreloadedValue(DAG, *MFI, VT, RegID);
5959   }
5960   case Intrinsic::amdgcn_implicitarg_ptr: {
5961     if (MFI->isEntryFunction())
5962       return getImplicitArgPtr(DAG, DL);
5963     return getPreloadedValue(DAG, *MFI, VT,
5964                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5965   }
5966   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5967     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
5968       // This only makes sense to call in a kernel, so just lower to null.
5969       return DAG.getConstant(0, DL, VT);
5970     }
5971 
5972     return getPreloadedValue(DAG, *MFI, VT,
5973                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5974   }
5975   case Intrinsic::amdgcn_dispatch_id: {
5976     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5977   }
5978   case Intrinsic::amdgcn_rcp:
5979     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5980   case Intrinsic::amdgcn_rsq:
5981     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5982   case Intrinsic::amdgcn_rsq_legacy:
5983     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5984       return emitRemovedIntrinsicError(DAG, DL, VT);
5985     return SDValue();
5986   case Intrinsic::amdgcn_rcp_legacy:
5987     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5988       return emitRemovedIntrinsicError(DAG, DL, VT);
5989     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5990   case Intrinsic::amdgcn_rsq_clamp: {
5991     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5992       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5993 
5994     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5995     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5996     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5997 
5998     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5999     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6000                               DAG.getConstantFP(Max, DL, VT));
6001     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6002                        DAG.getConstantFP(Min, DL, VT));
6003   }
6004   case Intrinsic::r600_read_ngroups_x:
6005     if (Subtarget->isAmdHsaOS())
6006       return emitNonHSAIntrinsicError(DAG, DL, VT);
6007 
6008     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6009                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6010   case Intrinsic::r600_read_ngroups_y:
6011     if (Subtarget->isAmdHsaOS())
6012       return emitNonHSAIntrinsicError(DAG, DL, VT);
6013 
6014     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6015                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6016   case Intrinsic::r600_read_ngroups_z:
6017     if (Subtarget->isAmdHsaOS())
6018       return emitNonHSAIntrinsicError(DAG, DL, VT);
6019 
6020     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6021                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6022   case Intrinsic::r600_read_global_size_x:
6023     if (Subtarget->isAmdHsaOS())
6024       return emitNonHSAIntrinsicError(DAG, DL, VT);
6025 
6026     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6027                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6028   case Intrinsic::r600_read_global_size_y:
6029     if (Subtarget->isAmdHsaOS())
6030       return emitNonHSAIntrinsicError(DAG, DL, VT);
6031 
6032     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6033                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6034   case Intrinsic::r600_read_global_size_z:
6035     if (Subtarget->isAmdHsaOS())
6036       return emitNonHSAIntrinsicError(DAG, DL, VT);
6037 
6038     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6039                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6040   case Intrinsic::r600_read_local_size_x:
6041     if (Subtarget->isAmdHsaOS())
6042       return emitNonHSAIntrinsicError(DAG, DL, VT);
6043 
6044     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6045                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6046   case Intrinsic::r600_read_local_size_y:
6047     if (Subtarget->isAmdHsaOS())
6048       return emitNonHSAIntrinsicError(DAG, DL, VT);
6049 
6050     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6051                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6052   case Intrinsic::r600_read_local_size_z:
6053     if (Subtarget->isAmdHsaOS())
6054       return emitNonHSAIntrinsicError(DAG, DL, VT);
6055 
6056     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6057                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6058   case Intrinsic::amdgcn_workgroup_id_x:
6059     return getPreloadedValue(DAG, *MFI, VT,
6060                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6061   case Intrinsic::amdgcn_workgroup_id_y:
6062     return getPreloadedValue(DAG, *MFI, VT,
6063                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6064   case Intrinsic::amdgcn_workgroup_id_z:
6065     return getPreloadedValue(DAG, *MFI, VT,
6066                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6067   case Intrinsic::amdgcn_workitem_id_x:
6068     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6069                           SDLoc(DAG.getEntryNode()),
6070                           MFI->getArgInfo().WorkItemIDX);
6071   case Intrinsic::amdgcn_workitem_id_y:
6072     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6073                           SDLoc(DAG.getEntryNode()),
6074                           MFI->getArgInfo().WorkItemIDY);
6075   case Intrinsic::amdgcn_workitem_id_z:
6076     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6077                           SDLoc(DAG.getEntryNode()),
6078                           MFI->getArgInfo().WorkItemIDZ);
6079   case Intrinsic::amdgcn_wavefrontsize:
6080     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6081                            SDLoc(Op), MVT::i32);
6082   case Intrinsic::amdgcn_s_buffer_load: {
6083     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6084     SDValue GLC;
6085     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6086     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6087                           IsGFX10 ? &DLC : nullptr))
6088       return Op;
6089     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6090                         DAG);
6091   }
6092   case Intrinsic::amdgcn_fdiv_fast:
6093     return lowerFDIV_FAST(Op, DAG);
6094   case Intrinsic::amdgcn_sin:
6095     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6096 
6097   case Intrinsic::amdgcn_cos:
6098     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6099 
6100   case Intrinsic::amdgcn_mul_u24:
6101     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6102   case Intrinsic::amdgcn_mul_i24:
6103     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6104 
6105   case Intrinsic::amdgcn_log_clamp: {
6106     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6107       return SDValue();
6108 
6109     DiagnosticInfoUnsupported BadIntrin(
6110       MF.getFunction(), "intrinsic not supported on subtarget",
6111       DL.getDebugLoc());
6112       DAG.getContext()->diagnose(BadIntrin);
6113       return DAG.getUNDEF(VT);
6114   }
6115   case Intrinsic::amdgcn_ldexp:
6116     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6117                        Op.getOperand(1), Op.getOperand(2));
6118 
6119   case Intrinsic::amdgcn_fract:
6120     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6121 
6122   case Intrinsic::amdgcn_class:
6123     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6124                        Op.getOperand(1), Op.getOperand(2));
6125   case Intrinsic::amdgcn_div_fmas:
6126     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6127                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6128                        Op.getOperand(4));
6129 
6130   case Intrinsic::amdgcn_div_fixup:
6131     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6132                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6133 
6134   case Intrinsic::amdgcn_trig_preop:
6135     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
6136                        Op.getOperand(1), Op.getOperand(2));
6137   case Intrinsic::amdgcn_div_scale: {
6138     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6139 
6140     // Translate to the operands expected by the machine instruction. The
6141     // first parameter must be the same as the first instruction.
6142     SDValue Numerator = Op.getOperand(1);
6143     SDValue Denominator = Op.getOperand(2);
6144 
6145     // Note this order is opposite of the machine instruction's operations,
6146     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6147     // intrinsic has the numerator as the first operand to match a normal
6148     // division operation.
6149 
6150     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6151 
6152     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6153                        Denominator, Numerator);
6154   }
6155   case Intrinsic::amdgcn_icmp: {
6156     // There is a Pat that handles this variant, so return it as-is.
6157     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6158         Op.getConstantOperandVal(2) == 0 &&
6159         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6160       return Op;
6161     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6162   }
6163   case Intrinsic::amdgcn_fcmp: {
6164     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6165   }
6166   case Intrinsic::amdgcn_ballot:
6167     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6168   case Intrinsic::amdgcn_fmed3:
6169     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6170                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6171   case Intrinsic::amdgcn_fdot2:
6172     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6173                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6174                        Op.getOperand(4));
6175   case Intrinsic::amdgcn_fmul_legacy:
6176     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6177                        Op.getOperand(1), Op.getOperand(2));
6178   case Intrinsic::amdgcn_sffbh:
6179     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6180   case Intrinsic::amdgcn_sbfe:
6181     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6182                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6183   case Intrinsic::amdgcn_ubfe:
6184     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6185                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6186   case Intrinsic::amdgcn_cvt_pkrtz:
6187   case Intrinsic::amdgcn_cvt_pknorm_i16:
6188   case Intrinsic::amdgcn_cvt_pknorm_u16:
6189   case Intrinsic::amdgcn_cvt_pk_i16:
6190   case Intrinsic::amdgcn_cvt_pk_u16: {
6191     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6192     EVT VT = Op.getValueType();
6193     unsigned Opcode;
6194 
6195     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6196       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6197     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6198       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6199     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6200       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6201     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6202       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6203     else
6204       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6205 
6206     if (isTypeLegal(VT))
6207       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6208 
6209     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6210                                Op.getOperand(1), Op.getOperand(2));
6211     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6212   }
6213   case Intrinsic::amdgcn_fmad_ftz:
6214     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6215                        Op.getOperand(2), Op.getOperand(3));
6216 
6217   case Intrinsic::amdgcn_if_break:
6218     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6219                                       Op->getOperand(1), Op->getOperand(2)), 0);
6220 
6221   case Intrinsic::amdgcn_groupstaticsize: {
6222     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6223     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6224       return Op;
6225 
6226     const Module *M = MF.getFunction().getParent();
6227     const GlobalValue *GV =
6228         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6229     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6230                                             SIInstrInfo::MO_ABS32_LO);
6231     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6232   }
6233   case Intrinsic::amdgcn_is_shared:
6234   case Intrinsic::amdgcn_is_private: {
6235     SDLoc SL(Op);
6236     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6237       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6238     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6239     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6240                                  Op.getOperand(1));
6241 
6242     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6243                                 DAG.getConstant(1, SL, MVT::i32));
6244     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6245   }
6246   case Intrinsic::amdgcn_alignbit:
6247     return DAG.getNode(ISD::FSHR, DL, VT,
6248                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6249   case Intrinsic::amdgcn_reloc_constant: {
6250     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6251     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6252     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6253     auto RelocSymbol = cast<GlobalVariable>(
6254         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6255     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6256                                             SIInstrInfo::MO_ABS32_LO);
6257     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6258   }
6259   default:
6260     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6261             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6262       return lowerImage(Op, ImageDimIntr, DAG);
6263 
6264     return Op;
6265   }
6266 }
6267 
6268 // This function computes an appropriate offset to pass to
6269 // MachineMemOperand::setOffset() based on the offset inputs to
6270 // an intrinsic.  If any of the offsets are non-contstant or
6271 // if VIndex is non-zero then this function returns 0.  Otherwise,
6272 // it returns the sum of VOffset, SOffset, and Offset.
6273 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6274                                       SDValue SOffset,
6275                                       SDValue Offset,
6276                                       SDValue VIndex = SDValue()) {
6277 
6278   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6279       !isa<ConstantSDNode>(Offset))
6280     return 0;
6281 
6282   if (VIndex) {
6283     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6284       return 0;
6285   }
6286 
6287   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6288          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6289          cast<ConstantSDNode>(Offset)->getSExtValue();
6290 }
6291 
6292 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6293   switch (MF.getFunction().getCallingConv()) {
6294   case CallingConv::AMDGPU_PS:
6295     return 1;
6296   case CallingConv::AMDGPU_VS:
6297     return 2;
6298   case CallingConv::AMDGPU_GS:
6299     return 3;
6300   case CallingConv::AMDGPU_HS:
6301   case CallingConv::AMDGPU_LS:
6302   case CallingConv::AMDGPU_ES:
6303     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6304   case CallingConv::AMDGPU_CS:
6305   case CallingConv::AMDGPU_KERNEL:
6306   case CallingConv::C:
6307   case CallingConv::Fast:
6308   default:
6309     // Assume other calling conventions are various compute callable functions
6310     return 0;
6311   }
6312 }
6313 
6314 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6315                                                  SelectionDAG &DAG) const {
6316   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6317   SDLoc DL(Op);
6318 
6319   switch (IntrID) {
6320   case Intrinsic::amdgcn_ds_ordered_add:
6321   case Intrinsic::amdgcn_ds_ordered_swap: {
6322     MemSDNode *M = cast<MemSDNode>(Op);
6323     SDValue Chain = M->getOperand(0);
6324     SDValue M0 = M->getOperand(2);
6325     SDValue Value = M->getOperand(3);
6326     unsigned IndexOperand = M->getConstantOperandVal(7);
6327     unsigned WaveRelease = M->getConstantOperandVal(8);
6328     unsigned WaveDone = M->getConstantOperandVal(9);
6329 
6330     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6331     IndexOperand &= ~0x3f;
6332     unsigned CountDw = 0;
6333 
6334     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6335       CountDw = (IndexOperand >> 24) & 0xf;
6336       IndexOperand &= ~(0xf << 24);
6337 
6338       if (CountDw < 1 || CountDw > 4) {
6339         report_fatal_error(
6340             "ds_ordered_count: dword count must be between 1 and 4");
6341       }
6342     }
6343 
6344     if (IndexOperand)
6345       report_fatal_error("ds_ordered_count: bad index operand");
6346 
6347     if (WaveDone && !WaveRelease)
6348       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6349 
6350     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6351     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6352     unsigned Offset0 = OrderedCountIndex << 2;
6353     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6354                        (Instruction << 4);
6355 
6356     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6357       Offset1 |= (CountDw - 1) << 6;
6358 
6359     unsigned Offset = Offset0 | (Offset1 << 8);
6360 
6361     SDValue Ops[] = {
6362       Chain,
6363       Value,
6364       DAG.getTargetConstant(Offset, DL, MVT::i16),
6365       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6366     };
6367     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6368                                    M->getVTList(), Ops, M->getMemoryVT(),
6369                                    M->getMemOperand());
6370   }
6371   case Intrinsic::amdgcn_ds_fadd: {
6372     MemSDNode *M = cast<MemSDNode>(Op);
6373     unsigned Opc;
6374     switch (IntrID) {
6375     case Intrinsic::amdgcn_ds_fadd:
6376       Opc = ISD::ATOMIC_LOAD_FADD;
6377       break;
6378     }
6379 
6380     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6381                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6382                          M->getMemOperand());
6383   }
6384   case Intrinsic::amdgcn_atomic_inc:
6385   case Intrinsic::amdgcn_atomic_dec:
6386   case Intrinsic::amdgcn_ds_fmin:
6387   case Intrinsic::amdgcn_ds_fmax: {
6388     MemSDNode *M = cast<MemSDNode>(Op);
6389     unsigned Opc;
6390     switch (IntrID) {
6391     case Intrinsic::amdgcn_atomic_inc:
6392       Opc = AMDGPUISD::ATOMIC_INC;
6393       break;
6394     case Intrinsic::amdgcn_atomic_dec:
6395       Opc = AMDGPUISD::ATOMIC_DEC;
6396       break;
6397     case Intrinsic::amdgcn_ds_fmin:
6398       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6399       break;
6400     case Intrinsic::amdgcn_ds_fmax:
6401       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6402       break;
6403     default:
6404       llvm_unreachable("Unknown intrinsic!");
6405     }
6406     SDValue Ops[] = {
6407       M->getOperand(0), // Chain
6408       M->getOperand(2), // Ptr
6409       M->getOperand(3)  // Value
6410     };
6411 
6412     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6413                                    M->getMemoryVT(), M->getMemOperand());
6414   }
6415   case Intrinsic::amdgcn_buffer_load:
6416   case Intrinsic::amdgcn_buffer_load_format: {
6417     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6418     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6419     unsigned IdxEn = 1;
6420     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6421       IdxEn = Idx->getZExtValue() != 0;
6422     SDValue Ops[] = {
6423       Op.getOperand(0), // Chain
6424       Op.getOperand(2), // rsrc
6425       Op.getOperand(3), // vindex
6426       SDValue(),        // voffset -- will be set by setBufferOffsets
6427       SDValue(),        // soffset -- will be set by setBufferOffsets
6428       SDValue(),        // offset -- will be set by setBufferOffsets
6429       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6430       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6431     };
6432 
6433     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6434     // We don't know the offset if vindex is non-zero, so clear it.
6435     if (IdxEn)
6436       Offset = 0;
6437 
6438     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6439         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6440 
6441     EVT VT = Op.getValueType();
6442     EVT IntVT = VT.changeTypeToInteger();
6443     auto *M = cast<MemSDNode>(Op);
6444     M->getMemOperand()->setOffset(Offset);
6445     EVT LoadVT = Op.getValueType();
6446 
6447     if (LoadVT.getScalarType() == MVT::f16)
6448       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6449                                  M, DAG, Ops);
6450 
6451     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6452     if (LoadVT.getScalarType() == MVT::i8 ||
6453         LoadVT.getScalarType() == MVT::i16)
6454       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6455 
6456     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6457                                M->getMemOperand(), DAG);
6458   }
6459   case Intrinsic::amdgcn_raw_buffer_load:
6460   case Intrinsic::amdgcn_raw_buffer_load_format: {
6461     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6462 
6463     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6464     SDValue Ops[] = {
6465       Op.getOperand(0), // Chain
6466       Op.getOperand(2), // rsrc
6467       DAG.getConstant(0, DL, MVT::i32), // vindex
6468       Offsets.first,    // voffset
6469       Op.getOperand(4), // soffset
6470       Offsets.second,   // offset
6471       Op.getOperand(5), // cachepolicy, swizzled buffer
6472       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6473     };
6474 
6475     auto *M = cast<MemSDNode>(Op);
6476     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6477     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6478   }
6479   case Intrinsic::amdgcn_struct_buffer_load:
6480   case Intrinsic::amdgcn_struct_buffer_load_format: {
6481     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6482 
6483     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6484     SDValue Ops[] = {
6485       Op.getOperand(0), // Chain
6486       Op.getOperand(2), // rsrc
6487       Op.getOperand(3), // vindex
6488       Offsets.first,    // voffset
6489       Op.getOperand(5), // soffset
6490       Offsets.second,   // offset
6491       Op.getOperand(6), // cachepolicy, swizzled buffer
6492       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6493     };
6494 
6495     auto *M = cast<MemSDNode>(Op);
6496     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6497                                                         Ops[2]));
6498     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6499   }
6500   case Intrinsic::amdgcn_tbuffer_load: {
6501     MemSDNode *M = cast<MemSDNode>(Op);
6502     EVT LoadVT = Op.getValueType();
6503 
6504     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6505     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6506     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6507     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6508     unsigned IdxEn = 1;
6509     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6510       IdxEn = Idx->getZExtValue() != 0;
6511     SDValue Ops[] = {
6512       Op.getOperand(0),  // Chain
6513       Op.getOperand(2),  // rsrc
6514       Op.getOperand(3),  // vindex
6515       Op.getOperand(4),  // voffset
6516       Op.getOperand(5),  // soffset
6517       Op.getOperand(6),  // offset
6518       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6519       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6520       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6521     };
6522 
6523     if (LoadVT.getScalarType() == MVT::f16)
6524       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6525                                  M, DAG, Ops);
6526     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6527                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6528                                DAG);
6529   }
6530   case Intrinsic::amdgcn_raw_tbuffer_load: {
6531     MemSDNode *M = cast<MemSDNode>(Op);
6532     EVT LoadVT = Op.getValueType();
6533     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6534 
6535     SDValue Ops[] = {
6536       Op.getOperand(0),  // Chain
6537       Op.getOperand(2),  // rsrc
6538       DAG.getConstant(0, DL, MVT::i32), // vindex
6539       Offsets.first,     // voffset
6540       Op.getOperand(4),  // soffset
6541       Offsets.second,    // offset
6542       Op.getOperand(5),  // format
6543       Op.getOperand(6),  // cachepolicy, swizzled buffer
6544       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6545     };
6546 
6547     if (LoadVT.getScalarType() == MVT::f16)
6548       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6549                                  M, DAG, Ops);
6550     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6551                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6552                                DAG);
6553   }
6554   case Intrinsic::amdgcn_struct_tbuffer_load: {
6555     MemSDNode *M = cast<MemSDNode>(Op);
6556     EVT LoadVT = Op.getValueType();
6557     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6558 
6559     SDValue Ops[] = {
6560       Op.getOperand(0),  // Chain
6561       Op.getOperand(2),  // rsrc
6562       Op.getOperand(3),  // vindex
6563       Offsets.first,     // voffset
6564       Op.getOperand(5),  // soffset
6565       Offsets.second,    // offset
6566       Op.getOperand(6),  // format
6567       Op.getOperand(7),  // cachepolicy, swizzled buffer
6568       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6569     };
6570 
6571     if (LoadVT.getScalarType() == MVT::f16)
6572       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6573                                  M, DAG, Ops);
6574     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6575                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6576                                DAG);
6577   }
6578   case Intrinsic::amdgcn_buffer_atomic_swap:
6579   case Intrinsic::amdgcn_buffer_atomic_add:
6580   case Intrinsic::amdgcn_buffer_atomic_sub:
6581   case Intrinsic::amdgcn_buffer_atomic_smin:
6582   case Intrinsic::amdgcn_buffer_atomic_umin:
6583   case Intrinsic::amdgcn_buffer_atomic_smax:
6584   case Intrinsic::amdgcn_buffer_atomic_umax:
6585   case Intrinsic::amdgcn_buffer_atomic_and:
6586   case Intrinsic::amdgcn_buffer_atomic_or:
6587   case Intrinsic::amdgcn_buffer_atomic_xor: {
6588     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6589     unsigned IdxEn = 1;
6590     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6591       IdxEn = Idx->getZExtValue() != 0;
6592     SDValue Ops[] = {
6593       Op.getOperand(0), // Chain
6594       Op.getOperand(2), // vdata
6595       Op.getOperand(3), // rsrc
6596       Op.getOperand(4), // vindex
6597       SDValue(),        // voffset -- will be set by setBufferOffsets
6598       SDValue(),        // soffset -- will be set by setBufferOffsets
6599       SDValue(),        // offset -- will be set by setBufferOffsets
6600       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6601       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6602     };
6603     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6604     // We don't know the offset if vindex is non-zero, so clear it.
6605     if (IdxEn)
6606       Offset = 0;
6607     EVT VT = Op.getValueType();
6608 
6609     auto *M = cast<MemSDNode>(Op);
6610     M->getMemOperand()->setOffset(Offset);
6611     unsigned Opcode = 0;
6612 
6613     switch (IntrID) {
6614     case Intrinsic::amdgcn_buffer_atomic_swap:
6615       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6616       break;
6617     case Intrinsic::amdgcn_buffer_atomic_add:
6618       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6619       break;
6620     case Intrinsic::amdgcn_buffer_atomic_sub:
6621       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6622       break;
6623     case Intrinsic::amdgcn_buffer_atomic_smin:
6624       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6625       break;
6626     case Intrinsic::amdgcn_buffer_atomic_umin:
6627       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6628       break;
6629     case Intrinsic::amdgcn_buffer_atomic_smax:
6630       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6631       break;
6632     case Intrinsic::amdgcn_buffer_atomic_umax:
6633       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6634       break;
6635     case Intrinsic::amdgcn_buffer_atomic_and:
6636       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6637       break;
6638     case Intrinsic::amdgcn_buffer_atomic_or:
6639       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6640       break;
6641     case Intrinsic::amdgcn_buffer_atomic_xor:
6642       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6643       break;
6644     default:
6645       llvm_unreachable("unhandled atomic opcode");
6646     }
6647 
6648     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6649                                    M->getMemOperand());
6650   }
6651   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6652   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6653   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6654   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6655   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6656   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6657   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6658   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6659   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6660   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6661   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6662   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6663     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6664     SDValue Ops[] = {
6665       Op.getOperand(0), // Chain
6666       Op.getOperand(2), // vdata
6667       Op.getOperand(3), // rsrc
6668       DAG.getConstant(0, DL, MVT::i32), // vindex
6669       Offsets.first,    // voffset
6670       Op.getOperand(5), // soffset
6671       Offsets.second,   // offset
6672       Op.getOperand(6), // cachepolicy
6673       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6674     };
6675     EVT VT = Op.getValueType();
6676 
6677     auto *M = cast<MemSDNode>(Op);
6678     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6679     unsigned Opcode = 0;
6680 
6681     switch (IntrID) {
6682     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6683       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6684       break;
6685     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6686       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6687       break;
6688     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6689       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6690       break;
6691     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6692       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6693       break;
6694     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6695       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6696       break;
6697     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6698       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6699       break;
6700     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6701       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6702       break;
6703     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6704       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6705       break;
6706     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6707       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6708       break;
6709     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6710       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6711       break;
6712     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6713       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6714       break;
6715     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6716       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6717       break;
6718     default:
6719       llvm_unreachable("unhandled atomic opcode");
6720     }
6721 
6722     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6723                                    M->getMemOperand());
6724   }
6725   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6726   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6727   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6728   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6729   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6730   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6731   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6732   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6733   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6734   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6735   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6736   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6737     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6738     SDValue Ops[] = {
6739       Op.getOperand(0), // Chain
6740       Op.getOperand(2), // vdata
6741       Op.getOperand(3), // rsrc
6742       Op.getOperand(4), // vindex
6743       Offsets.first,    // voffset
6744       Op.getOperand(6), // soffset
6745       Offsets.second,   // offset
6746       Op.getOperand(7), // cachepolicy
6747       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6748     };
6749     EVT VT = Op.getValueType();
6750 
6751     auto *M = cast<MemSDNode>(Op);
6752     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6753                                                         Ops[3]));
6754     unsigned Opcode = 0;
6755 
6756     switch (IntrID) {
6757     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6758       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6759       break;
6760     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6761       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6762       break;
6763     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6764       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6765       break;
6766     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6767       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6768       break;
6769     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6770       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6771       break;
6772     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6773       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6774       break;
6775     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6776       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6777       break;
6778     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6779       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6780       break;
6781     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6782       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6783       break;
6784     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6785       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6786       break;
6787     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6788       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6789       break;
6790     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6791       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6792       break;
6793     default:
6794       llvm_unreachable("unhandled atomic opcode");
6795     }
6796 
6797     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6798                                    M->getMemOperand());
6799   }
6800   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6801     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6802     unsigned IdxEn = 1;
6803     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6804       IdxEn = Idx->getZExtValue() != 0;
6805     SDValue Ops[] = {
6806       Op.getOperand(0), // Chain
6807       Op.getOperand(2), // src
6808       Op.getOperand(3), // cmp
6809       Op.getOperand(4), // rsrc
6810       Op.getOperand(5), // vindex
6811       SDValue(),        // voffset -- will be set by setBufferOffsets
6812       SDValue(),        // soffset -- will be set by setBufferOffsets
6813       SDValue(),        // offset -- will be set by setBufferOffsets
6814       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6815       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6816     };
6817     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6818     // We don't know the offset if vindex is non-zero, so clear it.
6819     if (IdxEn)
6820       Offset = 0;
6821     EVT VT = Op.getValueType();
6822     auto *M = cast<MemSDNode>(Op);
6823     M->getMemOperand()->setOffset(Offset);
6824 
6825     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6826                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6827   }
6828   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6829     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6830     SDValue Ops[] = {
6831       Op.getOperand(0), // Chain
6832       Op.getOperand(2), // src
6833       Op.getOperand(3), // cmp
6834       Op.getOperand(4), // rsrc
6835       DAG.getConstant(0, DL, MVT::i32), // vindex
6836       Offsets.first,    // voffset
6837       Op.getOperand(6), // soffset
6838       Offsets.second,   // offset
6839       Op.getOperand(7), // cachepolicy
6840       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6841     };
6842     EVT VT = Op.getValueType();
6843     auto *M = cast<MemSDNode>(Op);
6844     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6845 
6846     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6847                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6848   }
6849   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6850     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6851     SDValue Ops[] = {
6852       Op.getOperand(0), // Chain
6853       Op.getOperand(2), // src
6854       Op.getOperand(3), // cmp
6855       Op.getOperand(4), // rsrc
6856       Op.getOperand(5), // vindex
6857       Offsets.first,    // voffset
6858       Op.getOperand(7), // soffset
6859       Offsets.second,   // offset
6860       Op.getOperand(8), // cachepolicy
6861       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6862     };
6863     EVT VT = Op.getValueType();
6864     auto *M = cast<MemSDNode>(Op);
6865     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6866                                                         Ops[4]));
6867 
6868     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6869                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6870   }
6871 
6872   default:
6873     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6874             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6875       return lowerImage(Op, ImageDimIntr, DAG);
6876 
6877     return SDValue();
6878   }
6879 }
6880 
6881 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6882 // dwordx4 if on SI.
6883 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6884                                               SDVTList VTList,
6885                                               ArrayRef<SDValue> Ops, EVT MemVT,
6886                                               MachineMemOperand *MMO,
6887                                               SelectionDAG &DAG) const {
6888   EVT VT = VTList.VTs[0];
6889   EVT WidenedVT = VT;
6890   EVT WidenedMemVT = MemVT;
6891   if (!Subtarget->hasDwordx3LoadStores() &&
6892       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6893     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6894                                  WidenedVT.getVectorElementType(), 4);
6895     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6896                                     WidenedMemVT.getVectorElementType(), 4);
6897     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6898   }
6899 
6900   assert(VTList.NumVTs == 2);
6901   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6902 
6903   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6904                                        WidenedMemVT, MMO);
6905   if (WidenedVT != VT) {
6906     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6907                                DAG.getVectorIdxConstant(0, DL));
6908     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6909   }
6910   return NewOp;
6911 }
6912 
6913 SDValue SITargetLowering::handleD16VData(SDValue VData,
6914                                          SelectionDAG &DAG) const {
6915   EVT StoreVT = VData.getValueType();
6916 
6917   // No change for f16 and legal vector D16 types.
6918   if (!StoreVT.isVector())
6919     return VData;
6920 
6921   SDLoc DL(VData);
6922   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6923 
6924   if (Subtarget->hasUnpackedD16VMem()) {
6925     // We need to unpack the packed data to store.
6926     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6927     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6928 
6929     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6930                                         StoreVT.getVectorNumElements());
6931     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6932     return DAG.UnrollVectorOp(ZExt.getNode());
6933   }
6934 
6935   assert(isTypeLegal(StoreVT));
6936   return VData;
6937 }
6938 
6939 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6940                                               SelectionDAG &DAG) const {
6941   SDLoc DL(Op);
6942   SDValue Chain = Op.getOperand(0);
6943   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6944   MachineFunction &MF = DAG.getMachineFunction();
6945 
6946   switch (IntrinsicID) {
6947   case Intrinsic::amdgcn_exp_compr: {
6948     SDValue Src0 = Op.getOperand(4);
6949     SDValue Src1 = Op.getOperand(5);
6950     // Hack around illegal type on SI by directly selecting it.
6951     if (isTypeLegal(Src0.getValueType()))
6952       return SDValue();
6953 
6954     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6955     SDValue Undef = DAG.getUNDEF(MVT::f32);
6956     const SDValue Ops[] = {
6957       Op.getOperand(2), // tgt
6958       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
6959       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
6960       Undef, // src2
6961       Undef, // src3
6962       Op.getOperand(7), // vm
6963       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6964       Op.getOperand(3), // en
6965       Op.getOperand(0) // Chain
6966     };
6967 
6968     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
6969     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
6970   }
6971   case Intrinsic::amdgcn_s_barrier: {
6972     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6973       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6974       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6975       if (WGSize <= ST.getWavefrontSize())
6976         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6977                                           Op.getOperand(0)), 0);
6978     }
6979     return SDValue();
6980   };
6981   case Intrinsic::amdgcn_tbuffer_store: {
6982     SDValue VData = Op.getOperand(2);
6983     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6984     if (IsD16)
6985       VData = handleD16VData(VData, DAG);
6986     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6987     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6988     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6989     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6990     unsigned IdxEn = 1;
6991     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6992       IdxEn = Idx->getZExtValue() != 0;
6993     SDValue Ops[] = {
6994       Chain,
6995       VData,             // vdata
6996       Op.getOperand(3),  // rsrc
6997       Op.getOperand(4),  // vindex
6998       Op.getOperand(5),  // voffset
6999       Op.getOperand(6),  // soffset
7000       Op.getOperand(7),  // offset
7001       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7002       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7003       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7004     };
7005     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7006                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7007     MemSDNode *M = cast<MemSDNode>(Op);
7008     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7009                                    M->getMemoryVT(), M->getMemOperand());
7010   }
7011 
7012   case Intrinsic::amdgcn_struct_tbuffer_store: {
7013     SDValue VData = Op.getOperand(2);
7014     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7015     if (IsD16)
7016       VData = handleD16VData(VData, DAG);
7017     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7018     SDValue Ops[] = {
7019       Chain,
7020       VData,             // vdata
7021       Op.getOperand(3),  // rsrc
7022       Op.getOperand(4),  // vindex
7023       Offsets.first,     // voffset
7024       Op.getOperand(6),  // soffset
7025       Offsets.second,    // offset
7026       Op.getOperand(7),  // format
7027       Op.getOperand(8),  // cachepolicy, swizzled buffer
7028       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7029     };
7030     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7031                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7032     MemSDNode *M = cast<MemSDNode>(Op);
7033     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7034                                    M->getMemoryVT(), M->getMemOperand());
7035   }
7036 
7037   case Intrinsic::amdgcn_raw_tbuffer_store: {
7038     SDValue VData = Op.getOperand(2);
7039     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7040     if (IsD16)
7041       VData = handleD16VData(VData, DAG);
7042     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7043     SDValue Ops[] = {
7044       Chain,
7045       VData,             // vdata
7046       Op.getOperand(3),  // rsrc
7047       DAG.getConstant(0, DL, MVT::i32), // vindex
7048       Offsets.first,     // voffset
7049       Op.getOperand(5),  // soffset
7050       Offsets.second,    // offset
7051       Op.getOperand(6),  // format
7052       Op.getOperand(7),  // cachepolicy, swizzled buffer
7053       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7054     };
7055     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7056                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7057     MemSDNode *M = cast<MemSDNode>(Op);
7058     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7059                                    M->getMemoryVT(), M->getMemOperand());
7060   }
7061 
7062   case Intrinsic::amdgcn_buffer_store:
7063   case Intrinsic::amdgcn_buffer_store_format: {
7064     SDValue VData = Op.getOperand(2);
7065     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7066     if (IsD16)
7067       VData = handleD16VData(VData, DAG);
7068     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7069     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7070     unsigned IdxEn = 1;
7071     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7072       IdxEn = Idx->getZExtValue() != 0;
7073     SDValue Ops[] = {
7074       Chain,
7075       VData,
7076       Op.getOperand(3), // rsrc
7077       Op.getOperand(4), // vindex
7078       SDValue(), // voffset -- will be set by setBufferOffsets
7079       SDValue(), // soffset -- will be set by setBufferOffsets
7080       SDValue(), // offset -- will be set by setBufferOffsets
7081       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7082       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7083     };
7084     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7085     // We don't know the offset if vindex is non-zero, so clear it.
7086     if (IdxEn)
7087       Offset = 0;
7088     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7089                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7090     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7091     MemSDNode *M = cast<MemSDNode>(Op);
7092     M->getMemOperand()->setOffset(Offset);
7093 
7094     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7095     EVT VDataType = VData.getValueType().getScalarType();
7096     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7097       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7098 
7099     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7100                                    M->getMemoryVT(), M->getMemOperand());
7101   }
7102 
7103   case Intrinsic::amdgcn_raw_buffer_store:
7104   case Intrinsic::amdgcn_raw_buffer_store_format: {
7105     const bool IsFormat =
7106         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7107 
7108     SDValue VData = Op.getOperand(2);
7109     EVT VDataVT = VData.getValueType();
7110     EVT EltType = VDataVT.getScalarType();
7111     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7112     if (IsD16)
7113       VData = handleD16VData(VData, DAG);
7114 
7115     if (!isTypeLegal(VDataVT)) {
7116       VData =
7117           DAG.getNode(ISD::BITCAST, DL,
7118                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7119     }
7120 
7121     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7122     SDValue Ops[] = {
7123       Chain,
7124       VData,
7125       Op.getOperand(3), // rsrc
7126       DAG.getConstant(0, DL, MVT::i32), // vindex
7127       Offsets.first,    // voffset
7128       Op.getOperand(5), // soffset
7129       Offsets.second,   // offset
7130       Op.getOperand(6), // cachepolicy, swizzled buffer
7131       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7132     };
7133     unsigned Opc =
7134         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7135     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7136     MemSDNode *M = cast<MemSDNode>(Op);
7137     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7138 
7139     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7140     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7141       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7142 
7143     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7144                                    M->getMemoryVT(), M->getMemOperand());
7145   }
7146 
7147   case Intrinsic::amdgcn_struct_buffer_store:
7148   case Intrinsic::amdgcn_struct_buffer_store_format: {
7149     const bool IsFormat =
7150         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7151 
7152     SDValue VData = Op.getOperand(2);
7153     EVT VDataVT = VData.getValueType();
7154     EVT EltType = VDataVT.getScalarType();
7155     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7156 
7157     if (IsD16)
7158       VData = handleD16VData(VData, DAG);
7159 
7160     if (!isTypeLegal(VDataVT)) {
7161       VData =
7162           DAG.getNode(ISD::BITCAST, DL,
7163                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7164     }
7165 
7166     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7167     SDValue Ops[] = {
7168       Chain,
7169       VData,
7170       Op.getOperand(3), // rsrc
7171       Op.getOperand(4), // vindex
7172       Offsets.first,    // voffset
7173       Op.getOperand(6), // soffset
7174       Offsets.second,   // offset
7175       Op.getOperand(7), // cachepolicy, swizzled buffer
7176       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7177     };
7178     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7179                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7180     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7181     MemSDNode *M = cast<MemSDNode>(Op);
7182     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7183                                                         Ops[3]));
7184 
7185     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7186     EVT VDataType = VData.getValueType().getScalarType();
7187     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7188       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7189 
7190     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7191                                    M->getMemoryVT(), M->getMemOperand());
7192   }
7193 
7194   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7195     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7196     unsigned IdxEn = 1;
7197     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7198       IdxEn = Idx->getZExtValue() != 0;
7199     SDValue Ops[] = {
7200       Chain,
7201       Op.getOperand(2), // vdata
7202       Op.getOperand(3), // rsrc
7203       Op.getOperand(4), // vindex
7204       SDValue(),        // voffset -- will be set by setBufferOffsets
7205       SDValue(),        // soffset -- will be set by setBufferOffsets
7206       SDValue(),        // offset -- will be set by setBufferOffsets
7207       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7208       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7209     };
7210     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7211     // We don't know the offset if vindex is non-zero, so clear it.
7212     if (IdxEn)
7213       Offset = 0;
7214     EVT VT = Op.getOperand(2).getValueType();
7215 
7216     auto *M = cast<MemSDNode>(Op);
7217     M->getMemOperand()->setOffset(Offset);
7218     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7219                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7220 
7221     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7222                                    M->getMemOperand());
7223   }
7224 
7225   case Intrinsic::amdgcn_global_atomic_fadd: {
7226     SDValue Ops[] = {
7227       Chain,
7228       Op.getOperand(2), // ptr
7229       Op.getOperand(3)  // vdata
7230     };
7231     EVT VT = Op.getOperand(3).getValueType();
7232 
7233     auto *M = cast<MemSDNode>(Op);
7234     if (VT.isVector()) {
7235       return DAG.getMemIntrinsicNode(
7236         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7237         M->getMemOperand());
7238     }
7239 
7240     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7241                          DAG.getVTList(VT, MVT::Other), Ops,
7242                          M->getMemOperand()).getValue(1);
7243   }
7244   case Intrinsic::amdgcn_end_cf:
7245     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7246                                       Op->getOperand(2), Chain), 0);
7247 
7248   default: {
7249     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7250             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7251       return lowerImage(Op, ImageDimIntr, DAG);
7252 
7253     return Op;
7254   }
7255   }
7256 }
7257 
7258 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7259 // offset (the offset that is included in bounds checking and swizzling, to be
7260 // split between the instruction's voffset and immoffset fields) and soffset
7261 // (the offset that is excluded from bounds checking and swizzling, to go in
7262 // the instruction's soffset field).  This function takes the first kind of
7263 // offset and figures out how to split it between voffset and immoffset.
7264 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7265     SDValue Offset, SelectionDAG &DAG) const {
7266   SDLoc DL(Offset);
7267   const unsigned MaxImm = 4095;
7268   SDValue N0 = Offset;
7269   ConstantSDNode *C1 = nullptr;
7270 
7271   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7272     N0 = SDValue();
7273   else if (DAG.isBaseWithConstantOffset(N0)) {
7274     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7275     N0 = N0.getOperand(0);
7276   }
7277 
7278   if (C1) {
7279     unsigned ImmOffset = C1->getZExtValue();
7280     // If the immediate value is too big for the immoffset field, put the value
7281     // and -4096 into the immoffset field so that the value that is copied/added
7282     // for the voffset field is a multiple of 4096, and it stands more chance
7283     // of being CSEd with the copy/add for another similar load/store.
7284     // However, do not do that rounding down to a multiple of 4096 if that is a
7285     // negative number, as it appears to be illegal to have a negative offset
7286     // in the vgpr, even if adding the immediate offset makes it positive.
7287     unsigned Overflow = ImmOffset & ~MaxImm;
7288     ImmOffset -= Overflow;
7289     if ((int32_t)Overflow < 0) {
7290       Overflow += ImmOffset;
7291       ImmOffset = 0;
7292     }
7293     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7294     if (Overflow) {
7295       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7296       if (!N0)
7297         N0 = OverflowVal;
7298       else {
7299         SDValue Ops[] = { N0, OverflowVal };
7300         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7301       }
7302     }
7303   }
7304   if (!N0)
7305     N0 = DAG.getConstant(0, DL, MVT::i32);
7306   if (!C1)
7307     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7308   return {N0, SDValue(C1, 0)};
7309 }
7310 
7311 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7312 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7313 // pointed to by Offsets.
7314 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7315                                         SelectionDAG &DAG, SDValue *Offsets,
7316                                         unsigned Align) const {
7317   SDLoc DL(CombinedOffset);
7318   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7319     uint32_t Imm = C->getZExtValue();
7320     uint32_t SOffset, ImmOffset;
7321     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7322       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7323       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7324       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7325       return SOffset + ImmOffset;
7326     }
7327   }
7328   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7329     SDValue N0 = CombinedOffset.getOperand(0);
7330     SDValue N1 = CombinedOffset.getOperand(1);
7331     uint32_t SOffset, ImmOffset;
7332     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7333     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7334                                                 Subtarget, Align)) {
7335       Offsets[0] = N0;
7336       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7337       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7338       return 0;
7339     }
7340   }
7341   Offsets[0] = CombinedOffset;
7342   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7343   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7344   return 0;
7345 }
7346 
7347 // Handle 8 bit and 16 bit buffer loads
7348 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7349                                                      EVT LoadVT, SDLoc DL,
7350                                                      ArrayRef<SDValue> Ops,
7351                                                      MemSDNode *M) const {
7352   EVT IntVT = LoadVT.changeTypeToInteger();
7353   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7354          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7355 
7356   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7357   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7358                                                Ops, IntVT,
7359                                                M->getMemOperand());
7360   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7361   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7362 
7363   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7364 }
7365 
7366 // Handle 8 bit and 16 bit buffer stores
7367 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7368                                                       EVT VDataType, SDLoc DL,
7369                                                       SDValue Ops[],
7370                                                       MemSDNode *M) const {
7371   if (VDataType == MVT::f16)
7372     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7373 
7374   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7375   Ops[1] = BufferStoreExt;
7376   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7377                                  AMDGPUISD::BUFFER_STORE_SHORT;
7378   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7379   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7380                                      M->getMemOperand());
7381 }
7382 
7383 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7384                                  ISD::LoadExtType ExtType, SDValue Op,
7385                                  const SDLoc &SL, EVT VT) {
7386   if (VT.bitsLT(Op.getValueType()))
7387     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7388 
7389   switch (ExtType) {
7390   case ISD::SEXTLOAD:
7391     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7392   case ISD::ZEXTLOAD:
7393     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7394   case ISD::EXTLOAD:
7395     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7396   case ISD::NON_EXTLOAD:
7397     return Op;
7398   }
7399 
7400   llvm_unreachable("invalid ext type");
7401 }
7402 
7403 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7404   SelectionDAG &DAG = DCI.DAG;
7405   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7406     return SDValue();
7407 
7408   // FIXME: Constant loads should all be marked invariant.
7409   unsigned AS = Ld->getAddressSpace();
7410   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7411       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7412       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7413     return SDValue();
7414 
7415   // Don't do this early, since it may interfere with adjacent load merging for
7416   // illegal types. We can avoid losing alignment information for exotic types
7417   // pre-legalize.
7418   EVT MemVT = Ld->getMemoryVT();
7419   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7420       MemVT.getSizeInBits() >= 32)
7421     return SDValue();
7422 
7423   SDLoc SL(Ld);
7424 
7425   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7426          "unexpected vector extload");
7427 
7428   // TODO: Drop only high part of range.
7429   SDValue Ptr = Ld->getBasePtr();
7430   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7431                                 MVT::i32, SL, Ld->getChain(), Ptr,
7432                                 Ld->getOffset(),
7433                                 Ld->getPointerInfo(), MVT::i32,
7434                                 Ld->getAlignment(),
7435                                 Ld->getMemOperand()->getFlags(),
7436                                 Ld->getAAInfo(),
7437                                 nullptr); // Drop ranges
7438 
7439   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7440   if (MemVT.isFloatingPoint()) {
7441     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7442            "unexpected fp extload");
7443     TruncVT = MemVT.changeTypeToInteger();
7444   }
7445 
7446   SDValue Cvt = NewLoad;
7447   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7448     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7449                       DAG.getValueType(TruncVT));
7450   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7451              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7452     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7453   } else {
7454     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7455   }
7456 
7457   EVT VT = Ld->getValueType(0);
7458   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7459 
7460   DCI.AddToWorklist(Cvt.getNode());
7461 
7462   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7463   // the appropriate extension from the 32-bit load.
7464   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7465   DCI.AddToWorklist(Cvt.getNode());
7466 
7467   // Handle conversion back to floating point if necessary.
7468   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7469 
7470   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7471 }
7472 
7473 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7474   SDLoc DL(Op);
7475   LoadSDNode *Load = cast<LoadSDNode>(Op);
7476   ISD::LoadExtType ExtType = Load->getExtensionType();
7477   EVT MemVT = Load->getMemoryVT();
7478 
7479   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7480     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7481       return SDValue();
7482 
7483     // FIXME: Copied from PPC
7484     // First, load into 32 bits, then truncate to 1 bit.
7485 
7486     SDValue Chain = Load->getChain();
7487     SDValue BasePtr = Load->getBasePtr();
7488     MachineMemOperand *MMO = Load->getMemOperand();
7489 
7490     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7491 
7492     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7493                                    BasePtr, RealMemVT, MMO);
7494 
7495     if (!MemVT.isVector()) {
7496       SDValue Ops[] = {
7497         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7498         NewLD.getValue(1)
7499       };
7500 
7501       return DAG.getMergeValues(Ops, DL);
7502     }
7503 
7504     SmallVector<SDValue, 3> Elts;
7505     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7506       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7507                                 DAG.getConstant(I, DL, MVT::i32));
7508 
7509       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7510     }
7511 
7512     SDValue Ops[] = {
7513       DAG.getBuildVector(MemVT, DL, Elts),
7514       NewLD.getValue(1)
7515     };
7516 
7517     return DAG.getMergeValues(Ops, DL);
7518   }
7519 
7520   if (!MemVT.isVector())
7521     return SDValue();
7522 
7523   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7524          "Custom lowering for non-i32 vectors hasn't been implemented.");
7525 
7526   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7527                                       MemVT, *Load->getMemOperand())) {
7528     SDValue Ops[2];
7529     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7530     return DAG.getMergeValues(Ops, DL);
7531   }
7532 
7533   unsigned Alignment = Load->getAlignment();
7534   unsigned AS = Load->getAddressSpace();
7535   if (Subtarget->hasLDSMisalignedBug() &&
7536       AS == AMDGPUAS::FLAT_ADDRESS &&
7537       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7538     return SplitVectorLoad(Op, DAG);
7539   }
7540 
7541   MachineFunction &MF = DAG.getMachineFunction();
7542   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7543   // If there is a possibilty that flat instruction access scratch memory
7544   // then we need to use the same legalization rules we use for private.
7545   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7546       !Subtarget->hasMultiDwordFlatScratchAddressing())
7547     AS = MFI->hasFlatScratchInit() ?
7548          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7549 
7550   unsigned NumElements = MemVT.getVectorNumElements();
7551 
7552   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7553       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7554     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7555       if (MemVT.isPow2VectorType())
7556         return SDValue();
7557       if (NumElements == 3)
7558         return WidenVectorLoad(Op, DAG);
7559       return SplitVectorLoad(Op, DAG);
7560     }
7561     // Non-uniform loads will be selected to MUBUF instructions, so they
7562     // have the same legalization requirements as global and private
7563     // loads.
7564     //
7565   }
7566 
7567   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7568       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7569       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7570     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7571         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7572         Alignment >= 4 && NumElements < 32) {
7573       if (MemVT.isPow2VectorType())
7574         return SDValue();
7575       if (NumElements == 3)
7576         return WidenVectorLoad(Op, DAG);
7577       return SplitVectorLoad(Op, DAG);
7578     }
7579     // Non-uniform loads will be selected to MUBUF instructions, so they
7580     // have the same legalization requirements as global and private
7581     // loads.
7582     //
7583   }
7584   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7585       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7586       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7587       AS == AMDGPUAS::FLAT_ADDRESS) {
7588     if (NumElements > 4)
7589       return SplitVectorLoad(Op, DAG);
7590     // v3 loads not supported on SI.
7591     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7592       return WidenVectorLoad(Op, DAG);
7593     // v3 and v4 loads are supported for private and global memory.
7594     return SDValue();
7595   }
7596   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7597     // Depending on the setting of the private_element_size field in the
7598     // resource descriptor, we can only make private accesses up to a certain
7599     // size.
7600     switch (Subtarget->getMaxPrivateElementSize()) {
7601     case 4: {
7602       SDValue Ops[2];
7603       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7604       return DAG.getMergeValues(Ops, DL);
7605     }
7606     case 8:
7607       if (NumElements > 2)
7608         return SplitVectorLoad(Op, DAG);
7609       return SDValue();
7610     case 16:
7611       // Same as global/flat
7612       if (NumElements > 4)
7613         return SplitVectorLoad(Op, DAG);
7614       // v3 loads not supported on SI.
7615       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7616         return WidenVectorLoad(Op, DAG);
7617       return SDValue();
7618     default:
7619       llvm_unreachable("unsupported private_element_size");
7620     }
7621   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7622     // Use ds_read_b128 if possible.
7623     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7624         MemVT.getStoreSize() == 16)
7625       return SDValue();
7626 
7627     if (NumElements > 2)
7628       return SplitVectorLoad(Op, DAG);
7629 
7630     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7631     // address is negative, then the instruction is incorrectly treated as
7632     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7633     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7634     // load later in the SILoadStoreOptimizer.
7635     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7636         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7637         Load->getAlignment() < 8) {
7638       return SplitVectorLoad(Op, DAG);
7639     }
7640   }
7641   return SDValue();
7642 }
7643 
7644 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7645   EVT VT = Op.getValueType();
7646   assert(VT.getSizeInBits() == 64);
7647 
7648   SDLoc DL(Op);
7649   SDValue Cond = Op.getOperand(0);
7650 
7651   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7652   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7653 
7654   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7655   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7656 
7657   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7658   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7659 
7660   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7661 
7662   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7663   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7664 
7665   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7666 
7667   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7668   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7669 }
7670 
7671 // Catch division cases where we can use shortcuts with rcp and rsq
7672 // instructions.
7673 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7674                                               SelectionDAG &DAG) const {
7675   SDLoc SL(Op);
7676   SDValue LHS = Op.getOperand(0);
7677   SDValue RHS = Op.getOperand(1);
7678   EVT VT = Op.getValueType();
7679   const SDNodeFlags Flags = Op->getFlags();
7680 
7681   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7682                             Flags.hasApproximateFuncs();
7683 
7684   // Without !fpmath accuracy information, we can't do more because we don't
7685   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7686   if (!AllowInaccurateRcp)
7687     return SDValue();
7688 
7689   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7690     if (CLHS->isExactlyValue(1.0)) {
7691       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7692       // the CI documentation has a worst case error of 1 ulp.
7693       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7694       // use it as long as we aren't trying to use denormals.
7695       //
7696       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7697 
7698       // 1.0 / sqrt(x) -> rsq(x)
7699 
7700       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7701       // error seems really high at 2^29 ULP.
7702       if (RHS.getOpcode() == ISD::FSQRT)
7703         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7704 
7705       // 1.0 / x -> rcp(x)
7706       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7707     }
7708 
7709     // Same as for 1.0, but expand the sign out of the constant.
7710     if (CLHS->isExactlyValue(-1.0)) {
7711       // -1.0 / x -> rcp (fneg x)
7712       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7713       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7714     }
7715   }
7716 
7717   // Turn into multiply by the reciprocal.
7718   // x / y -> x * (1.0 / y)
7719   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7720   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7721 }
7722 
7723 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7724                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7725   if (GlueChain->getNumValues() <= 1) {
7726     return DAG.getNode(Opcode, SL, VT, A, B);
7727   }
7728 
7729   assert(GlueChain->getNumValues() == 3);
7730 
7731   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7732   switch (Opcode) {
7733   default: llvm_unreachable("no chain equivalent for opcode");
7734   case ISD::FMUL:
7735     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7736     break;
7737   }
7738 
7739   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7740                      GlueChain.getValue(2));
7741 }
7742 
7743 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7744                            EVT VT, SDValue A, SDValue B, SDValue C,
7745                            SDValue GlueChain) {
7746   if (GlueChain->getNumValues() <= 1) {
7747     return DAG.getNode(Opcode, SL, VT, A, B, C);
7748   }
7749 
7750   assert(GlueChain->getNumValues() == 3);
7751 
7752   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7753   switch (Opcode) {
7754   default: llvm_unreachable("no chain equivalent for opcode");
7755   case ISD::FMA:
7756     Opcode = AMDGPUISD::FMA_W_CHAIN;
7757     break;
7758   }
7759 
7760   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7761                      GlueChain.getValue(2));
7762 }
7763 
7764 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7765   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7766     return FastLowered;
7767 
7768   SDLoc SL(Op);
7769   SDValue Src0 = Op.getOperand(0);
7770   SDValue Src1 = Op.getOperand(1);
7771 
7772   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7773   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7774 
7775   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7776   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7777 
7778   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7779   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7780 
7781   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7782 }
7783 
7784 // Faster 2.5 ULP division that does not support denormals.
7785 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7786   SDLoc SL(Op);
7787   SDValue LHS = Op.getOperand(1);
7788   SDValue RHS = Op.getOperand(2);
7789 
7790   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7791 
7792   const APFloat K0Val(BitsToFloat(0x6f800000));
7793   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7794 
7795   const APFloat K1Val(BitsToFloat(0x2f800000));
7796   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7797 
7798   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7799 
7800   EVT SetCCVT =
7801     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7802 
7803   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7804 
7805   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7806 
7807   // TODO: Should this propagate fast-math-flags?
7808   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7809 
7810   // rcp does not support denormals.
7811   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7812 
7813   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7814 
7815   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7816 }
7817 
7818 // Returns immediate value for setting the F32 denorm mode when using the
7819 // S_DENORM_MODE instruction.
7820 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7821                                           const SDLoc &SL, const GCNSubtarget *ST) {
7822   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7823   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7824                                 ? FP_DENORM_FLUSH_NONE
7825                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7826 
7827   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7828   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7829 }
7830 
7831 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7832   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7833     return FastLowered;
7834 
7835   SDLoc SL(Op);
7836   SDValue LHS = Op.getOperand(0);
7837   SDValue RHS = Op.getOperand(1);
7838 
7839   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7840 
7841   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7842 
7843   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7844                                           RHS, RHS, LHS);
7845   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7846                                         LHS, RHS, LHS);
7847 
7848   // Denominator is scaled to not be denormal, so using rcp is ok.
7849   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7850                                   DenominatorScaled);
7851   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7852                                      DenominatorScaled);
7853 
7854   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7855                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7856                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7857   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7858 
7859   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7860 
7861   if (!HasFP32Denormals) {
7862     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7863 
7864     SDValue EnableDenorm;
7865     if (Subtarget->hasDenormModeInst()) {
7866       const SDValue EnableDenormValue =
7867           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7868 
7869       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7870                                  DAG.getEntryNode(), EnableDenormValue);
7871     } else {
7872       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7873                                                         SL, MVT::i32);
7874       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7875                                  DAG.getEntryNode(), EnableDenormValue,
7876                                  BitField);
7877     }
7878 
7879     SDValue Ops[3] = {
7880       NegDivScale0,
7881       EnableDenorm.getValue(0),
7882       EnableDenorm.getValue(1)
7883     };
7884 
7885     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7886   }
7887 
7888   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7889                              ApproxRcp, One, NegDivScale0);
7890 
7891   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7892                              ApproxRcp, Fma0);
7893 
7894   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7895                            Fma1, Fma1);
7896 
7897   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7898                              NumeratorScaled, Mul);
7899 
7900   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7901 
7902   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7903                              NumeratorScaled, Fma3);
7904 
7905   if (!HasFP32Denormals) {
7906     SDValue DisableDenorm;
7907     if (Subtarget->hasDenormModeInst()) {
7908       const SDValue DisableDenormValue =
7909           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7910 
7911       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7912                                   Fma4.getValue(1), DisableDenormValue,
7913                                   Fma4.getValue(2));
7914     } else {
7915       const SDValue DisableDenormValue =
7916           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7917 
7918       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7919                                   Fma4.getValue(1), DisableDenormValue,
7920                                   BitField, Fma4.getValue(2));
7921     }
7922 
7923     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7924                                       DisableDenorm, DAG.getRoot());
7925     DAG.setRoot(OutputChain);
7926   }
7927 
7928   SDValue Scale = NumeratorScaled.getValue(1);
7929   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7930                              Fma4, Fma1, Fma3, Scale);
7931 
7932   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7933 }
7934 
7935 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7936   if (DAG.getTarget().Options.UnsafeFPMath)
7937     return lowerFastUnsafeFDIV(Op, DAG);
7938 
7939   SDLoc SL(Op);
7940   SDValue X = Op.getOperand(0);
7941   SDValue Y = Op.getOperand(1);
7942 
7943   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7944 
7945   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7946 
7947   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7948 
7949   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7950 
7951   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7952 
7953   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7954 
7955   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7956 
7957   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7958 
7959   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7960 
7961   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7962   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7963 
7964   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7965                              NegDivScale0, Mul, DivScale1);
7966 
7967   SDValue Scale;
7968 
7969   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7970     // Workaround a hardware bug on SI where the condition output from div_scale
7971     // is not usable.
7972 
7973     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7974 
7975     // Figure out if the scale to use for div_fmas.
7976     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7977     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7978     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7979     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7980 
7981     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7982     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7983 
7984     SDValue Scale0Hi
7985       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7986     SDValue Scale1Hi
7987       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7988 
7989     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7990     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7991     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7992   } else {
7993     Scale = DivScale1.getValue(1);
7994   }
7995 
7996   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7997                              Fma4, Fma3, Mul, Scale);
7998 
7999   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8000 }
8001 
8002 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8003   EVT VT = Op.getValueType();
8004 
8005   if (VT == MVT::f32)
8006     return LowerFDIV32(Op, DAG);
8007 
8008   if (VT == MVT::f64)
8009     return LowerFDIV64(Op, DAG);
8010 
8011   if (VT == MVT::f16)
8012     return LowerFDIV16(Op, DAG);
8013 
8014   llvm_unreachable("Unexpected type for fdiv");
8015 }
8016 
8017 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8018   SDLoc DL(Op);
8019   StoreSDNode *Store = cast<StoreSDNode>(Op);
8020   EVT VT = Store->getMemoryVT();
8021 
8022   if (VT == MVT::i1) {
8023     return DAG.getTruncStore(Store->getChain(), DL,
8024        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8025        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8026   }
8027 
8028   assert(VT.isVector() &&
8029          Store->getValue().getValueType().getScalarType() == MVT::i32);
8030 
8031   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8032                                       VT, *Store->getMemOperand())) {
8033     return expandUnalignedStore(Store, DAG);
8034   }
8035 
8036   unsigned AS = Store->getAddressSpace();
8037   if (Subtarget->hasLDSMisalignedBug() &&
8038       AS == AMDGPUAS::FLAT_ADDRESS &&
8039       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8040     return SplitVectorStore(Op, DAG);
8041   }
8042 
8043   MachineFunction &MF = DAG.getMachineFunction();
8044   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8045   // If there is a possibilty that flat instruction access scratch memory
8046   // then we need to use the same legalization rules we use for private.
8047   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8048       !Subtarget->hasMultiDwordFlatScratchAddressing())
8049     AS = MFI->hasFlatScratchInit() ?
8050          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8051 
8052   unsigned NumElements = VT.getVectorNumElements();
8053   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8054       AS == AMDGPUAS::FLAT_ADDRESS) {
8055     if (NumElements > 4)
8056       return SplitVectorStore(Op, DAG);
8057     // v3 stores not supported on SI.
8058     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8059       return SplitVectorStore(Op, DAG);
8060     return SDValue();
8061   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8062     switch (Subtarget->getMaxPrivateElementSize()) {
8063     case 4:
8064       return scalarizeVectorStore(Store, DAG);
8065     case 8:
8066       if (NumElements > 2)
8067         return SplitVectorStore(Op, DAG);
8068       return SDValue();
8069     case 16:
8070       if (NumElements > 4 || NumElements == 3)
8071         return SplitVectorStore(Op, DAG);
8072       return SDValue();
8073     default:
8074       llvm_unreachable("unsupported private_element_size");
8075     }
8076   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8077     // Use ds_write_b128 if possible.
8078     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8079         VT.getStoreSize() == 16 && NumElements != 3)
8080       return SDValue();
8081 
8082     if (NumElements > 2)
8083       return SplitVectorStore(Op, DAG);
8084 
8085     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8086     // address is negative, then the instruction is incorrectly treated as
8087     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8088     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8089     // store later in the SILoadStoreOptimizer.
8090     if (!Subtarget->hasUsableDSOffset() &&
8091         NumElements == 2 && VT.getStoreSize() == 8 &&
8092         Store->getAlignment() < 8) {
8093       return SplitVectorStore(Op, DAG);
8094     }
8095 
8096     return SDValue();
8097   } else {
8098     llvm_unreachable("unhandled address space");
8099   }
8100 }
8101 
8102 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8103   SDLoc DL(Op);
8104   EVT VT = Op.getValueType();
8105   SDValue Arg = Op.getOperand(0);
8106   SDValue TrigVal;
8107 
8108   // TODO: Should this propagate fast-math-flags?
8109 
8110   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
8111 
8112   if (Subtarget->hasTrigReducedRange()) {
8113     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8114     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
8115   } else {
8116     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8117   }
8118 
8119   switch (Op.getOpcode()) {
8120   case ISD::FCOS:
8121     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
8122   case ISD::FSIN:
8123     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
8124   default:
8125     llvm_unreachable("Wrong trig opcode");
8126   }
8127 }
8128 
8129 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8130   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8131   assert(AtomicNode->isCompareAndSwap());
8132   unsigned AS = AtomicNode->getAddressSpace();
8133 
8134   // No custom lowering required for local address space
8135   if (!isFlatGlobalAddrSpace(AS))
8136     return Op;
8137 
8138   // Non-local address space requires custom lowering for atomic compare
8139   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8140   SDLoc DL(Op);
8141   SDValue ChainIn = Op.getOperand(0);
8142   SDValue Addr = Op.getOperand(1);
8143   SDValue Old = Op.getOperand(2);
8144   SDValue New = Op.getOperand(3);
8145   EVT VT = Op.getValueType();
8146   MVT SimpleVT = VT.getSimpleVT();
8147   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8148 
8149   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8150   SDValue Ops[] = { ChainIn, Addr, NewOld };
8151 
8152   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8153                                  Ops, VT, AtomicNode->getMemOperand());
8154 }
8155 
8156 //===----------------------------------------------------------------------===//
8157 // Custom DAG optimizations
8158 //===----------------------------------------------------------------------===//
8159 
8160 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8161                                                      DAGCombinerInfo &DCI) const {
8162   EVT VT = N->getValueType(0);
8163   EVT ScalarVT = VT.getScalarType();
8164   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8165     return SDValue();
8166 
8167   SelectionDAG &DAG = DCI.DAG;
8168   SDLoc DL(N);
8169 
8170   SDValue Src = N->getOperand(0);
8171   EVT SrcVT = Src.getValueType();
8172 
8173   // TODO: We could try to match extracting the higher bytes, which would be
8174   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8175   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8176   // about in practice.
8177   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8178     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8179       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8180       DCI.AddToWorklist(Cvt.getNode());
8181 
8182       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8183       if (ScalarVT != MVT::f32) {
8184         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8185                           DAG.getTargetConstant(0, DL, MVT::i32));
8186       }
8187       return Cvt;
8188     }
8189   }
8190 
8191   return SDValue();
8192 }
8193 
8194 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8195 
8196 // This is a variant of
8197 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8198 //
8199 // The normal DAG combiner will do this, but only if the add has one use since
8200 // that would increase the number of instructions.
8201 //
8202 // This prevents us from seeing a constant offset that can be folded into a
8203 // memory instruction's addressing mode. If we know the resulting add offset of
8204 // a pointer can be folded into an addressing offset, we can replace the pointer
8205 // operand with the add of new constant offset. This eliminates one of the uses,
8206 // and may allow the remaining use to also be simplified.
8207 //
8208 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8209                                                unsigned AddrSpace,
8210                                                EVT MemVT,
8211                                                DAGCombinerInfo &DCI) const {
8212   SDValue N0 = N->getOperand(0);
8213   SDValue N1 = N->getOperand(1);
8214 
8215   // We only do this to handle cases where it's profitable when there are
8216   // multiple uses of the add, so defer to the standard combine.
8217   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8218       N0->hasOneUse())
8219     return SDValue();
8220 
8221   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8222   if (!CN1)
8223     return SDValue();
8224 
8225   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8226   if (!CAdd)
8227     return SDValue();
8228 
8229   // If the resulting offset is too large, we can't fold it into the addressing
8230   // mode offset.
8231   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8232   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8233 
8234   AddrMode AM;
8235   AM.HasBaseReg = true;
8236   AM.BaseOffs = Offset.getSExtValue();
8237   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8238     return SDValue();
8239 
8240   SelectionDAG &DAG = DCI.DAG;
8241   SDLoc SL(N);
8242   EVT VT = N->getValueType(0);
8243 
8244   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8245   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8246 
8247   SDNodeFlags Flags;
8248   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8249                           (N0.getOpcode() == ISD::OR ||
8250                            N0->getFlags().hasNoUnsignedWrap()));
8251 
8252   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8253 }
8254 
8255 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8256                                                   DAGCombinerInfo &DCI) const {
8257   SDValue Ptr = N->getBasePtr();
8258   SelectionDAG &DAG = DCI.DAG;
8259   SDLoc SL(N);
8260 
8261   // TODO: We could also do this for multiplies.
8262   if (Ptr.getOpcode() == ISD::SHL) {
8263     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8264                                           N->getMemoryVT(), DCI);
8265     if (NewPtr) {
8266       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8267 
8268       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8269       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8270     }
8271   }
8272 
8273   return SDValue();
8274 }
8275 
8276 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8277   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8278          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8279          (Opc == ISD::XOR && Val == 0);
8280 }
8281 
8282 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8283 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8284 // integer combine opportunities since most 64-bit operations are decomposed
8285 // this way.  TODO: We won't want this for SALU especially if it is an inline
8286 // immediate.
8287 SDValue SITargetLowering::splitBinaryBitConstantOp(
8288   DAGCombinerInfo &DCI,
8289   const SDLoc &SL,
8290   unsigned Opc, SDValue LHS,
8291   const ConstantSDNode *CRHS) const {
8292   uint64_t Val = CRHS->getZExtValue();
8293   uint32_t ValLo = Lo_32(Val);
8294   uint32_t ValHi = Hi_32(Val);
8295   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8296 
8297     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8298          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8299         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8300     // If we need to materialize a 64-bit immediate, it will be split up later
8301     // anyway. Avoid creating the harder to understand 64-bit immediate
8302     // materialization.
8303     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8304   }
8305 
8306   return SDValue();
8307 }
8308 
8309 // Returns true if argument is a boolean value which is not serialized into
8310 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8311 static bool isBoolSGPR(SDValue V) {
8312   if (V.getValueType() != MVT::i1)
8313     return false;
8314   switch (V.getOpcode()) {
8315   default: break;
8316   case ISD::SETCC:
8317   case ISD::AND:
8318   case ISD::OR:
8319   case ISD::XOR:
8320   case AMDGPUISD::FP_CLASS:
8321     return true;
8322   }
8323   return false;
8324 }
8325 
8326 // If a constant has all zeroes or all ones within each byte return it.
8327 // Otherwise return 0.
8328 static uint32_t getConstantPermuteMask(uint32_t C) {
8329   // 0xff for any zero byte in the mask
8330   uint32_t ZeroByteMask = 0;
8331   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8332   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8333   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8334   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8335   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8336   if ((NonZeroByteMask & C) != NonZeroByteMask)
8337     return 0; // Partial bytes selected.
8338   return C;
8339 }
8340 
8341 // Check if a node selects whole bytes from its operand 0 starting at a byte
8342 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8343 // or -1 if not succeeded.
8344 // Note byte select encoding:
8345 // value 0-3 selects corresponding source byte;
8346 // value 0xc selects zero;
8347 // value 0xff selects 0xff.
8348 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8349   assert(V.getValueSizeInBits() == 32);
8350 
8351   if (V.getNumOperands() != 2)
8352     return ~0;
8353 
8354   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8355   if (!N1)
8356     return ~0;
8357 
8358   uint32_t C = N1->getZExtValue();
8359 
8360   switch (V.getOpcode()) {
8361   default:
8362     break;
8363   case ISD::AND:
8364     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8365       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8366     }
8367     break;
8368 
8369   case ISD::OR:
8370     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8371       return (0x03020100 & ~ConstMask) | ConstMask;
8372     }
8373     break;
8374 
8375   case ISD::SHL:
8376     if (C % 8)
8377       return ~0;
8378 
8379     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8380 
8381   case ISD::SRL:
8382     if (C % 8)
8383       return ~0;
8384 
8385     return uint32_t(0x0c0c0c0c03020100ull >> C);
8386   }
8387 
8388   return ~0;
8389 }
8390 
8391 SDValue SITargetLowering::performAndCombine(SDNode *N,
8392                                             DAGCombinerInfo &DCI) const {
8393   if (DCI.isBeforeLegalize())
8394     return SDValue();
8395 
8396   SelectionDAG &DAG = DCI.DAG;
8397   EVT VT = N->getValueType(0);
8398   SDValue LHS = N->getOperand(0);
8399   SDValue RHS = N->getOperand(1);
8400 
8401 
8402   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8403   if (VT == MVT::i64 && CRHS) {
8404     if (SDValue Split
8405         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8406       return Split;
8407   }
8408 
8409   if (CRHS && VT == MVT::i32) {
8410     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8411     // nb = number of trailing zeroes in mask
8412     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8413     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8414     uint64_t Mask = CRHS->getZExtValue();
8415     unsigned Bits = countPopulation(Mask);
8416     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8417         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8418       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8419         unsigned Shift = CShift->getZExtValue();
8420         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8421         unsigned Offset = NB + Shift;
8422         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8423           SDLoc SL(N);
8424           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8425                                     LHS->getOperand(0),
8426                                     DAG.getConstant(Offset, SL, MVT::i32),
8427                                     DAG.getConstant(Bits, SL, MVT::i32));
8428           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8429           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8430                                     DAG.getValueType(NarrowVT));
8431           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8432                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8433           return Shl;
8434         }
8435       }
8436     }
8437 
8438     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8439     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8440         isa<ConstantSDNode>(LHS.getOperand(2))) {
8441       uint32_t Sel = getConstantPermuteMask(Mask);
8442       if (!Sel)
8443         return SDValue();
8444 
8445       // Select 0xc for all zero bytes
8446       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8447       SDLoc DL(N);
8448       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8449                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8450     }
8451   }
8452 
8453   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8454   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8455   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8456     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8457     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8458 
8459     SDValue X = LHS.getOperand(0);
8460     SDValue Y = RHS.getOperand(0);
8461     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8462       return SDValue();
8463 
8464     if (LCC == ISD::SETO) {
8465       if (X != LHS.getOperand(1))
8466         return SDValue();
8467 
8468       if (RCC == ISD::SETUNE) {
8469         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8470         if (!C1 || !C1->isInfinity() || C1->isNegative())
8471           return SDValue();
8472 
8473         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8474                               SIInstrFlags::N_SUBNORMAL |
8475                               SIInstrFlags::N_ZERO |
8476                               SIInstrFlags::P_ZERO |
8477                               SIInstrFlags::P_SUBNORMAL |
8478                               SIInstrFlags::P_NORMAL;
8479 
8480         static_assert(((~(SIInstrFlags::S_NAN |
8481                           SIInstrFlags::Q_NAN |
8482                           SIInstrFlags::N_INFINITY |
8483                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8484                       "mask not equal");
8485 
8486         SDLoc DL(N);
8487         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8488                            X, DAG.getConstant(Mask, DL, MVT::i32));
8489       }
8490     }
8491   }
8492 
8493   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8494     std::swap(LHS, RHS);
8495 
8496   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8497       RHS.hasOneUse()) {
8498     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8499     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8500     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8501     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8502     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8503         (RHS.getOperand(0) == LHS.getOperand(0) &&
8504          LHS.getOperand(0) == LHS.getOperand(1))) {
8505       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8506       unsigned NewMask = LCC == ISD::SETO ?
8507         Mask->getZExtValue() & ~OrdMask :
8508         Mask->getZExtValue() & OrdMask;
8509 
8510       SDLoc DL(N);
8511       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8512                          DAG.getConstant(NewMask, DL, MVT::i32));
8513     }
8514   }
8515 
8516   if (VT == MVT::i32 &&
8517       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8518     // and x, (sext cc from i1) => select cc, x, 0
8519     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8520       std::swap(LHS, RHS);
8521     if (isBoolSGPR(RHS.getOperand(0)))
8522       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8523                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8524   }
8525 
8526   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8527   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8528   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8529       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8530     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8531     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8532     if (LHSMask != ~0u && RHSMask != ~0u) {
8533       // Canonicalize the expression in an attempt to have fewer unique masks
8534       // and therefore fewer registers used to hold the masks.
8535       if (LHSMask > RHSMask) {
8536         std::swap(LHSMask, RHSMask);
8537         std::swap(LHS, RHS);
8538       }
8539 
8540       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8541       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8542       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8543       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8544 
8545       // Check of we need to combine values from two sources within a byte.
8546       if (!(LHSUsedLanes & RHSUsedLanes) &&
8547           // If we select high and lower word keep it for SDWA.
8548           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8549           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8550         // Each byte in each mask is either selector mask 0-3, or has higher
8551         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8552         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8553         // mask which is not 0xff wins. By anding both masks we have a correct
8554         // result except that 0x0c shall be corrected to give 0x0c only.
8555         uint32_t Mask = LHSMask & RHSMask;
8556         for (unsigned I = 0; I < 32; I += 8) {
8557           uint32_t ByteSel = 0xff << I;
8558           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8559             Mask &= (0x0c << I) & 0xffffffff;
8560         }
8561 
8562         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8563         // or 0x0c.
8564         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8565         SDLoc DL(N);
8566 
8567         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8568                            LHS.getOperand(0), RHS.getOperand(0),
8569                            DAG.getConstant(Sel, DL, MVT::i32));
8570       }
8571     }
8572   }
8573 
8574   return SDValue();
8575 }
8576 
8577 SDValue SITargetLowering::performOrCombine(SDNode *N,
8578                                            DAGCombinerInfo &DCI) const {
8579   SelectionDAG &DAG = DCI.DAG;
8580   SDValue LHS = N->getOperand(0);
8581   SDValue RHS = N->getOperand(1);
8582 
8583   EVT VT = N->getValueType(0);
8584   if (VT == MVT::i1) {
8585     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8586     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8587         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8588       SDValue Src = LHS.getOperand(0);
8589       if (Src != RHS.getOperand(0))
8590         return SDValue();
8591 
8592       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8593       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8594       if (!CLHS || !CRHS)
8595         return SDValue();
8596 
8597       // Only 10 bits are used.
8598       static const uint32_t MaxMask = 0x3ff;
8599 
8600       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8601       SDLoc DL(N);
8602       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8603                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8604     }
8605 
8606     return SDValue();
8607   }
8608 
8609   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8610   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8611       LHS.getOpcode() == AMDGPUISD::PERM &&
8612       isa<ConstantSDNode>(LHS.getOperand(2))) {
8613     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8614     if (!Sel)
8615       return SDValue();
8616 
8617     Sel |= LHS.getConstantOperandVal(2);
8618     SDLoc DL(N);
8619     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8620                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8621   }
8622 
8623   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8624   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8625   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8626       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8627     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8628     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8629     if (LHSMask != ~0u && RHSMask != ~0u) {
8630       // Canonicalize the expression in an attempt to have fewer unique masks
8631       // and therefore fewer registers used to hold the masks.
8632       if (LHSMask > RHSMask) {
8633         std::swap(LHSMask, RHSMask);
8634         std::swap(LHS, RHS);
8635       }
8636 
8637       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8638       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8639       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8640       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8641 
8642       // Check of we need to combine values from two sources within a byte.
8643       if (!(LHSUsedLanes & RHSUsedLanes) &&
8644           // If we select high and lower word keep it for SDWA.
8645           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8646           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8647         // Kill zero bytes selected by other mask. Zero value is 0xc.
8648         LHSMask &= ~RHSUsedLanes;
8649         RHSMask &= ~LHSUsedLanes;
8650         // Add 4 to each active LHS lane
8651         LHSMask |= LHSUsedLanes & 0x04040404;
8652         // Combine masks
8653         uint32_t Sel = LHSMask | RHSMask;
8654         SDLoc DL(N);
8655 
8656         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8657                            LHS.getOperand(0), RHS.getOperand(0),
8658                            DAG.getConstant(Sel, DL, MVT::i32));
8659       }
8660     }
8661   }
8662 
8663   if (VT != MVT::i64)
8664     return SDValue();
8665 
8666   // TODO: This could be a generic combine with a predicate for extracting the
8667   // high half of an integer being free.
8668 
8669   // (or i64:x, (zero_extend i32:y)) ->
8670   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8671   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8672       RHS.getOpcode() != ISD::ZERO_EXTEND)
8673     std::swap(LHS, RHS);
8674 
8675   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8676     SDValue ExtSrc = RHS.getOperand(0);
8677     EVT SrcVT = ExtSrc.getValueType();
8678     if (SrcVT == MVT::i32) {
8679       SDLoc SL(N);
8680       SDValue LowLHS, HiBits;
8681       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8682       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8683 
8684       DCI.AddToWorklist(LowOr.getNode());
8685       DCI.AddToWorklist(HiBits.getNode());
8686 
8687       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8688                                 LowOr, HiBits);
8689       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8690     }
8691   }
8692 
8693   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8694   if (CRHS) {
8695     if (SDValue Split
8696           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8697       return Split;
8698   }
8699 
8700   return SDValue();
8701 }
8702 
8703 SDValue SITargetLowering::performXorCombine(SDNode *N,
8704                                             DAGCombinerInfo &DCI) const {
8705   EVT VT = N->getValueType(0);
8706   if (VT != MVT::i64)
8707     return SDValue();
8708 
8709   SDValue LHS = N->getOperand(0);
8710   SDValue RHS = N->getOperand(1);
8711 
8712   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8713   if (CRHS) {
8714     if (SDValue Split
8715           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8716       return Split;
8717   }
8718 
8719   return SDValue();
8720 }
8721 
8722 // Instructions that will be lowered with a final instruction that zeros the
8723 // high result bits.
8724 // XXX - probably only need to list legal operations.
8725 static bool fp16SrcZerosHighBits(unsigned Opc) {
8726   switch (Opc) {
8727   case ISD::FADD:
8728   case ISD::FSUB:
8729   case ISD::FMUL:
8730   case ISD::FDIV:
8731   case ISD::FREM:
8732   case ISD::FMA:
8733   case ISD::FMAD:
8734   case ISD::FCANONICALIZE:
8735   case ISD::FP_ROUND:
8736   case ISD::UINT_TO_FP:
8737   case ISD::SINT_TO_FP:
8738   case ISD::FABS:
8739     // Fabs is lowered to a bit operation, but it's an and which will clear the
8740     // high bits anyway.
8741   case ISD::FSQRT:
8742   case ISD::FSIN:
8743   case ISD::FCOS:
8744   case ISD::FPOWI:
8745   case ISD::FPOW:
8746   case ISD::FLOG:
8747   case ISD::FLOG2:
8748   case ISD::FLOG10:
8749   case ISD::FEXP:
8750   case ISD::FEXP2:
8751   case ISD::FCEIL:
8752   case ISD::FTRUNC:
8753   case ISD::FRINT:
8754   case ISD::FNEARBYINT:
8755   case ISD::FROUND:
8756   case ISD::FFLOOR:
8757   case ISD::FMINNUM:
8758   case ISD::FMAXNUM:
8759   case AMDGPUISD::FRACT:
8760   case AMDGPUISD::CLAMP:
8761   case AMDGPUISD::COS_HW:
8762   case AMDGPUISD::SIN_HW:
8763   case AMDGPUISD::FMIN3:
8764   case AMDGPUISD::FMAX3:
8765   case AMDGPUISD::FMED3:
8766   case AMDGPUISD::FMAD_FTZ:
8767   case AMDGPUISD::RCP:
8768   case AMDGPUISD::RSQ:
8769   case AMDGPUISD::RCP_IFLAG:
8770   case AMDGPUISD::LDEXP:
8771     return true;
8772   default:
8773     // fcopysign, select and others may be lowered to 32-bit bit operations
8774     // which don't zero the high bits.
8775     return false;
8776   }
8777 }
8778 
8779 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8780                                                    DAGCombinerInfo &DCI) const {
8781   if (!Subtarget->has16BitInsts() ||
8782       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8783     return SDValue();
8784 
8785   EVT VT = N->getValueType(0);
8786   if (VT != MVT::i32)
8787     return SDValue();
8788 
8789   SDValue Src = N->getOperand(0);
8790   if (Src.getValueType() != MVT::i16)
8791     return SDValue();
8792 
8793   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8794   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8795   if (Src.getOpcode() == ISD::BITCAST) {
8796     SDValue BCSrc = Src.getOperand(0);
8797     if (BCSrc.getValueType() == MVT::f16 &&
8798         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8799       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8800   }
8801 
8802   return SDValue();
8803 }
8804 
8805 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8806                                                         DAGCombinerInfo &DCI)
8807                                                         const {
8808   SDValue Src = N->getOperand(0);
8809   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8810 
8811   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8812       VTSign->getVT() == MVT::i8) ||
8813       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8814       VTSign->getVT() == MVT::i16)) &&
8815       Src.hasOneUse()) {
8816     auto *M = cast<MemSDNode>(Src);
8817     SDValue Ops[] = {
8818       Src.getOperand(0), // Chain
8819       Src.getOperand(1), // rsrc
8820       Src.getOperand(2), // vindex
8821       Src.getOperand(3), // voffset
8822       Src.getOperand(4), // soffset
8823       Src.getOperand(5), // offset
8824       Src.getOperand(6),
8825       Src.getOperand(7)
8826     };
8827     // replace with BUFFER_LOAD_BYTE/SHORT
8828     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8829                                          Src.getOperand(0).getValueType());
8830     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8831                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8832     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8833                                                           ResList,
8834                                                           Ops, M->getMemoryVT(),
8835                                                           M->getMemOperand());
8836     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8837                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8838   }
8839   return SDValue();
8840 }
8841 
8842 SDValue SITargetLowering::performClassCombine(SDNode *N,
8843                                               DAGCombinerInfo &DCI) const {
8844   SelectionDAG &DAG = DCI.DAG;
8845   SDValue Mask = N->getOperand(1);
8846 
8847   // fp_class x, 0 -> false
8848   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8849     if (CMask->isNullValue())
8850       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8851   }
8852 
8853   if (N->getOperand(0).isUndef())
8854     return DAG.getUNDEF(MVT::i1);
8855 
8856   return SDValue();
8857 }
8858 
8859 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8860                                             DAGCombinerInfo &DCI) const {
8861   EVT VT = N->getValueType(0);
8862   SDValue N0 = N->getOperand(0);
8863 
8864   if (N0.isUndef())
8865     return N0;
8866 
8867   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8868                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8869     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8870                            N->getFlags());
8871   }
8872 
8873   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8874     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8875                            N0.getOperand(0), N->getFlags());
8876   }
8877 
8878   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8879 }
8880 
8881 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8882                                        unsigned MaxDepth) const {
8883   unsigned Opcode = Op.getOpcode();
8884   if (Opcode == ISD::FCANONICALIZE)
8885     return true;
8886 
8887   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8888     auto F = CFP->getValueAPF();
8889     if (F.isNaN() && F.isSignaling())
8890       return false;
8891     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8892   }
8893 
8894   // If source is a result of another standard FP operation it is already in
8895   // canonical form.
8896   if (MaxDepth == 0)
8897     return false;
8898 
8899   switch (Opcode) {
8900   // These will flush denorms if required.
8901   case ISD::FADD:
8902   case ISD::FSUB:
8903   case ISD::FMUL:
8904   case ISD::FCEIL:
8905   case ISD::FFLOOR:
8906   case ISD::FMA:
8907   case ISD::FMAD:
8908   case ISD::FSQRT:
8909   case ISD::FDIV:
8910   case ISD::FREM:
8911   case ISD::FP_ROUND:
8912   case ISD::FP_EXTEND:
8913   case AMDGPUISD::FMUL_LEGACY:
8914   case AMDGPUISD::FMAD_FTZ:
8915   case AMDGPUISD::RCP:
8916   case AMDGPUISD::RSQ:
8917   case AMDGPUISD::RSQ_CLAMP:
8918   case AMDGPUISD::RCP_LEGACY:
8919   case AMDGPUISD::RCP_IFLAG:
8920   case AMDGPUISD::TRIG_PREOP:
8921   case AMDGPUISD::DIV_SCALE:
8922   case AMDGPUISD::DIV_FMAS:
8923   case AMDGPUISD::DIV_FIXUP:
8924   case AMDGPUISD::FRACT:
8925   case AMDGPUISD::LDEXP:
8926   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8927   case AMDGPUISD::CVT_F32_UBYTE0:
8928   case AMDGPUISD::CVT_F32_UBYTE1:
8929   case AMDGPUISD::CVT_F32_UBYTE2:
8930   case AMDGPUISD::CVT_F32_UBYTE3:
8931     return true;
8932 
8933   // It can/will be lowered or combined as a bit operation.
8934   // Need to check their input recursively to handle.
8935   case ISD::FNEG:
8936   case ISD::FABS:
8937   case ISD::FCOPYSIGN:
8938     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8939 
8940   case ISD::FSIN:
8941   case ISD::FCOS:
8942   case ISD::FSINCOS:
8943     return Op.getValueType().getScalarType() != MVT::f16;
8944 
8945   case ISD::FMINNUM:
8946   case ISD::FMAXNUM:
8947   case ISD::FMINNUM_IEEE:
8948   case ISD::FMAXNUM_IEEE:
8949   case AMDGPUISD::CLAMP:
8950   case AMDGPUISD::FMED3:
8951   case AMDGPUISD::FMAX3:
8952   case AMDGPUISD::FMIN3: {
8953     // FIXME: Shouldn't treat the generic operations different based these.
8954     // However, we aren't really required to flush the result from
8955     // minnum/maxnum..
8956 
8957     // snans will be quieted, so we only need to worry about denormals.
8958     if (Subtarget->supportsMinMaxDenormModes() ||
8959         denormalsEnabledForType(DAG, Op.getValueType()))
8960       return true;
8961 
8962     // Flushing may be required.
8963     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8964     // targets need to check their input recursively.
8965 
8966     // FIXME: Does this apply with clamp? It's implemented with max.
8967     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8968       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8969         return false;
8970     }
8971 
8972     return true;
8973   }
8974   case ISD::SELECT: {
8975     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8976            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8977   }
8978   case ISD::BUILD_VECTOR: {
8979     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8980       SDValue SrcOp = Op.getOperand(i);
8981       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8982         return false;
8983     }
8984 
8985     return true;
8986   }
8987   case ISD::EXTRACT_VECTOR_ELT:
8988   case ISD::EXTRACT_SUBVECTOR: {
8989     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8990   }
8991   case ISD::INSERT_VECTOR_ELT: {
8992     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8993            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8994   }
8995   case ISD::UNDEF:
8996     // Could be anything.
8997     return false;
8998 
8999   case ISD::BITCAST: {
9000     // Hack round the mess we make when legalizing extract_vector_elt
9001     SDValue Src = Op.getOperand(0);
9002     if (Src.getValueType() == MVT::i16 &&
9003         Src.getOpcode() == ISD::TRUNCATE) {
9004       SDValue TruncSrc = Src.getOperand(0);
9005       if (TruncSrc.getValueType() == MVT::i32 &&
9006           TruncSrc.getOpcode() == ISD::BITCAST &&
9007           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9008         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9009       }
9010     }
9011 
9012     return false;
9013   }
9014   case ISD::INTRINSIC_WO_CHAIN: {
9015     unsigned IntrinsicID
9016       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9017     // TODO: Handle more intrinsics
9018     switch (IntrinsicID) {
9019     case Intrinsic::amdgcn_cvt_pkrtz:
9020     case Intrinsic::amdgcn_cubeid:
9021     case Intrinsic::amdgcn_frexp_mant:
9022     case Intrinsic::amdgcn_fdot2:
9023     case Intrinsic::amdgcn_rcp:
9024     case Intrinsic::amdgcn_rsq:
9025     case Intrinsic::amdgcn_rsq_clamp:
9026     case Intrinsic::amdgcn_rcp_legacy:
9027     case Intrinsic::amdgcn_rsq_legacy:
9028       return true;
9029     default:
9030       break;
9031     }
9032 
9033     LLVM_FALLTHROUGH;
9034   }
9035   default:
9036     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9037            DAG.isKnownNeverSNaN(Op);
9038   }
9039 
9040   llvm_unreachable("invalid operation");
9041 }
9042 
9043 // Constant fold canonicalize.
9044 SDValue SITargetLowering::getCanonicalConstantFP(
9045   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9046   // Flush denormals to 0 if not enabled.
9047   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9048     return DAG.getConstantFP(0.0, SL, VT);
9049 
9050   if (C.isNaN()) {
9051     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9052     if (C.isSignaling()) {
9053       // Quiet a signaling NaN.
9054       // FIXME: Is this supposed to preserve payload bits?
9055       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9056     }
9057 
9058     // Make sure it is the canonical NaN bitpattern.
9059     //
9060     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9061     // immediate?
9062     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9063       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9064   }
9065 
9066   // Already canonical.
9067   return DAG.getConstantFP(C, SL, VT);
9068 }
9069 
9070 static bool vectorEltWillFoldAway(SDValue Op) {
9071   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9072 }
9073 
9074 SDValue SITargetLowering::performFCanonicalizeCombine(
9075   SDNode *N,
9076   DAGCombinerInfo &DCI) const {
9077   SelectionDAG &DAG = DCI.DAG;
9078   SDValue N0 = N->getOperand(0);
9079   EVT VT = N->getValueType(0);
9080 
9081   // fcanonicalize undef -> qnan
9082   if (N0.isUndef()) {
9083     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9084     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9085   }
9086 
9087   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9088     EVT VT = N->getValueType(0);
9089     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9090   }
9091 
9092   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9093   //                                                   (fcanonicalize k)
9094   //
9095   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9096 
9097   // TODO: This could be better with wider vectors that will be split to v2f16,
9098   // and to consider uses since there aren't that many packed operations.
9099   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9100       isTypeLegal(MVT::v2f16)) {
9101     SDLoc SL(N);
9102     SDValue NewElts[2];
9103     SDValue Lo = N0.getOperand(0);
9104     SDValue Hi = N0.getOperand(1);
9105     EVT EltVT = Lo.getValueType();
9106 
9107     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9108       for (unsigned I = 0; I != 2; ++I) {
9109         SDValue Op = N0.getOperand(I);
9110         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9111           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9112                                               CFP->getValueAPF());
9113         } else if (Op.isUndef()) {
9114           // Handled below based on what the other operand is.
9115           NewElts[I] = Op;
9116         } else {
9117           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9118         }
9119       }
9120 
9121       // If one half is undef, and one is constant, perfer a splat vector rather
9122       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9123       // cheaper to use and may be free with a packed operation.
9124       if (NewElts[0].isUndef()) {
9125         if (isa<ConstantFPSDNode>(NewElts[1]))
9126           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9127             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9128       }
9129 
9130       if (NewElts[1].isUndef()) {
9131         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9132           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9133       }
9134 
9135       return DAG.getBuildVector(VT, SL, NewElts);
9136     }
9137   }
9138 
9139   unsigned SrcOpc = N0.getOpcode();
9140 
9141   // If it's free to do so, push canonicalizes further up the source, which may
9142   // find a canonical source.
9143   //
9144   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9145   // sNaNs.
9146   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9147     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9148     if (CRHS && N0.hasOneUse()) {
9149       SDLoc SL(N);
9150       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9151                                    N0.getOperand(0));
9152       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9153       DCI.AddToWorklist(Canon0.getNode());
9154 
9155       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9156     }
9157   }
9158 
9159   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9160 }
9161 
9162 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9163   switch (Opc) {
9164   case ISD::FMAXNUM:
9165   case ISD::FMAXNUM_IEEE:
9166     return AMDGPUISD::FMAX3;
9167   case ISD::SMAX:
9168     return AMDGPUISD::SMAX3;
9169   case ISD::UMAX:
9170     return AMDGPUISD::UMAX3;
9171   case ISD::FMINNUM:
9172   case ISD::FMINNUM_IEEE:
9173     return AMDGPUISD::FMIN3;
9174   case ISD::SMIN:
9175     return AMDGPUISD::SMIN3;
9176   case ISD::UMIN:
9177     return AMDGPUISD::UMIN3;
9178   default:
9179     llvm_unreachable("Not a min/max opcode");
9180   }
9181 }
9182 
9183 SDValue SITargetLowering::performIntMed3ImmCombine(
9184   SelectionDAG &DAG, const SDLoc &SL,
9185   SDValue Op0, SDValue Op1, bool Signed) const {
9186   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9187   if (!K1)
9188     return SDValue();
9189 
9190   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9191   if (!K0)
9192     return SDValue();
9193 
9194   if (Signed) {
9195     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9196       return SDValue();
9197   } else {
9198     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9199       return SDValue();
9200   }
9201 
9202   EVT VT = K0->getValueType(0);
9203   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9204   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9205     return DAG.getNode(Med3Opc, SL, VT,
9206                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9207   }
9208 
9209   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9210   MVT NVT = MVT::i32;
9211   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9212 
9213   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9214   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9215   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9216 
9217   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9218   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9219 }
9220 
9221 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9222   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9223     return C;
9224 
9225   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9226     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9227       return C;
9228   }
9229 
9230   return nullptr;
9231 }
9232 
9233 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9234                                                   const SDLoc &SL,
9235                                                   SDValue Op0,
9236                                                   SDValue Op1) const {
9237   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9238   if (!K1)
9239     return SDValue();
9240 
9241   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9242   if (!K0)
9243     return SDValue();
9244 
9245   // Ordered >= (although NaN inputs should have folded away by now).
9246   if (K0->getValueAPF() > K1->getValueAPF())
9247     return SDValue();
9248 
9249   const MachineFunction &MF = DAG.getMachineFunction();
9250   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9251 
9252   // TODO: Check IEEE bit enabled?
9253   EVT VT = Op0.getValueType();
9254   if (Info->getMode().DX10Clamp) {
9255     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9256     // hardware fmed3 behavior converting to a min.
9257     // FIXME: Should this be allowing -0.0?
9258     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9259       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9260   }
9261 
9262   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9263   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9264     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9265     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9266     // then give the other result, which is different from med3 with a NaN
9267     // input.
9268     SDValue Var = Op0.getOperand(0);
9269     if (!DAG.isKnownNeverSNaN(Var))
9270       return SDValue();
9271 
9272     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9273 
9274     if ((!K0->hasOneUse() ||
9275          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9276         (!K1->hasOneUse() ||
9277          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9278       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9279                          Var, SDValue(K0, 0), SDValue(K1, 0));
9280     }
9281   }
9282 
9283   return SDValue();
9284 }
9285 
9286 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9287                                                DAGCombinerInfo &DCI) const {
9288   SelectionDAG &DAG = DCI.DAG;
9289 
9290   EVT VT = N->getValueType(0);
9291   unsigned Opc = N->getOpcode();
9292   SDValue Op0 = N->getOperand(0);
9293   SDValue Op1 = N->getOperand(1);
9294 
9295   // Only do this if the inner op has one use since this will just increases
9296   // register pressure for no benefit.
9297 
9298   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9299       !VT.isVector() &&
9300       (VT == MVT::i32 || VT == MVT::f32 ||
9301        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9302     // max(max(a, b), c) -> max3(a, b, c)
9303     // min(min(a, b), c) -> min3(a, b, c)
9304     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9305       SDLoc DL(N);
9306       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9307                          DL,
9308                          N->getValueType(0),
9309                          Op0.getOperand(0),
9310                          Op0.getOperand(1),
9311                          Op1);
9312     }
9313 
9314     // Try commuted.
9315     // max(a, max(b, c)) -> max3(a, b, c)
9316     // min(a, min(b, c)) -> min3(a, b, c)
9317     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9318       SDLoc DL(N);
9319       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9320                          DL,
9321                          N->getValueType(0),
9322                          Op0,
9323                          Op1.getOperand(0),
9324                          Op1.getOperand(1));
9325     }
9326   }
9327 
9328   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9329   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9330     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9331       return Med3;
9332   }
9333 
9334   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9335     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9336       return Med3;
9337   }
9338 
9339   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9340   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9341        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9342        (Opc == AMDGPUISD::FMIN_LEGACY &&
9343         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9344       (VT == MVT::f32 || VT == MVT::f64 ||
9345        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9346        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9347       Op0.hasOneUse()) {
9348     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9349       return Res;
9350   }
9351 
9352   return SDValue();
9353 }
9354 
9355 static bool isClampZeroToOne(SDValue A, SDValue B) {
9356   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9357     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9358       // FIXME: Should this be allowing -0.0?
9359       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9360              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9361     }
9362   }
9363 
9364   return false;
9365 }
9366 
9367 // FIXME: Should only worry about snans for version with chain.
9368 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9369                                               DAGCombinerInfo &DCI) const {
9370   EVT VT = N->getValueType(0);
9371   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9372   // NaNs. With a NaN input, the order of the operands may change the result.
9373 
9374   SelectionDAG &DAG = DCI.DAG;
9375   SDLoc SL(N);
9376 
9377   SDValue Src0 = N->getOperand(0);
9378   SDValue Src1 = N->getOperand(1);
9379   SDValue Src2 = N->getOperand(2);
9380 
9381   if (isClampZeroToOne(Src0, Src1)) {
9382     // const_a, const_b, x -> clamp is safe in all cases including signaling
9383     // nans.
9384     // FIXME: Should this be allowing -0.0?
9385     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9386   }
9387 
9388   const MachineFunction &MF = DAG.getMachineFunction();
9389   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9390 
9391   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9392   // handling no dx10-clamp?
9393   if (Info->getMode().DX10Clamp) {
9394     // If NaNs is clamped to 0, we are free to reorder the inputs.
9395 
9396     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9397       std::swap(Src0, Src1);
9398 
9399     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9400       std::swap(Src1, Src2);
9401 
9402     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9403       std::swap(Src0, Src1);
9404 
9405     if (isClampZeroToOne(Src1, Src2))
9406       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9407   }
9408 
9409   return SDValue();
9410 }
9411 
9412 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9413                                                  DAGCombinerInfo &DCI) const {
9414   SDValue Src0 = N->getOperand(0);
9415   SDValue Src1 = N->getOperand(1);
9416   if (Src0.isUndef() && Src1.isUndef())
9417     return DCI.DAG.getUNDEF(N->getValueType(0));
9418   return SDValue();
9419 }
9420 
9421 SDValue SITargetLowering::performExtractVectorEltCombine(
9422   SDNode *N, DAGCombinerInfo &DCI) const {
9423   SDValue Vec = N->getOperand(0);
9424   SelectionDAG &DAG = DCI.DAG;
9425 
9426   EVT VecVT = Vec.getValueType();
9427   EVT EltVT = VecVT.getVectorElementType();
9428 
9429   if ((Vec.getOpcode() == ISD::FNEG ||
9430        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9431     SDLoc SL(N);
9432     EVT EltVT = N->getValueType(0);
9433     SDValue Idx = N->getOperand(1);
9434     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9435                               Vec.getOperand(0), Idx);
9436     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9437   }
9438 
9439   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9440   //    =>
9441   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9442   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9443   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9444   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9445     SDLoc SL(N);
9446     EVT EltVT = N->getValueType(0);
9447     SDValue Idx = N->getOperand(1);
9448     unsigned Opc = Vec.getOpcode();
9449 
9450     switch(Opc) {
9451     default:
9452       break;
9453       // TODO: Support other binary operations.
9454     case ISD::FADD:
9455     case ISD::FSUB:
9456     case ISD::FMUL:
9457     case ISD::ADD:
9458     case ISD::UMIN:
9459     case ISD::UMAX:
9460     case ISD::SMIN:
9461     case ISD::SMAX:
9462     case ISD::FMAXNUM:
9463     case ISD::FMINNUM:
9464     case ISD::FMAXNUM_IEEE:
9465     case ISD::FMINNUM_IEEE: {
9466       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9467                                  Vec.getOperand(0), Idx);
9468       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9469                                  Vec.getOperand(1), Idx);
9470 
9471       DCI.AddToWorklist(Elt0.getNode());
9472       DCI.AddToWorklist(Elt1.getNode());
9473       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9474     }
9475     }
9476   }
9477 
9478   unsigned VecSize = VecVT.getSizeInBits();
9479   unsigned EltSize = EltVT.getSizeInBits();
9480 
9481   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9482   // This elminates non-constant index and subsequent movrel or scratch access.
9483   // Sub-dword vectors of size 2 dword or less have better implementation.
9484   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9485   // instructions.
9486   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9487       !isa<ConstantSDNode>(N->getOperand(1))) {
9488     SDLoc SL(N);
9489     SDValue Idx = N->getOperand(1);
9490     SDValue V;
9491     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9492       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9493       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9494       if (I == 0)
9495         V = Elt;
9496       else
9497         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9498     }
9499     return V;
9500   }
9501 
9502   if (!DCI.isBeforeLegalize())
9503     return SDValue();
9504 
9505   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9506   // elements. This exposes more load reduction opportunities by replacing
9507   // multiple small extract_vector_elements with a single 32-bit extract.
9508   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9509   if (isa<MemSDNode>(Vec) &&
9510       EltSize <= 16 &&
9511       EltVT.isByteSized() &&
9512       VecSize > 32 &&
9513       VecSize % 32 == 0 &&
9514       Idx) {
9515     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9516 
9517     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9518     unsigned EltIdx = BitIndex / 32;
9519     unsigned LeftoverBitIdx = BitIndex % 32;
9520     SDLoc SL(N);
9521 
9522     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9523     DCI.AddToWorklist(Cast.getNode());
9524 
9525     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9526                               DAG.getConstant(EltIdx, SL, MVT::i32));
9527     DCI.AddToWorklist(Elt.getNode());
9528     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9529                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9530     DCI.AddToWorklist(Srl.getNode());
9531 
9532     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9533     DCI.AddToWorklist(Trunc.getNode());
9534     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9535   }
9536 
9537   return SDValue();
9538 }
9539 
9540 SDValue
9541 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9542                                                 DAGCombinerInfo &DCI) const {
9543   SDValue Vec = N->getOperand(0);
9544   SDValue Idx = N->getOperand(2);
9545   EVT VecVT = Vec.getValueType();
9546   EVT EltVT = VecVT.getVectorElementType();
9547   unsigned VecSize = VecVT.getSizeInBits();
9548   unsigned EltSize = EltVT.getSizeInBits();
9549 
9550   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9551   // => BUILD_VECTOR n x select (e, const-idx)
9552   // This elminates non-constant index and subsequent movrel or scratch access.
9553   // Sub-dword vectors of size 2 dword or less have better implementation.
9554   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9555   // instructions.
9556   if (isa<ConstantSDNode>(Idx) ||
9557       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9558     return SDValue();
9559 
9560   SelectionDAG &DAG = DCI.DAG;
9561   SDLoc SL(N);
9562   SDValue Ins = N->getOperand(1);
9563   EVT IdxVT = Idx.getValueType();
9564 
9565   SmallVector<SDValue, 16> Ops;
9566   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9567     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9568     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9569     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9570     Ops.push_back(V);
9571   }
9572 
9573   return DAG.getBuildVector(VecVT, SL, Ops);
9574 }
9575 
9576 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9577                                           const SDNode *N0,
9578                                           const SDNode *N1) const {
9579   EVT VT = N0->getValueType(0);
9580 
9581   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9582   // support denormals ever.
9583   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9584        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9585         getSubtarget()->hasMadF16())) &&
9586        isOperationLegal(ISD::FMAD, VT))
9587     return ISD::FMAD;
9588 
9589   const TargetOptions &Options = DAG.getTarget().Options;
9590   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9591        (N0->getFlags().hasAllowContract() &&
9592         N1->getFlags().hasAllowContract())) &&
9593       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9594     return ISD::FMA;
9595   }
9596 
9597   return 0;
9598 }
9599 
9600 // For a reassociatable opcode perform:
9601 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9602 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9603                                                SelectionDAG &DAG) const {
9604   EVT VT = N->getValueType(0);
9605   if (VT != MVT::i32 && VT != MVT::i64)
9606     return SDValue();
9607 
9608   unsigned Opc = N->getOpcode();
9609   SDValue Op0 = N->getOperand(0);
9610   SDValue Op1 = N->getOperand(1);
9611 
9612   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9613     return SDValue();
9614 
9615   if (Op0->isDivergent())
9616     std::swap(Op0, Op1);
9617 
9618   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9619     return SDValue();
9620 
9621   SDValue Op2 = Op1.getOperand(1);
9622   Op1 = Op1.getOperand(0);
9623   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9624     return SDValue();
9625 
9626   if (Op1->isDivergent())
9627     std::swap(Op1, Op2);
9628 
9629   // If either operand is constant this will conflict with
9630   // DAGCombiner::ReassociateOps().
9631   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9632       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9633     return SDValue();
9634 
9635   SDLoc SL(N);
9636   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9637   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9638 }
9639 
9640 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9641                            EVT VT,
9642                            SDValue N0, SDValue N1, SDValue N2,
9643                            bool Signed) {
9644   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9645   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9646   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9647   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9648 }
9649 
9650 SDValue SITargetLowering::performAddCombine(SDNode *N,
9651                                             DAGCombinerInfo &DCI) const {
9652   SelectionDAG &DAG = DCI.DAG;
9653   EVT VT = N->getValueType(0);
9654   SDLoc SL(N);
9655   SDValue LHS = N->getOperand(0);
9656   SDValue RHS = N->getOperand(1);
9657 
9658   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9659       && Subtarget->hasMad64_32() &&
9660       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9661       VT.getScalarSizeInBits() <= 64) {
9662     if (LHS.getOpcode() != ISD::MUL)
9663       std::swap(LHS, RHS);
9664 
9665     SDValue MulLHS = LHS.getOperand(0);
9666     SDValue MulRHS = LHS.getOperand(1);
9667     SDValue AddRHS = RHS;
9668 
9669     // TODO: Maybe restrict if SGPR inputs.
9670     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9671         numBitsUnsigned(MulRHS, DAG) <= 32) {
9672       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9673       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9674       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9675       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9676     }
9677 
9678     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9679       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9680       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9681       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9682       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9683     }
9684 
9685     return SDValue();
9686   }
9687 
9688   if (SDValue V = reassociateScalarOps(N, DAG)) {
9689     return V;
9690   }
9691 
9692   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9693     return SDValue();
9694 
9695   // add x, zext (setcc) => addcarry x, 0, setcc
9696   // add x, sext (setcc) => subcarry x, 0, setcc
9697   unsigned Opc = LHS.getOpcode();
9698   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9699       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9700     std::swap(RHS, LHS);
9701 
9702   Opc = RHS.getOpcode();
9703   switch (Opc) {
9704   default: break;
9705   case ISD::ZERO_EXTEND:
9706   case ISD::SIGN_EXTEND:
9707   case ISD::ANY_EXTEND: {
9708     auto Cond = RHS.getOperand(0);
9709     // If this won't be a real VOPC output, we would still need to insert an
9710     // extra instruction anyway.
9711     if (!isBoolSGPR(Cond))
9712       break;
9713     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9714     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9715     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9716     return DAG.getNode(Opc, SL, VTList, Args);
9717   }
9718   case ISD::ADDCARRY: {
9719     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9720     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9721     if (!C || C->getZExtValue() != 0) break;
9722     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9723     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9724   }
9725   }
9726   return SDValue();
9727 }
9728 
9729 SDValue SITargetLowering::performSubCombine(SDNode *N,
9730                                             DAGCombinerInfo &DCI) const {
9731   SelectionDAG &DAG = DCI.DAG;
9732   EVT VT = N->getValueType(0);
9733 
9734   if (VT != MVT::i32)
9735     return SDValue();
9736 
9737   SDLoc SL(N);
9738   SDValue LHS = N->getOperand(0);
9739   SDValue RHS = N->getOperand(1);
9740 
9741   // sub x, zext (setcc) => subcarry x, 0, setcc
9742   // sub x, sext (setcc) => addcarry x, 0, setcc
9743   unsigned Opc = RHS.getOpcode();
9744   switch (Opc) {
9745   default: break;
9746   case ISD::ZERO_EXTEND:
9747   case ISD::SIGN_EXTEND:
9748   case ISD::ANY_EXTEND: {
9749     auto Cond = RHS.getOperand(0);
9750     // If this won't be a real VOPC output, we would still need to insert an
9751     // extra instruction anyway.
9752     if (!isBoolSGPR(Cond))
9753       break;
9754     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9755     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9756     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9757     return DAG.getNode(Opc, SL, VTList, Args);
9758   }
9759   }
9760 
9761   if (LHS.getOpcode() == ISD::SUBCARRY) {
9762     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9763     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9764     if (!C || !C->isNullValue())
9765       return SDValue();
9766     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9767     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9768   }
9769   return SDValue();
9770 }
9771 
9772 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9773   DAGCombinerInfo &DCI) const {
9774 
9775   if (N->getValueType(0) != MVT::i32)
9776     return SDValue();
9777 
9778   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9779   if (!C || C->getZExtValue() != 0)
9780     return SDValue();
9781 
9782   SelectionDAG &DAG = DCI.DAG;
9783   SDValue LHS = N->getOperand(0);
9784 
9785   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9786   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9787   unsigned LHSOpc = LHS.getOpcode();
9788   unsigned Opc = N->getOpcode();
9789   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9790       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9791     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9792     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9793   }
9794   return SDValue();
9795 }
9796 
9797 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9798                                              DAGCombinerInfo &DCI) const {
9799   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9800     return SDValue();
9801 
9802   SelectionDAG &DAG = DCI.DAG;
9803   EVT VT = N->getValueType(0);
9804 
9805   SDLoc SL(N);
9806   SDValue LHS = N->getOperand(0);
9807   SDValue RHS = N->getOperand(1);
9808 
9809   // These should really be instruction patterns, but writing patterns with
9810   // source modiifiers is a pain.
9811 
9812   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9813   if (LHS.getOpcode() == ISD::FADD) {
9814     SDValue A = LHS.getOperand(0);
9815     if (A == LHS.getOperand(1)) {
9816       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9817       if (FusedOp != 0) {
9818         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9819         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9820       }
9821     }
9822   }
9823 
9824   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9825   if (RHS.getOpcode() == ISD::FADD) {
9826     SDValue A = RHS.getOperand(0);
9827     if (A == RHS.getOperand(1)) {
9828       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9829       if (FusedOp != 0) {
9830         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9831         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9832       }
9833     }
9834   }
9835 
9836   return SDValue();
9837 }
9838 
9839 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9840                                              DAGCombinerInfo &DCI) const {
9841   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9842     return SDValue();
9843 
9844   SelectionDAG &DAG = DCI.DAG;
9845   SDLoc SL(N);
9846   EVT VT = N->getValueType(0);
9847   assert(!VT.isVector());
9848 
9849   // Try to get the fneg to fold into the source modifier. This undoes generic
9850   // DAG combines and folds them into the mad.
9851   //
9852   // Only do this if we are not trying to support denormals. v_mad_f32 does
9853   // not support denormals ever.
9854   SDValue LHS = N->getOperand(0);
9855   SDValue RHS = N->getOperand(1);
9856   if (LHS.getOpcode() == ISD::FADD) {
9857     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9858     SDValue A = LHS.getOperand(0);
9859     if (A == LHS.getOperand(1)) {
9860       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9861       if (FusedOp != 0){
9862         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9863         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9864 
9865         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9866       }
9867     }
9868   }
9869 
9870   if (RHS.getOpcode() == ISD::FADD) {
9871     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9872 
9873     SDValue A = RHS.getOperand(0);
9874     if (A == RHS.getOperand(1)) {
9875       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9876       if (FusedOp != 0){
9877         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9878         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9879       }
9880     }
9881   }
9882 
9883   return SDValue();
9884 }
9885 
9886 SDValue SITargetLowering::performFMACombine(SDNode *N,
9887                                             DAGCombinerInfo &DCI) const {
9888   SelectionDAG &DAG = DCI.DAG;
9889   EVT VT = N->getValueType(0);
9890   SDLoc SL(N);
9891 
9892   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9893     return SDValue();
9894 
9895   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9896   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9897   SDValue Op1 = N->getOperand(0);
9898   SDValue Op2 = N->getOperand(1);
9899   SDValue FMA = N->getOperand(2);
9900 
9901   if (FMA.getOpcode() != ISD::FMA ||
9902       Op1.getOpcode() != ISD::FP_EXTEND ||
9903       Op2.getOpcode() != ISD::FP_EXTEND)
9904     return SDValue();
9905 
9906   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9907   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9908   // is sufficient to allow generaing fdot2.
9909   const TargetOptions &Options = DAG.getTarget().Options;
9910   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9911       (N->getFlags().hasAllowContract() &&
9912        FMA->getFlags().hasAllowContract())) {
9913     Op1 = Op1.getOperand(0);
9914     Op2 = Op2.getOperand(0);
9915     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9916         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9917       return SDValue();
9918 
9919     SDValue Vec1 = Op1.getOperand(0);
9920     SDValue Idx1 = Op1.getOperand(1);
9921     SDValue Vec2 = Op2.getOperand(0);
9922 
9923     SDValue FMAOp1 = FMA.getOperand(0);
9924     SDValue FMAOp2 = FMA.getOperand(1);
9925     SDValue FMAAcc = FMA.getOperand(2);
9926 
9927     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9928         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9929       return SDValue();
9930 
9931     FMAOp1 = FMAOp1.getOperand(0);
9932     FMAOp2 = FMAOp2.getOperand(0);
9933     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9934         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9935       return SDValue();
9936 
9937     SDValue Vec3 = FMAOp1.getOperand(0);
9938     SDValue Vec4 = FMAOp2.getOperand(0);
9939     SDValue Idx2 = FMAOp1.getOperand(1);
9940 
9941     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9942         // Idx1 and Idx2 cannot be the same.
9943         Idx1 == Idx2)
9944       return SDValue();
9945 
9946     if (Vec1 == Vec2 || Vec3 == Vec4)
9947       return SDValue();
9948 
9949     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9950       return SDValue();
9951 
9952     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9953         (Vec1 == Vec4 && Vec2 == Vec3)) {
9954       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9955                          DAG.getTargetConstant(0, SL, MVT::i1));
9956     }
9957   }
9958   return SDValue();
9959 }
9960 
9961 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9962                                               DAGCombinerInfo &DCI) const {
9963   SelectionDAG &DAG = DCI.DAG;
9964   SDLoc SL(N);
9965 
9966   SDValue LHS = N->getOperand(0);
9967   SDValue RHS = N->getOperand(1);
9968   EVT VT = LHS.getValueType();
9969   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9970 
9971   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9972   if (!CRHS) {
9973     CRHS = dyn_cast<ConstantSDNode>(LHS);
9974     if (CRHS) {
9975       std::swap(LHS, RHS);
9976       CC = getSetCCSwappedOperands(CC);
9977     }
9978   }
9979 
9980   if (CRHS) {
9981     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9982         isBoolSGPR(LHS.getOperand(0))) {
9983       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9984       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9985       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9986       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9987       if ((CRHS->isAllOnesValue() &&
9988            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9989           (CRHS->isNullValue() &&
9990            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9991         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9992                            DAG.getConstant(-1, SL, MVT::i1));
9993       if ((CRHS->isAllOnesValue() &&
9994            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9995           (CRHS->isNullValue() &&
9996            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9997         return LHS.getOperand(0);
9998     }
9999 
10000     uint64_t CRHSVal = CRHS->getZExtValue();
10001     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10002         LHS.getOpcode() == ISD::SELECT &&
10003         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10004         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10005         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10006         isBoolSGPR(LHS.getOperand(0))) {
10007       // Given CT != FT:
10008       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10009       // setcc (select cc, CT, CF), CF, ne => cc
10010       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10011       // setcc (select cc, CT, CF), CT, eq => cc
10012       uint64_t CT = LHS.getConstantOperandVal(1);
10013       uint64_t CF = LHS.getConstantOperandVal(2);
10014 
10015       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10016           (CT == CRHSVal && CC == ISD::SETNE))
10017         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10018                            DAG.getConstant(-1, SL, MVT::i1));
10019       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10020           (CT == CRHSVal && CC == ISD::SETEQ))
10021         return LHS.getOperand(0);
10022     }
10023   }
10024 
10025   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10026                                            VT != MVT::f16))
10027     return SDValue();
10028 
10029   // Match isinf/isfinite pattern
10030   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10031   // (fcmp one (fabs x), inf) -> (fp_class x,
10032   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10033   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10034     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10035     if (!CRHS)
10036       return SDValue();
10037 
10038     const APFloat &APF = CRHS->getValueAPF();
10039     if (APF.isInfinity() && !APF.isNegative()) {
10040       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10041                                  SIInstrFlags::N_INFINITY;
10042       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10043                                     SIInstrFlags::P_ZERO |
10044                                     SIInstrFlags::N_NORMAL |
10045                                     SIInstrFlags::P_NORMAL |
10046                                     SIInstrFlags::N_SUBNORMAL |
10047                                     SIInstrFlags::P_SUBNORMAL;
10048       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10049       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10050                          DAG.getConstant(Mask, SL, MVT::i32));
10051     }
10052   }
10053 
10054   return SDValue();
10055 }
10056 
10057 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10058                                                      DAGCombinerInfo &DCI) const {
10059   SelectionDAG &DAG = DCI.DAG;
10060   SDLoc SL(N);
10061   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10062 
10063   SDValue Src = N->getOperand(0);
10064   SDValue Shift = N->getOperand(0);
10065 
10066   // TODO: Extend type shouldn't matter (assuming legal types).
10067   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10068     Shift = Shift.getOperand(0);
10069 
10070   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10071     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10072     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10073     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10074     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10075     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10076     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10077       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10078                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10079 
10080       unsigned ShiftOffset = 8 * Offset;
10081       if (Shift.getOpcode() == ISD::SHL)
10082         ShiftOffset -= C->getZExtValue();
10083       else
10084         ShiftOffset += C->getZExtValue();
10085 
10086       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10087         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10088                            MVT::f32, Shift);
10089       }
10090     }
10091   }
10092 
10093   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10094   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10095   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10096     // We simplified Src. If this node is not dead, visit it again so it is
10097     // folded properly.
10098     if (N->getOpcode() != ISD::DELETED_NODE)
10099       DCI.AddToWorklist(N);
10100     return SDValue(N, 0);
10101   }
10102 
10103   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10104   if (SDValue DemandedSrc =
10105           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10106     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10107 
10108   return SDValue();
10109 }
10110 
10111 SDValue SITargetLowering::performClampCombine(SDNode *N,
10112                                               DAGCombinerInfo &DCI) const {
10113   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10114   if (!CSrc)
10115     return SDValue();
10116 
10117   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10118   const APFloat &F = CSrc->getValueAPF();
10119   APFloat Zero = APFloat::getZero(F.getSemantics());
10120   if (F < Zero ||
10121       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10122     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10123   }
10124 
10125   APFloat One(F.getSemantics(), "1.0");
10126   if (F > One)
10127     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10128 
10129   return SDValue(CSrc, 0);
10130 }
10131 
10132 
10133 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10134                                             DAGCombinerInfo &DCI) const {
10135   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10136     return SDValue();
10137   switch (N->getOpcode()) {
10138   default:
10139     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10140   case ISD::ADD:
10141     return performAddCombine(N, DCI);
10142   case ISD::SUB:
10143     return performSubCombine(N, DCI);
10144   case ISD::ADDCARRY:
10145   case ISD::SUBCARRY:
10146     return performAddCarrySubCarryCombine(N, DCI);
10147   case ISD::FADD:
10148     return performFAddCombine(N, DCI);
10149   case ISD::FSUB:
10150     return performFSubCombine(N, DCI);
10151   case ISD::SETCC:
10152     return performSetCCCombine(N, DCI);
10153   case ISD::FMAXNUM:
10154   case ISD::FMINNUM:
10155   case ISD::FMAXNUM_IEEE:
10156   case ISD::FMINNUM_IEEE:
10157   case ISD::SMAX:
10158   case ISD::SMIN:
10159   case ISD::UMAX:
10160   case ISD::UMIN:
10161   case AMDGPUISD::FMIN_LEGACY:
10162   case AMDGPUISD::FMAX_LEGACY:
10163     return performMinMaxCombine(N, DCI);
10164   case ISD::FMA:
10165     return performFMACombine(N, DCI);
10166   case ISD::LOAD: {
10167     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10168       return Widended;
10169     LLVM_FALLTHROUGH;
10170   }
10171   case ISD::STORE:
10172   case ISD::ATOMIC_LOAD:
10173   case ISD::ATOMIC_STORE:
10174   case ISD::ATOMIC_CMP_SWAP:
10175   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10176   case ISD::ATOMIC_SWAP:
10177   case ISD::ATOMIC_LOAD_ADD:
10178   case ISD::ATOMIC_LOAD_SUB:
10179   case ISD::ATOMIC_LOAD_AND:
10180   case ISD::ATOMIC_LOAD_OR:
10181   case ISD::ATOMIC_LOAD_XOR:
10182   case ISD::ATOMIC_LOAD_NAND:
10183   case ISD::ATOMIC_LOAD_MIN:
10184   case ISD::ATOMIC_LOAD_MAX:
10185   case ISD::ATOMIC_LOAD_UMIN:
10186   case ISD::ATOMIC_LOAD_UMAX:
10187   case ISD::ATOMIC_LOAD_FADD:
10188   case AMDGPUISD::ATOMIC_INC:
10189   case AMDGPUISD::ATOMIC_DEC:
10190   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10191   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10192     if (DCI.isBeforeLegalize())
10193       break;
10194     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10195   case ISD::AND:
10196     return performAndCombine(N, DCI);
10197   case ISD::OR:
10198     return performOrCombine(N, DCI);
10199   case ISD::XOR:
10200     return performXorCombine(N, DCI);
10201   case ISD::ZERO_EXTEND:
10202     return performZeroExtendCombine(N, DCI);
10203   case ISD::SIGN_EXTEND_INREG:
10204     return performSignExtendInRegCombine(N , DCI);
10205   case AMDGPUISD::FP_CLASS:
10206     return performClassCombine(N, DCI);
10207   case ISD::FCANONICALIZE:
10208     return performFCanonicalizeCombine(N, DCI);
10209   case AMDGPUISD::RCP:
10210     return performRcpCombine(N, DCI);
10211   case AMDGPUISD::FRACT:
10212   case AMDGPUISD::RSQ:
10213   case AMDGPUISD::RCP_LEGACY:
10214   case AMDGPUISD::RCP_IFLAG:
10215   case AMDGPUISD::RSQ_CLAMP:
10216   case AMDGPUISD::LDEXP: {
10217     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10218     SDValue Src = N->getOperand(0);
10219     if (Src.isUndef())
10220       return Src;
10221     break;
10222   }
10223   case ISD::SINT_TO_FP:
10224   case ISD::UINT_TO_FP:
10225     return performUCharToFloatCombine(N, DCI);
10226   case AMDGPUISD::CVT_F32_UBYTE0:
10227   case AMDGPUISD::CVT_F32_UBYTE1:
10228   case AMDGPUISD::CVT_F32_UBYTE2:
10229   case AMDGPUISD::CVT_F32_UBYTE3:
10230     return performCvtF32UByteNCombine(N, DCI);
10231   case AMDGPUISD::FMED3:
10232     return performFMed3Combine(N, DCI);
10233   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10234     return performCvtPkRTZCombine(N, DCI);
10235   case AMDGPUISD::CLAMP:
10236     return performClampCombine(N, DCI);
10237   case ISD::SCALAR_TO_VECTOR: {
10238     SelectionDAG &DAG = DCI.DAG;
10239     EVT VT = N->getValueType(0);
10240 
10241     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10242     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10243       SDLoc SL(N);
10244       SDValue Src = N->getOperand(0);
10245       EVT EltVT = Src.getValueType();
10246       if (EltVT == MVT::f16)
10247         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10248 
10249       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10250       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10251     }
10252 
10253     break;
10254   }
10255   case ISD::EXTRACT_VECTOR_ELT:
10256     return performExtractVectorEltCombine(N, DCI);
10257   case ISD::INSERT_VECTOR_ELT:
10258     return performInsertVectorEltCombine(N, DCI);
10259   }
10260   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10261 }
10262 
10263 /// Helper function for adjustWritemask
10264 static unsigned SubIdx2Lane(unsigned Idx) {
10265   switch (Idx) {
10266   default: return 0;
10267   case AMDGPU::sub0: return 0;
10268   case AMDGPU::sub1: return 1;
10269   case AMDGPU::sub2: return 2;
10270   case AMDGPU::sub3: return 3;
10271   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10272   }
10273 }
10274 
10275 /// Adjust the writemask of MIMG instructions
10276 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10277                                           SelectionDAG &DAG) const {
10278   unsigned Opcode = Node->getMachineOpcode();
10279 
10280   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10281   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10282   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10283     return Node; // not implemented for D16
10284 
10285   SDNode *Users[5] = { nullptr };
10286   unsigned Lane = 0;
10287   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10288   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10289   unsigned NewDmask = 0;
10290   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10291   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10292   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10293                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10294   unsigned TFCLane = 0;
10295   bool HasChain = Node->getNumValues() > 1;
10296 
10297   if (OldDmask == 0) {
10298     // These are folded out, but on the chance it happens don't assert.
10299     return Node;
10300   }
10301 
10302   unsigned OldBitsSet = countPopulation(OldDmask);
10303   // Work out which is the TFE/LWE lane if that is enabled.
10304   if (UsesTFC) {
10305     TFCLane = OldBitsSet;
10306   }
10307 
10308   // Try to figure out the used register components
10309   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10310        I != E; ++I) {
10311 
10312     // Don't look at users of the chain.
10313     if (I.getUse().getResNo() != 0)
10314       continue;
10315 
10316     // Abort if we can't understand the usage
10317     if (!I->isMachineOpcode() ||
10318         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10319       return Node;
10320 
10321     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10322     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10323     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10324     // set, etc.
10325     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10326 
10327     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10328     if (UsesTFC && Lane == TFCLane) {
10329       Users[Lane] = *I;
10330     } else {
10331       // Set which texture component corresponds to the lane.
10332       unsigned Comp;
10333       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10334         Comp = countTrailingZeros(Dmask);
10335         Dmask &= ~(1 << Comp);
10336       }
10337 
10338       // Abort if we have more than one user per component.
10339       if (Users[Lane])
10340         return Node;
10341 
10342       Users[Lane] = *I;
10343       NewDmask |= 1 << Comp;
10344     }
10345   }
10346 
10347   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10348   bool NoChannels = !NewDmask;
10349   if (NoChannels) {
10350     if (!UsesTFC) {
10351       // No uses of the result and not using TFC. Then do nothing.
10352       return Node;
10353     }
10354     // If the original dmask has one channel - then nothing to do
10355     if (OldBitsSet == 1)
10356       return Node;
10357     // Use an arbitrary dmask - required for the instruction to work
10358     NewDmask = 1;
10359   }
10360   // Abort if there's no change
10361   if (NewDmask == OldDmask)
10362     return Node;
10363 
10364   unsigned BitsSet = countPopulation(NewDmask);
10365 
10366   // Check for TFE or LWE - increase the number of channels by one to account
10367   // for the extra return value
10368   // This will need adjustment for D16 if this is also included in
10369   // adjustWriteMask (this function) but at present D16 are excluded.
10370   unsigned NewChannels = BitsSet + UsesTFC;
10371 
10372   int NewOpcode =
10373       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10374   assert(NewOpcode != -1 &&
10375          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10376          "failed to find equivalent MIMG op");
10377 
10378   // Adjust the writemask in the node
10379   SmallVector<SDValue, 12> Ops;
10380   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10381   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10382   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10383 
10384   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10385 
10386   MVT ResultVT = NewChannels == 1 ?
10387     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10388                            NewChannels == 5 ? 8 : NewChannels);
10389   SDVTList NewVTList = HasChain ?
10390     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10391 
10392 
10393   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10394                                               NewVTList, Ops);
10395 
10396   if (HasChain) {
10397     // Update chain.
10398     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10399     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10400   }
10401 
10402   if (NewChannels == 1) {
10403     assert(Node->hasNUsesOfValue(1, 0));
10404     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10405                                       SDLoc(Node), Users[Lane]->getValueType(0),
10406                                       SDValue(NewNode, 0));
10407     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10408     return nullptr;
10409   }
10410 
10411   // Update the users of the node with the new indices
10412   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10413     SDNode *User = Users[i];
10414     if (!User) {
10415       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10416       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10417       if (i || !NoChannels)
10418         continue;
10419     } else {
10420       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10421       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10422     }
10423 
10424     switch (Idx) {
10425     default: break;
10426     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10427     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10428     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10429     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10430     }
10431   }
10432 
10433   DAG.RemoveDeadNode(Node);
10434   return nullptr;
10435 }
10436 
10437 static bool isFrameIndexOp(SDValue Op) {
10438   if (Op.getOpcode() == ISD::AssertZext)
10439     Op = Op.getOperand(0);
10440 
10441   return isa<FrameIndexSDNode>(Op);
10442 }
10443 
10444 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10445 /// with frame index operands.
10446 /// LLVM assumes that inputs are to these instructions are registers.
10447 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10448                                                         SelectionDAG &DAG) const {
10449   if (Node->getOpcode() == ISD::CopyToReg) {
10450     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10451     SDValue SrcVal = Node->getOperand(2);
10452 
10453     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10454     // to try understanding copies to physical registers.
10455     if (SrcVal.getValueType() == MVT::i1 &&
10456         Register::isPhysicalRegister(DestReg->getReg())) {
10457       SDLoc SL(Node);
10458       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10459       SDValue VReg = DAG.getRegister(
10460         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10461 
10462       SDNode *Glued = Node->getGluedNode();
10463       SDValue ToVReg
10464         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10465                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10466       SDValue ToResultReg
10467         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10468                            VReg, ToVReg.getValue(1));
10469       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10470       DAG.RemoveDeadNode(Node);
10471       return ToResultReg.getNode();
10472     }
10473   }
10474 
10475   SmallVector<SDValue, 8> Ops;
10476   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10477     if (!isFrameIndexOp(Node->getOperand(i))) {
10478       Ops.push_back(Node->getOperand(i));
10479       continue;
10480     }
10481 
10482     SDLoc DL(Node);
10483     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10484                                      Node->getOperand(i).getValueType(),
10485                                      Node->getOperand(i)), 0));
10486   }
10487 
10488   return DAG.UpdateNodeOperands(Node, Ops);
10489 }
10490 
10491 /// Fold the instructions after selecting them.
10492 /// Returns null if users were already updated.
10493 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10494                                           SelectionDAG &DAG) const {
10495   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10496   unsigned Opcode = Node->getMachineOpcode();
10497 
10498   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10499       !TII->isGather4(Opcode)) {
10500     return adjustWritemask(Node, DAG);
10501   }
10502 
10503   if (Opcode == AMDGPU::INSERT_SUBREG ||
10504       Opcode == AMDGPU::REG_SEQUENCE) {
10505     legalizeTargetIndependentNode(Node, DAG);
10506     return Node;
10507   }
10508 
10509   switch (Opcode) {
10510   case AMDGPU::V_DIV_SCALE_F32:
10511   case AMDGPU::V_DIV_SCALE_F64: {
10512     // Satisfy the operand register constraint when one of the inputs is
10513     // undefined. Ordinarily each undef value will have its own implicit_def of
10514     // a vreg, so force these to use a single register.
10515     SDValue Src0 = Node->getOperand(0);
10516     SDValue Src1 = Node->getOperand(1);
10517     SDValue Src2 = Node->getOperand(2);
10518 
10519     if ((Src0.isMachineOpcode() &&
10520          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10521         (Src0 == Src1 || Src0 == Src2))
10522       break;
10523 
10524     MVT VT = Src0.getValueType().getSimpleVT();
10525     const TargetRegisterClass *RC =
10526         getRegClassFor(VT, Src0.getNode()->isDivergent());
10527 
10528     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10529     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10530 
10531     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10532                                       UndefReg, Src0, SDValue());
10533 
10534     // src0 must be the same register as src1 or src2, even if the value is
10535     // undefined, so make sure we don't violate this constraint.
10536     if (Src0.isMachineOpcode() &&
10537         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10538       if (Src1.isMachineOpcode() &&
10539           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10540         Src0 = Src1;
10541       else if (Src2.isMachineOpcode() &&
10542                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10543         Src0 = Src2;
10544       else {
10545         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10546         Src0 = UndefReg;
10547         Src1 = UndefReg;
10548       }
10549     } else
10550       break;
10551 
10552     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10553     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10554       Ops.push_back(Node->getOperand(I));
10555 
10556     Ops.push_back(ImpDef.getValue(1));
10557     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10558   }
10559   default:
10560     break;
10561   }
10562 
10563   return Node;
10564 }
10565 
10566 /// Assign the register class depending on the number of
10567 /// bits set in the writemask
10568 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10569                                                      SDNode *Node) const {
10570   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10571 
10572   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10573 
10574   if (TII->isVOP3(MI.getOpcode())) {
10575     // Make sure constant bus requirements are respected.
10576     TII->legalizeOperandsVOP3(MRI, MI);
10577 
10578     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10579     // This saves a chain-copy of registers and better ballance register
10580     // use between vgpr and agpr as agpr tuples tend to be big.
10581     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10582       unsigned Opc = MI.getOpcode();
10583       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10584       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10585                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10586         if (I == -1)
10587           break;
10588         MachineOperand &Op = MI.getOperand(I);
10589         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10590              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10591             !Register::isVirtualRegister(Op.getReg()) ||
10592             !TRI->isAGPR(MRI, Op.getReg()))
10593           continue;
10594         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10595         if (!Src || !Src->isCopy() ||
10596             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10597           continue;
10598         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10599         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10600         // All uses of agpr64 and agpr32 can also accept vgpr except for
10601         // v_accvgpr_read, but we do not produce agpr reads during selection,
10602         // so no use checks are needed.
10603         MRI.setRegClass(Op.getReg(), NewRC);
10604       }
10605     }
10606 
10607     return;
10608   }
10609 
10610   // Replace unused atomics with the no return version.
10611   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10612   if (NoRetAtomicOp != -1) {
10613     if (!Node->hasAnyUseOfValue(0)) {
10614       MI.setDesc(TII->get(NoRetAtomicOp));
10615       MI.RemoveOperand(0);
10616       return;
10617     }
10618 
10619     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10620     // instruction, because the return type of these instructions is a vec2 of
10621     // the memory type, so it can be tied to the input operand.
10622     // This means these instructions always have a use, so we need to add a
10623     // special case to check if the atomic has only one extract_subreg use,
10624     // which itself has no uses.
10625     if ((Node->hasNUsesOfValue(1, 0) &&
10626          Node->use_begin()->isMachineOpcode() &&
10627          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10628          !Node->use_begin()->hasAnyUseOfValue(0))) {
10629       Register Def = MI.getOperand(0).getReg();
10630 
10631       // Change this into a noret atomic.
10632       MI.setDesc(TII->get(NoRetAtomicOp));
10633       MI.RemoveOperand(0);
10634 
10635       // If we only remove the def operand from the atomic instruction, the
10636       // extract_subreg will be left with a use of a vreg without a def.
10637       // So we need to insert an implicit_def to avoid machine verifier
10638       // errors.
10639       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10640               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10641     }
10642     return;
10643   }
10644 }
10645 
10646 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10647                               uint64_t Val) {
10648   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10649   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10650 }
10651 
10652 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10653                                                 const SDLoc &DL,
10654                                                 SDValue Ptr) const {
10655   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10656 
10657   // Build the half of the subregister with the constants before building the
10658   // full 128-bit register. If we are building multiple resource descriptors,
10659   // this will allow CSEing of the 2-component register.
10660   const SDValue Ops0[] = {
10661     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10662     buildSMovImm32(DAG, DL, 0),
10663     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10664     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10665     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10666   };
10667 
10668   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10669                                                 MVT::v2i32, Ops0), 0);
10670 
10671   // Combine the constants and the pointer.
10672   const SDValue Ops1[] = {
10673     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10674     Ptr,
10675     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10676     SubRegHi,
10677     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10678   };
10679 
10680   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10681 }
10682 
10683 /// Return a resource descriptor with the 'Add TID' bit enabled
10684 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10685 ///        of the resource descriptor) to create an offset, which is added to
10686 ///        the resource pointer.
10687 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10688                                            SDValue Ptr, uint32_t RsrcDword1,
10689                                            uint64_t RsrcDword2And3) const {
10690   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10691   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10692   if (RsrcDword1) {
10693     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10694                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10695                     0);
10696   }
10697 
10698   SDValue DataLo = buildSMovImm32(DAG, DL,
10699                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10700   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10701 
10702   const SDValue Ops[] = {
10703     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10704     PtrLo,
10705     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10706     PtrHi,
10707     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10708     DataLo,
10709     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10710     DataHi,
10711     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10712   };
10713 
10714   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10715 }
10716 
10717 //===----------------------------------------------------------------------===//
10718 //                         SI Inline Assembly Support
10719 //===----------------------------------------------------------------------===//
10720 
10721 std::pair<unsigned, const TargetRegisterClass *>
10722 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10723                                                StringRef Constraint,
10724                                                MVT VT) const {
10725   const TargetRegisterClass *RC = nullptr;
10726   if (Constraint.size() == 1) {
10727     const unsigned BitWidth = VT.getSizeInBits();
10728     switch (Constraint[0]) {
10729     default:
10730       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10731     case 's':
10732     case 'r':
10733       switch (BitWidth) {
10734       case 16:
10735         RC = &AMDGPU::SReg_32RegClass;
10736         break;
10737       case 64:
10738         RC = &AMDGPU::SGPR_64RegClass;
10739         break;
10740       default:
10741         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
10742         if (!RC)
10743           return std::make_pair(0U, nullptr);
10744         break;
10745       }
10746       break;
10747     case 'v':
10748       switch (BitWidth) {
10749       case 16:
10750         RC = &AMDGPU::VGPR_32RegClass;
10751         break;
10752       default:
10753         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
10754         if (!RC)
10755           return std::make_pair(0U, nullptr);
10756         break;
10757       }
10758       break;
10759     case 'a':
10760       if (!Subtarget->hasMAIInsts())
10761         break;
10762       switch (BitWidth) {
10763       case 16:
10764         RC = &AMDGPU::AGPR_32RegClass;
10765         break;
10766       default:
10767         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
10768         if (!RC)
10769           return std::make_pair(0U, nullptr);
10770         break;
10771       }
10772       break;
10773     }
10774     // We actually support i128, i16 and f16 as inline parameters
10775     // even if they are not reported as legal
10776     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10777                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10778       return std::make_pair(0U, RC);
10779   }
10780 
10781   if (Constraint.size() > 1) {
10782     if (Constraint[1] == 'v') {
10783       RC = &AMDGPU::VGPR_32RegClass;
10784     } else if (Constraint[1] == 's') {
10785       RC = &AMDGPU::SGPR_32RegClass;
10786     } else if (Constraint[1] == 'a') {
10787       RC = &AMDGPU::AGPR_32RegClass;
10788     }
10789 
10790     if (RC) {
10791       uint32_t Idx;
10792       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10793       if (!Failed && Idx < RC->getNumRegs())
10794         return std::make_pair(RC->getRegister(Idx), RC);
10795     }
10796   }
10797 
10798   // FIXME: Returns VS_32 for physical SGPR constraints
10799   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10800 }
10801 
10802 SITargetLowering::ConstraintType
10803 SITargetLowering::getConstraintType(StringRef Constraint) const {
10804   if (Constraint.size() == 1) {
10805     switch (Constraint[0]) {
10806     default: break;
10807     case 's':
10808     case 'v':
10809     case 'a':
10810       return C_RegisterClass;
10811     }
10812   }
10813   return TargetLowering::getConstraintType(Constraint);
10814 }
10815 
10816 // Figure out which registers should be reserved for stack access. Only after
10817 // the function is legalized do we know all of the non-spill stack objects or if
10818 // calls are present.
10819 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10820   MachineRegisterInfo &MRI = MF.getRegInfo();
10821   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10822   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10823   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10824 
10825   if (Info->isEntryFunction()) {
10826     // Callable functions have fixed registers used for stack access.
10827     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10828   }
10829 
10830   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10831                              Info->getStackPtrOffsetReg()));
10832   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10833     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10834 
10835   // We need to worry about replacing the default register with itself in case
10836   // of MIR testcases missing the MFI.
10837   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10838     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10839 
10840   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10841     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10842 
10843   Info->limitOccupancy(MF);
10844 
10845   if (ST.isWave32() && !MF.empty()) {
10846     // Add VCC_HI def because many instructions marked as imp-use VCC where
10847     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10848     // having a use of undef.
10849 
10850     const SIInstrInfo *TII = ST.getInstrInfo();
10851     DebugLoc DL;
10852 
10853     MachineBasicBlock &MBB = MF.front();
10854     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10855     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10856 
10857     for (auto &MBB : MF) {
10858       for (auto &MI : MBB) {
10859         TII->fixImplicitOperands(MI);
10860       }
10861     }
10862   }
10863 
10864   TargetLoweringBase::finalizeLowering(MF);
10865 
10866   // Allocate a VGPR for future SGPR Spill if
10867   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
10868   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
10869   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
10870       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
10871     Info->reserveVGPRforSGPRSpills(MF);
10872 }
10873 
10874 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10875                                                      KnownBits &Known,
10876                                                      const APInt &DemandedElts,
10877                                                      const SelectionDAG &DAG,
10878                                                      unsigned Depth) const {
10879   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10880                                                 DAG, Depth);
10881 
10882   // Set the high bits to zero based on the maximum allowed scratch size per
10883   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10884   // calculation won't overflow, so assume the sign bit is never set.
10885   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10886 }
10887 
10888 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10889   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10890   const Align CacheLineAlign = Align(64);
10891 
10892   // Pre-GFX10 target did not benefit from loop alignment
10893   if (!ML || DisableLoopAlignment ||
10894       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10895       getSubtarget()->hasInstFwdPrefetchBug())
10896     return PrefAlign;
10897 
10898   // On GFX10 I$ is 4 x 64 bytes cache lines.
10899   // By default prefetcher keeps one cache line behind and reads two ahead.
10900   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10901   // behind and one ahead.
10902   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10903   // If loop fits 64 bytes it always spans no more than two cache lines and
10904   // does not need an alignment.
10905   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10906   // Else if loop is less or equal 192 bytes we need two lines behind.
10907 
10908   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10909   const MachineBasicBlock *Header = ML->getHeader();
10910   if (Header->getAlignment() != PrefAlign)
10911     return Header->getAlignment(); // Already processed.
10912 
10913   unsigned LoopSize = 0;
10914   for (const MachineBasicBlock *MBB : ML->blocks()) {
10915     // If inner loop block is aligned assume in average half of the alignment
10916     // size to be added as nops.
10917     if (MBB != Header)
10918       LoopSize += MBB->getAlignment().value() / 2;
10919 
10920     for (const MachineInstr &MI : *MBB) {
10921       LoopSize += TII->getInstSizeInBytes(MI);
10922       if (LoopSize > 192)
10923         return PrefAlign;
10924     }
10925   }
10926 
10927   if (LoopSize <= 64)
10928     return PrefAlign;
10929 
10930   if (LoopSize <= 128)
10931     return CacheLineAlign;
10932 
10933   // If any of parent loops is surrounded by prefetch instructions do not
10934   // insert new for inner loop, which would reset parent's settings.
10935   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10936     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10937       auto I = Exit->getFirstNonDebugInstr();
10938       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10939         return CacheLineAlign;
10940     }
10941   }
10942 
10943   MachineBasicBlock *Pre = ML->getLoopPreheader();
10944   MachineBasicBlock *Exit = ML->getExitBlock();
10945 
10946   if (Pre && Exit) {
10947     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10948             TII->get(AMDGPU::S_INST_PREFETCH))
10949       .addImm(1); // prefetch 2 lines behind PC
10950 
10951     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10952             TII->get(AMDGPU::S_INST_PREFETCH))
10953       .addImm(2); // prefetch 1 line behind PC
10954   }
10955 
10956   return CacheLineAlign;
10957 }
10958 
10959 LLVM_ATTRIBUTE_UNUSED
10960 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10961   assert(N->getOpcode() == ISD::CopyFromReg);
10962   do {
10963     // Follow the chain until we find an INLINEASM node.
10964     N = N->getOperand(0).getNode();
10965     if (N->getOpcode() == ISD::INLINEASM ||
10966         N->getOpcode() == ISD::INLINEASM_BR)
10967       return true;
10968   } while (N->getOpcode() == ISD::CopyFromReg);
10969   return false;
10970 }
10971 
10972 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10973   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10974 {
10975   switch (N->getOpcode()) {
10976     case ISD::CopyFromReg:
10977     {
10978       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10979       const MachineFunction * MF = FLI->MF;
10980       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10981       const MachineRegisterInfo &MRI = MF->getRegInfo();
10982       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10983       Register Reg = R->getReg();
10984       if (Reg.isPhysical())
10985         return !TRI.isSGPRReg(MRI, Reg);
10986 
10987       if (MRI.isLiveIn(Reg)) {
10988         // workitem.id.x workitem.id.y workitem.id.z
10989         // Any VGPR formal argument is also considered divergent
10990         if (!TRI.isSGPRReg(MRI, Reg))
10991           return true;
10992         // Formal arguments of non-entry functions
10993         // are conservatively considered divergent
10994         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10995           return true;
10996         return false;
10997       }
10998       const Value *V = FLI->getValueFromVirtualReg(Reg);
10999       if (V)
11000         return KDA->isDivergent(V);
11001       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11002       return !TRI.isSGPRReg(MRI, Reg);
11003     }
11004     break;
11005     case ISD::LOAD: {
11006       const LoadSDNode *L = cast<LoadSDNode>(N);
11007       unsigned AS = L->getAddressSpace();
11008       // A flat load may access private memory.
11009       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11010     } break;
11011     case ISD::CALLSEQ_END:
11012     return true;
11013     break;
11014     case ISD::INTRINSIC_WO_CHAIN:
11015     {
11016 
11017     }
11018       return AMDGPU::isIntrinsicSourceOfDivergence(
11019       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11020     case ISD::INTRINSIC_W_CHAIN:
11021       return AMDGPU::isIntrinsicSourceOfDivergence(
11022       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11023   }
11024   return false;
11025 }
11026 
11027 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11028                                                EVT VT) const {
11029   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11030   case MVT::f32:
11031     return hasFP32Denormals(DAG.getMachineFunction());
11032   case MVT::f64:
11033   case MVT::f16:
11034     return hasFP64FP16Denormals(DAG.getMachineFunction());
11035   default:
11036     return false;
11037   }
11038 }
11039 
11040 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11041                                                     const SelectionDAG &DAG,
11042                                                     bool SNaN,
11043                                                     unsigned Depth) const {
11044   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11045     const MachineFunction &MF = DAG.getMachineFunction();
11046     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11047 
11048     if (Info->getMode().DX10Clamp)
11049       return true; // Clamped to 0.
11050     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11051   }
11052 
11053   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11054                                                             SNaN, Depth);
11055 }
11056 
11057 TargetLowering::AtomicExpansionKind
11058 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11059   switch (RMW->getOperation()) {
11060   case AtomicRMWInst::FAdd: {
11061     Type *Ty = RMW->getType();
11062 
11063     // We don't have a way to support 16-bit atomics now, so just leave them
11064     // as-is.
11065     if (Ty->isHalfTy())
11066       return AtomicExpansionKind::None;
11067 
11068     if (!Ty->isFloatTy())
11069       return AtomicExpansionKind::CmpXChg;
11070 
11071     // TODO: Do have these for flat. Older targets also had them for buffers.
11072     unsigned AS = RMW->getPointerAddressSpace();
11073 
11074     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11075       return RMW->use_empty() ? AtomicExpansionKind::None :
11076                                 AtomicExpansionKind::CmpXChg;
11077     }
11078 
11079     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11080       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11081   }
11082   default:
11083     break;
11084   }
11085 
11086   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11087 }
11088 
11089 const TargetRegisterClass *
11090 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11091   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11092   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11093   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11094     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11095                                                : &AMDGPU::SReg_32RegClass;
11096   if (!TRI->isSGPRClass(RC) && !isDivergent)
11097     return TRI->getEquivalentSGPRClass(RC);
11098   else if (TRI->isSGPRClass(RC) && isDivergent)
11099     return TRI->getEquivalentVGPRClass(RC);
11100 
11101   return RC;
11102 }
11103 
11104 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11105 // uniform values (as produced by the mask results of control flow intrinsics)
11106 // used outside of divergent blocks. The phi users need to also be treated as
11107 // always uniform.
11108 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11109                       unsigned WaveSize) {
11110   // FIXME: We asssume we never cast the mask results of a control flow
11111   // intrinsic.
11112   // Early exit if the type won't be consistent as a compile time hack.
11113   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11114   if (!IT || IT->getBitWidth() != WaveSize)
11115     return false;
11116 
11117   if (!isa<Instruction>(V))
11118     return false;
11119   if (!Visited.insert(V).second)
11120     return false;
11121   bool Result = false;
11122   for (auto U : V->users()) {
11123     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11124       if (V == U->getOperand(1)) {
11125         switch (Intrinsic->getIntrinsicID()) {
11126         default:
11127           Result = false;
11128           break;
11129         case Intrinsic::amdgcn_if_break:
11130         case Intrinsic::amdgcn_if:
11131         case Intrinsic::amdgcn_else:
11132           Result = true;
11133           break;
11134         }
11135       }
11136       if (V == U->getOperand(0)) {
11137         switch (Intrinsic->getIntrinsicID()) {
11138         default:
11139           Result = false;
11140           break;
11141         case Intrinsic::amdgcn_end_cf:
11142         case Intrinsic::amdgcn_loop:
11143           Result = true;
11144           break;
11145         }
11146       }
11147     } else {
11148       Result = hasCFUser(U, Visited, WaveSize);
11149     }
11150     if (Result)
11151       break;
11152   }
11153   return Result;
11154 }
11155 
11156 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11157                                                const Value *V) const {
11158   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11159     if (CI->isInlineAsm()) {
11160       // FIXME: This cannot give a correct answer. This should only trigger in
11161       // the case where inline asm returns mixed SGPR and VGPR results, used
11162       // outside the defining block. We don't have a specific result to
11163       // consider, so this assumes if any value is SGPR, the overall register
11164       // also needs to be SGPR.
11165       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11166       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11167           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11168       for (auto &TC : TargetConstraints) {
11169         if (TC.Type == InlineAsm::isOutput) {
11170           ComputeConstraintToUse(TC, SDValue());
11171           unsigned AssignedReg;
11172           const TargetRegisterClass *RC;
11173           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11174               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11175           if (RC) {
11176             MachineRegisterInfo &MRI = MF.getRegInfo();
11177             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11178               return true;
11179             else if (SIRI->isSGPRClass(RC))
11180               return true;
11181           }
11182         }
11183       }
11184     }
11185   }
11186   SmallPtrSet<const Value *, 16> Visited;
11187   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11188 }
11189