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