1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #if defined(_MSC_VER) || defined(__MINGW32__)
15 // Provide M_PI.
16 #define _USE_MATH_DEFINES
17 #endif
18 
19 #include "SIISelLowering.h"
20 #include "AMDGPU.h"
21 #include "AMDGPUSubtarget.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
24 #include "SIDefines.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "Utils/AMDGPUBaseInfo.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/CallingConvLower.h"
41 #include "llvm/CodeGen/DAGCombine.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineLoopInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
93 static cl::opt<bool> DisableLoopAlignment(
94   "amdgpu-disable-loop-alignment",
95   cl::desc("Do not align and prefetch loops"),
96   cl::init(false));
97 
98 static bool hasFP32Denormals(const MachineFunction &MF) {
99   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
100   return Info->getMode().allFP32Denormals();
101 }
102 
103 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
104   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
105   return Info->getMode().allFP64FP16Denormals();
106 }
107 
108 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
109   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
110   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
111     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
112       return AMDGPU::SGPR0 + Reg;
113     }
114   }
115   llvm_unreachable("Cannot allocate sgpr");
116 }
117 
118 SITargetLowering::SITargetLowering(const TargetMachine &TM,
119                                    const GCNSubtarget &STI)
120     : AMDGPUTargetLowering(TM, STI),
121       Subtarget(&STI) {
122   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
123   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
124 
125   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
126   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
127 
128   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
129   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
130   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
131 
132   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
133   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
134 
135   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
136   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
137 
138   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
139   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
140 
141   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
142   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
143 
144   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
145   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
146 
147   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
148   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
149 
150   if (Subtarget->has16BitInsts()) {
151     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
152     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
153 
154     // Unless there are also VOP3P operations, not operations are really legal.
155     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
156     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
157     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
158     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
159   }
160 
161   if (Subtarget->hasMAIInsts()) {
162     addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
163     addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
164   }
165 
166   computeRegisterProperties(Subtarget->getRegisterInfo());
167 
168   // The boolean content concept here is too inflexible. Compares only ever
169   // really produce a 1-bit result. Any copy/extend from these will turn into a
170   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
171   // it's what most targets use.
172   setBooleanContents(ZeroOrOneBooleanContent);
173   setBooleanVectorContents(ZeroOrOneBooleanContent);
174 
175   // We need to custom lower vector stores from local memory
176   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
177   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
178   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
179   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
180   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
181   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
182   setOperationAction(ISD::LOAD, MVT::i1, Custom);
183   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
184 
185   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
186   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
187   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
188   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
189   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
190   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
191   setOperationAction(ISD::STORE, MVT::i1, Custom);
192   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
193 
194   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
195   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
196   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
197   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
198   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
199   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
200   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
201   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
202   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
203   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
204   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
205 
206   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
207   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
208 
209   setOperationAction(ISD::SELECT, MVT::i1, Promote);
210   setOperationAction(ISD::SELECT, MVT::i64, Custom);
211   setOperationAction(ISD::SELECT, MVT::f64, Promote);
212   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
213 
214   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
215   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
216   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
217   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
218   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
219 
220   setOperationAction(ISD::SETCC, MVT::i1, Promote);
221   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
222   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
223   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
224 
225   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
226   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
227 
228   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
229   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
230   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
231   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
232   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
233   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
234   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
235   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
236 
237   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
238   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
239   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
240   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
241   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
242   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
243 
244   setOperationAction(ISD::UADDO, MVT::i32, Legal);
245   setOperationAction(ISD::USUBO, MVT::i32, Legal);
246 
247   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
248   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
249 
250   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
251   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
252   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
253 
254 #if 0
255   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
256   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
257 #endif
258 
259   // We only support LOAD/STORE and vector manipulation ops for vectors
260   // with > 4 elements.
261   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
262                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
263                   MVT::v32i32, MVT::v32f32 }) {
264     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
265       switch (Op) {
266       case ISD::LOAD:
267       case ISD::STORE:
268       case ISD::BUILD_VECTOR:
269       case ISD::BITCAST:
270       case ISD::EXTRACT_VECTOR_ELT:
271       case ISD::INSERT_VECTOR_ELT:
272       case ISD::INSERT_SUBVECTOR:
273       case ISD::EXTRACT_SUBVECTOR:
274       case ISD::SCALAR_TO_VECTOR:
275         break;
276       case ISD::CONCAT_VECTORS:
277         setOperationAction(Op, VT, Custom);
278         break;
279       default:
280         setOperationAction(Op, VT, Expand);
281         break;
282       }
283     }
284   }
285 
286   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
287 
288   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
289   // is expanded to avoid having two separate loops in case the index is a VGPR.
290 
291   // Most operations are naturally 32-bit vector operations. We only support
292   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
293   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
294     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
295     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
296 
297     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
298     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
299 
300     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
301     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
302 
303     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
305   }
306 
307   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
308   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
309   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
310   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
311 
312   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
313   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
314 
315   // Avoid stack access for these.
316   // TODO: Generalize to more vector types.
317   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
318   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
319   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
320   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
321 
322   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
323   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
324   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
325   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
326   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
327 
328   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
329   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
330   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
331 
332   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
333   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
334   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
335   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
336 
337   // Deal with vec3 vector operations when widened to vec4.
338   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
339   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
340   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
341   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
342 
343   // Deal with vec5 vector operations when widened to vec8.
344   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
345   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
346   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
347   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
348 
349   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
350   // and output demarshalling
351   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
352   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
353 
354   // We can't return success/failure, only the old value,
355   // let LLVM add the comparison
356   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
357   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
358 
359   if (Subtarget->hasFlatAddressSpace()) {
360     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
361     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
362   }
363 
364   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
365   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
366 
367   // On SI this is s_memtime and s_memrealtime on VI.
368   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
369   setOperationAction(ISD::TRAP, MVT::Other, Custom);
370   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
371 
372   if (Subtarget->has16BitInsts()) {
373     setOperationAction(ISD::FPOW, MVT::f16, Promote);
374     setOperationAction(ISD::FLOG, MVT::f16, Custom);
375     setOperationAction(ISD::FEXP, MVT::f16, Custom);
376     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
377   }
378 
379   // v_mad_f32 does not support denormals. We report it as unconditionally
380   // legal, and the context where it is formed will disallow it when fp32
381   // denormals are enabled.
382   setOperationAction(ISD::FMAD, MVT::f32, Legal);
383 
384   if (!Subtarget->hasBFI()) {
385     // fcopysign can be done in a single instruction with BFI.
386     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
387     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
388   }
389 
390   if (!Subtarget->hasBCNT(32))
391     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
392 
393   if (!Subtarget->hasBCNT(64))
394     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
395 
396   if (Subtarget->hasFFBH())
397     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
398 
399   if (Subtarget->hasFFBL())
400     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
401 
402   // We only really have 32-bit BFE instructions (and 16-bit on VI).
403   //
404   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
405   // effort to match them now. We want this to be false for i64 cases when the
406   // extraction isn't restricted to the upper or lower half. Ideally we would
407   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
408   // span the midpoint are probably relatively rare, so don't worry about them
409   // for now.
410   if (Subtarget->hasBFE())
411     setHasExtractBitsInsn(true);
412 
413   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
414   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
415   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
416   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
417 
418 
419   // These are really only legal for ieee_mode functions. We should be avoiding
420   // them for functions that don't have ieee_mode enabled, so just say they are
421   // legal.
422   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
423   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
424   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
425   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
426 
427 
428   if (Subtarget->haveRoundOpsF64()) {
429     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
430     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
431     setOperationAction(ISD::FRINT, MVT::f64, Legal);
432   } else {
433     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
434     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
435     setOperationAction(ISD::FRINT, MVT::f64, Custom);
436     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
437   }
438 
439   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
440 
441   setOperationAction(ISD::FSIN, MVT::f32, Custom);
442   setOperationAction(ISD::FCOS, MVT::f32, Custom);
443   setOperationAction(ISD::FDIV, MVT::f32, Custom);
444   setOperationAction(ISD::FDIV, MVT::f64, Custom);
445 
446   if (Subtarget->has16BitInsts()) {
447     setOperationAction(ISD::Constant, MVT::i16, Legal);
448 
449     setOperationAction(ISD::SMIN, MVT::i16, Legal);
450     setOperationAction(ISD::SMAX, MVT::i16, Legal);
451 
452     setOperationAction(ISD::UMIN, MVT::i16, Legal);
453     setOperationAction(ISD::UMAX, MVT::i16, Legal);
454 
455     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
456     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
457 
458     setOperationAction(ISD::ROTR, MVT::i16, Promote);
459     setOperationAction(ISD::ROTL, MVT::i16, Promote);
460 
461     setOperationAction(ISD::SDIV, MVT::i16, Promote);
462     setOperationAction(ISD::UDIV, MVT::i16, Promote);
463     setOperationAction(ISD::SREM, MVT::i16, Promote);
464     setOperationAction(ISD::UREM, MVT::i16, Promote);
465 
466     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
467     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
468 
469     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
470     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
471     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
473     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
474 
475     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
476 
477     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
478 
479     setOperationAction(ISD::LOAD, MVT::i16, Custom);
480 
481     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
482 
483     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
484     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
485     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
486     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
487 
488     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
489     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
490 
491     // F16 - Constant Actions.
492     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
493 
494     // F16 - Load/Store Actions.
495     setOperationAction(ISD::LOAD, MVT::f16, Promote);
496     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
497     setOperationAction(ISD::STORE, MVT::f16, Promote);
498     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
499 
500     // F16 - VOP1 Actions.
501     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
502     setOperationAction(ISD::FCOS, MVT::f16, Custom);
503     setOperationAction(ISD::FSIN, MVT::f16, Custom);
504 
505     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
506     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
507 
508     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
509     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
510     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
511     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
512     setOperationAction(ISD::FROUND, MVT::f16, Custom);
513 
514     // F16 - VOP2 Actions.
515     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
516     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
517 
518     setOperationAction(ISD::FDIV, MVT::f16, Custom);
519 
520     // F16 - VOP3 Actions.
521     setOperationAction(ISD::FMA, MVT::f16, Legal);
522     if (STI.hasMadF16())
523       setOperationAction(ISD::FMAD, MVT::f16, Legal);
524 
525     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
526       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
527         switch (Op) {
528         case ISD::LOAD:
529         case ISD::STORE:
530         case ISD::BUILD_VECTOR:
531         case ISD::BITCAST:
532         case ISD::EXTRACT_VECTOR_ELT:
533         case ISD::INSERT_VECTOR_ELT:
534         case ISD::INSERT_SUBVECTOR:
535         case ISD::EXTRACT_SUBVECTOR:
536         case ISD::SCALAR_TO_VECTOR:
537           break;
538         case ISD::CONCAT_VECTORS:
539           setOperationAction(Op, VT, Custom);
540           break;
541         default:
542           setOperationAction(Op, VT, Expand);
543           break;
544         }
545       }
546     }
547 
548     // XXX - Do these do anything? Vector constants turn into build_vector.
549     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
550     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
551 
552     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
553     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
554 
555     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
556     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
557     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
558     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
559 
560     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
561     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
562     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
563     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
564 
565     setOperationAction(ISD::AND, MVT::v2i16, Promote);
566     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
567     setOperationAction(ISD::OR, MVT::v2i16, Promote);
568     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
569     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
570     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
571 
572     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
573     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
574     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
575     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
576 
577     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
578     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
579     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
580     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
581 
582     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
583     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
584     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
585     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
586 
587     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
588     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
589     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
590 
591     if (!Subtarget->hasVOP3PInsts()) {
592       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
593       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
594     }
595 
596     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
597     // This isn't really legal, but this avoids the legalizer unrolling it (and
598     // allows matching fneg (fabs x) patterns)
599     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
600 
601     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
602     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
603     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
604     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
605 
606     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
607     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
608 
609     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
610     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
611   }
612 
613   if (Subtarget->hasVOP3PInsts()) {
614     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
615     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
616     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
617     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
618     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
619     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
620     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
621     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
622     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
623     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
624 
625     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
626     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
627     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
628 
629     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
630     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
631 
632     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
633 
634     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
635     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
636 
637     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
638     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
639 
640     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
641     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
642     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
643     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
644     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
645     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
646 
647     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
648     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
649     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
650     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
651 
652     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
653     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
654     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
655 
656     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
657     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
658 
659     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
660     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
661     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
662 
663     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
664     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
665     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
666   }
667 
668   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
669   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
670 
671   if (Subtarget->has16BitInsts()) {
672     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
673     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
674     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
675     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
676   } else {
677     // Legalization hack.
678     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
679     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
680 
681     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
682     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
683   }
684 
685   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
686     setOperationAction(ISD::SELECT, VT, Custom);
687   }
688 
689   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
690   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
691   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
692   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
693   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
694   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
695   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
696 
697   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
698   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
699   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
700   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
701   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
702   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
703   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
704   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
705   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
706 
707   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
708   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
709   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
710   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
711   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
712   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
713   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
714   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
715 
716   setTargetDAGCombine(ISD::ADD);
717   setTargetDAGCombine(ISD::ADDCARRY);
718   setTargetDAGCombine(ISD::SUB);
719   setTargetDAGCombine(ISD::SUBCARRY);
720   setTargetDAGCombine(ISD::FADD);
721   setTargetDAGCombine(ISD::FSUB);
722   setTargetDAGCombine(ISD::FMINNUM);
723   setTargetDAGCombine(ISD::FMAXNUM);
724   setTargetDAGCombine(ISD::FMINNUM_IEEE);
725   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
726   setTargetDAGCombine(ISD::FMA);
727   setTargetDAGCombine(ISD::SMIN);
728   setTargetDAGCombine(ISD::SMAX);
729   setTargetDAGCombine(ISD::UMIN);
730   setTargetDAGCombine(ISD::UMAX);
731   setTargetDAGCombine(ISD::SETCC);
732   setTargetDAGCombine(ISD::AND);
733   setTargetDAGCombine(ISD::OR);
734   setTargetDAGCombine(ISD::XOR);
735   setTargetDAGCombine(ISD::SINT_TO_FP);
736   setTargetDAGCombine(ISD::UINT_TO_FP);
737   setTargetDAGCombine(ISD::FCANONICALIZE);
738   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
739   setTargetDAGCombine(ISD::ZERO_EXTEND);
740   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
741   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
742   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
743 
744   // All memory operations. Some folding on the pointer operand is done to help
745   // matching the constant offsets in the addressing modes.
746   setTargetDAGCombine(ISD::LOAD);
747   setTargetDAGCombine(ISD::STORE);
748   setTargetDAGCombine(ISD::ATOMIC_LOAD);
749   setTargetDAGCombine(ISD::ATOMIC_STORE);
750   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
751   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
752   setTargetDAGCombine(ISD::ATOMIC_SWAP);
753   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
754   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
755   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
756   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
757   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
758   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
759   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
760   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
761   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
762   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
763   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
764 
765   setSchedulingPreference(Sched::RegPressure);
766 }
767 
768 const GCNSubtarget *SITargetLowering::getSubtarget() const {
769   return Subtarget;
770 }
771 
772 //===----------------------------------------------------------------------===//
773 // TargetLowering queries
774 //===----------------------------------------------------------------------===//
775 
776 // v_mad_mix* support a conversion from f16 to f32.
777 //
778 // There is only one special case when denormals are enabled we don't currently,
779 // where this is OK to use.
780 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
781                                        EVT DestVT, EVT SrcVT) const {
782   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
783           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
784     DestVT.getScalarType() == MVT::f32 &&
785     SrcVT.getScalarType() == MVT::f16 &&
786     // TODO: This probably only requires no input flushing?
787     !hasFP32Denormals(DAG.getMachineFunction());
788 }
789 
790 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
791   // SI has some legal vector types, but no legal vector operations. Say no
792   // shuffles are legal in order to prefer scalarizing some vector operations.
793   return false;
794 }
795 
796 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
797                                                     CallingConv::ID CC,
798                                                     EVT VT) const {
799   if (CC == CallingConv::AMDGPU_KERNEL)
800     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
801 
802   if (VT.isVector()) {
803     EVT ScalarVT = VT.getScalarType();
804     unsigned Size = ScalarVT.getSizeInBits();
805     if (Size == 32)
806       return ScalarVT.getSimpleVT();
807 
808     if (Size > 32)
809       return MVT::i32;
810 
811     if (Size == 16 && Subtarget->has16BitInsts())
812       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
813   } else if (VT.getSizeInBits() > 32)
814     return MVT::i32;
815 
816   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
817 }
818 
819 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
820                                                          CallingConv::ID CC,
821                                                          EVT VT) const {
822   if (CC == CallingConv::AMDGPU_KERNEL)
823     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
824 
825   if (VT.isVector()) {
826     unsigned NumElts = VT.getVectorNumElements();
827     EVT ScalarVT = VT.getScalarType();
828     unsigned Size = ScalarVT.getSizeInBits();
829 
830     if (Size == 32)
831       return NumElts;
832 
833     if (Size > 32)
834       return NumElts * ((Size + 31) / 32);
835 
836     if (Size == 16 && Subtarget->has16BitInsts())
837       return (NumElts + 1) / 2;
838   } else if (VT.getSizeInBits() > 32)
839     return (VT.getSizeInBits() + 31) / 32;
840 
841   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
842 }
843 
844 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
845   LLVMContext &Context, CallingConv::ID CC,
846   EVT VT, EVT &IntermediateVT,
847   unsigned &NumIntermediates, MVT &RegisterVT) const {
848   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
849     unsigned NumElts = VT.getVectorNumElements();
850     EVT ScalarVT = VT.getScalarType();
851     unsigned Size = ScalarVT.getSizeInBits();
852     if (Size == 32) {
853       RegisterVT = ScalarVT.getSimpleVT();
854       IntermediateVT = RegisterVT;
855       NumIntermediates = NumElts;
856       return NumIntermediates;
857     }
858 
859     if (Size > 32) {
860       RegisterVT = MVT::i32;
861       IntermediateVT = RegisterVT;
862       NumIntermediates = NumElts * ((Size + 31) / 32);
863       return NumIntermediates;
864     }
865 
866     // FIXME: We should fix the ABI to be the same on targets without 16-bit
867     // support, but unless we can properly handle 3-vectors, it will be still be
868     // inconsistent.
869     if (Size == 16 && Subtarget->has16BitInsts()) {
870       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
871       IntermediateVT = RegisterVT;
872       NumIntermediates = (NumElts + 1) / 2;
873       return NumIntermediates;
874     }
875   }
876 
877   return TargetLowering::getVectorTypeBreakdownForCallingConv(
878     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
879 }
880 
881 // Peek through TFE struct returns to only use the data size.
882 static EVT memVTFromImageReturn(Type *Ty) {
883   auto *ST = dyn_cast<StructType>(Ty);
884   if (!ST)
885     return EVT::getEVT(Ty, true);
886 
887   // Some intrinsics return an aggregate type - special case to work out the
888   // correct memVT.
889   //
890   // Only limited forms of aggregate type currently expected.
891   if (ST->getNumContainedTypes() != 2 ||
892       !ST->getContainedType(1)->isIntegerTy(32))
893     return EVT();
894   return EVT::getEVT(ST->getContainedType(0));
895 }
896 
897 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
898                                           const CallInst &CI,
899                                           MachineFunction &MF,
900                                           unsigned IntrID) const {
901   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
902           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
903     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
904                                                   (Intrinsic::ID)IntrID);
905     if (Attr.hasFnAttribute(Attribute::ReadNone))
906       return false;
907 
908     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
909 
910     if (RsrcIntr->IsImage) {
911       Info.ptrVal = MFI->getImagePSV(
912         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
913         CI.getArgOperand(RsrcIntr->RsrcArg));
914       Info.align.reset();
915     } else {
916       Info.ptrVal = MFI->getBufferPSV(
917         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
918         CI.getArgOperand(RsrcIntr->RsrcArg));
919     }
920 
921     Info.flags = MachineMemOperand::MODereferenceable;
922     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
923       Info.opc = ISD::INTRINSIC_W_CHAIN;
924       // TODO: Account for dmask reducing loaded size.
925       Info.memVT = memVTFromImageReturn(CI.getType());
926       Info.flags |= MachineMemOperand::MOLoad;
927     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
928       Info.opc = ISD::INTRINSIC_VOID;
929       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
930       Info.flags |= MachineMemOperand::MOStore;
931     } else {
932       // Atomic
933       Info.opc = ISD::INTRINSIC_W_CHAIN;
934       Info.memVT = MVT::getVT(CI.getType());
935       Info.flags = MachineMemOperand::MOLoad |
936                    MachineMemOperand::MOStore |
937                    MachineMemOperand::MODereferenceable;
938 
939       // XXX - Should this be volatile without known ordering?
940       Info.flags |= MachineMemOperand::MOVolatile;
941     }
942     return true;
943   }
944 
945   switch (IntrID) {
946   case Intrinsic::amdgcn_atomic_inc:
947   case Intrinsic::amdgcn_atomic_dec:
948   case Intrinsic::amdgcn_ds_ordered_add:
949   case Intrinsic::amdgcn_ds_ordered_swap:
950   case Intrinsic::amdgcn_ds_fadd:
951   case Intrinsic::amdgcn_ds_fmin:
952   case Intrinsic::amdgcn_ds_fmax: {
953     Info.opc = ISD::INTRINSIC_W_CHAIN;
954     Info.memVT = MVT::getVT(CI.getType());
955     Info.ptrVal = CI.getOperand(0);
956     Info.align.reset();
957     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
958 
959     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
960     if (!Vol->isZero())
961       Info.flags |= MachineMemOperand::MOVolatile;
962 
963     return true;
964   }
965   case Intrinsic::amdgcn_buffer_atomic_fadd: {
966     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
967 
968     Info.opc = ISD::INTRINSIC_VOID;
969     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
970     Info.ptrVal = MFI->getBufferPSV(
971       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
972       CI.getArgOperand(1));
973     Info.align.reset();
974     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
975 
976     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
977     if (!Vol || !Vol->isZero())
978       Info.flags |= MachineMemOperand::MOVolatile;
979 
980     return true;
981   }
982   case Intrinsic::amdgcn_global_atomic_fadd: {
983     Info.opc = ISD::INTRINSIC_VOID;
984     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
985                             ->getPointerElementType());
986     Info.ptrVal = CI.getOperand(0);
987     Info.align.reset();
988     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
989 
990     return true;
991   }
992   case Intrinsic::amdgcn_ds_append:
993   case Intrinsic::amdgcn_ds_consume: {
994     Info.opc = ISD::INTRINSIC_W_CHAIN;
995     Info.memVT = MVT::getVT(CI.getType());
996     Info.ptrVal = CI.getOperand(0);
997     Info.align.reset();
998     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
999 
1000     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1001     if (!Vol->isZero())
1002       Info.flags |= MachineMemOperand::MOVolatile;
1003 
1004     return true;
1005   }
1006   case Intrinsic::amdgcn_ds_gws_init:
1007   case Intrinsic::amdgcn_ds_gws_barrier:
1008   case Intrinsic::amdgcn_ds_gws_sema_v:
1009   case Intrinsic::amdgcn_ds_gws_sema_br:
1010   case Intrinsic::amdgcn_ds_gws_sema_p:
1011   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1012     Info.opc = ISD::INTRINSIC_VOID;
1013 
1014     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1015     Info.ptrVal =
1016         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1017 
1018     // This is an abstract access, but we need to specify a type and size.
1019     Info.memVT = MVT::i32;
1020     Info.size = 4;
1021     Info.align = Align(4);
1022 
1023     Info.flags = MachineMemOperand::MOStore;
1024     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1025       Info.flags = MachineMemOperand::MOLoad;
1026     return true;
1027   }
1028   default:
1029     return false;
1030   }
1031 }
1032 
1033 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1034                                             SmallVectorImpl<Value*> &Ops,
1035                                             Type *&AccessTy) const {
1036   switch (II->getIntrinsicID()) {
1037   case Intrinsic::amdgcn_atomic_inc:
1038   case Intrinsic::amdgcn_atomic_dec:
1039   case Intrinsic::amdgcn_ds_ordered_add:
1040   case Intrinsic::amdgcn_ds_ordered_swap:
1041   case Intrinsic::amdgcn_ds_fadd:
1042   case Intrinsic::amdgcn_ds_fmin:
1043   case Intrinsic::amdgcn_ds_fmax: {
1044     Value *Ptr = II->getArgOperand(0);
1045     AccessTy = II->getType();
1046     Ops.push_back(Ptr);
1047     return true;
1048   }
1049   default:
1050     return false;
1051   }
1052 }
1053 
1054 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1055   if (!Subtarget->hasFlatInstOffsets()) {
1056     // Flat instructions do not have offsets, and only have the register
1057     // address.
1058     return AM.BaseOffs == 0 && AM.Scale == 0;
1059   }
1060 
1061   return AM.Scale == 0 &&
1062          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1063                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1064                                   /*Signed=*/false));
1065 }
1066 
1067 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1068   if (Subtarget->hasFlatGlobalInsts())
1069     return AM.Scale == 0 &&
1070            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1071                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1072                                     /*Signed=*/true));
1073 
1074   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1075       // Assume the we will use FLAT for all global memory accesses
1076       // on VI.
1077       // FIXME: This assumption is currently wrong.  On VI we still use
1078       // MUBUF instructions for the r + i addressing mode.  As currently
1079       // implemented, the MUBUF instructions only work on buffer < 4GB.
1080       // It may be possible to support > 4GB buffers with MUBUF instructions,
1081       // by setting the stride value in the resource descriptor which would
1082       // increase the size limit to (stride * 4GB).  However, this is risky,
1083       // because it has never been validated.
1084     return isLegalFlatAddressingMode(AM);
1085   }
1086 
1087   return isLegalMUBUFAddressingMode(AM);
1088 }
1089 
1090 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1091   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1092   // additionally can do r + r + i with addr64. 32-bit has more addressing
1093   // mode options. Depending on the resource constant, it can also do
1094   // (i64 r0) + (i32 r1) * (i14 i).
1095   //
1096   // Private arrays end up using a scratch buffer most of the time, so also
1097   // assume those use MUBUF instructions. Scratch loads / stores are currently
1098   // implemented as mubuf instructions with offen bit set, so slightly
1099   // different than the normal addr64.
1100   if (!isUInt<12>(AM.BaseOffs))
1101     return false;
1102 
1103   // FIXME: Since we can split immediate into soffset and immediate offset,
1104   // would it make sense to allow any immediate?
1105 
1106   switch (AM.Scale) {
1107   case 0: // r + i or just i, depending on HasBaseReg.
1108     return true;
1109   case 1:
1110     return true; // We have r + r or r + i.
1111   case 2:
1112     if (AM.HasBaseReg) {
1113       // Reject 2 * r + r.
1114       return false;
1115     }
1116 
1117     // Allow 2 * r as r + r
1118     // Or  2 * r + i is allowed as r + r + i.
1119     return true;
1120   default: // Don't allow n * r
1121     return false;
1122   }
1123 }
1124 
1125 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1126                                              const AddrMode &AM, Type *Ty,
1127                                              unsigned AS, Instruction *I) const {
1128   // No global is ever allowed as a base.
1129   if (AM.BaseGV)
1130     return false;
1131 
1132   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1133     return isLegalGlobalAddressingMode(AM);
1134 
1135   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1136       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1137       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1138     // If the offset isn't a multiple of 4, it probably isn't going to be
1139     // correctly aligned.
1140     // FIXME: Can we get the real alignment here?
1141     if (AM.BaseOffs % 4 != 0)
1142       return isLegalMUBUFAddressingMode(AM);
1143 
1144     // There are no SMRD extloads, so if we have to do a small type access we
1145     // will use a MUBUF load.
1146     // FIXME?: We also need to do this if unaligned, but we don't know the
1147     // alignment here.
1148     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1149       return isLegalGlobalAddressingMode(AM);
1150 
1151     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1152       // SMRD instructions have an 8-bit, dword offset on SI.
1153       if (!isUInt<8>(AM.BaseOffs / 4))
1154         return false;
1155     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1156       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1157       // in 8-bits, it can use a smaller encoding.
1158       if (!isUInt<32>(AM.BaseOffs / 4))
1159         return false;
1160     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1161       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1162       if (!isUInt<20>(AM.BaseOffs))
1163         return false;
1164     } else
1165       llvm_unreachable("unhandled generation");
1166 
1167     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1168       return true;
1169 
1170     if (AM.Scale == 1 && AM.HasBaseReg)
1171       return true;
1172 
1173     return false;
1174 
1175   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1176     return isLegalMUBUFAddressingMode(AM);
1177   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1178              AS == AMDGPUAS::REGION_ADDRESS) {
1179     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1180     // field.
1181     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1182     // an 8-bit dword offset but we don't know the alignment here.
1183     if (!isUInt<16>(AM.BaseOffs))
1184       return false;
1185 
1186     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1187       return true;
1188 
1189     if (AM.Scale == 1 && AM.HasBaseReg)
1190       return true;
1191 
1192     return false;
1193   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1194              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1195     // For an unknown address space, this usually means that this is for some
1196     // reason being used for pure arithmetic, and not based on some addressing
1197     // computation. We don't have instructions that compute pointers with any
1198     // addressing modes, so treat them as having no offset like flat
1199     // instructions.
1200     return isLegalFlatAddressingMode(AM);
1201   } else {
1202     llvm_unreachable("unhandled address space");
1203   }
1204 }
1205 
1206 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1207                                         const SelectionDAG &DAG) const {
1208   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1209     return (MemVT.getSizeInBits() <= 4 * 32);
1210   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1211     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1212     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1213   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1214     return (MemVT.getSizeInBits() <= 2 * 32);
1215   }
1216   return true;
1217 }
1218 
1219 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1220     unsigned Size, unsigned AddrSpace, unsigned Align,
1221     MachineMemOperand::Flags Flags, bool *IsFast) const {
1222   if (IsFast)
1223     *IsFast = false;
1224 
1225   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1226       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1227     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1228     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1229     // with adjacent offsets.
1230     bool AlignedBy4 = (Align % 4 == 0);
1231     if (IsFast)
1232       *IsFast = AlignedBy4;
1233 
1234     return AlignedBy4;
1235   }
1236 
1237   // FIXME: We have to be conservative here and assume that flat operations
1238   // will access scratch.  If we had access to the IR function, then we
1239   // could determine if any private memory was used in the function.
1240   if (!Subtarget->hasUnalignedScratchAccess() &&
1241       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1242        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1243     bool AlignedBy4 = Align >= 4;
1244     if (IsFast)
1245       *IsFast = AlignedBy4;
1246 
1247     return AlignedBy4;
1248   }
1249 
1250   if (Subtarget->hasUnalignedBufferAccess()) {
1251     // If we have an uniform constant load, it still requires using a slow
1252     // buffer instruction if unaligned.
1253     if (IsFast) {
1254       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1255                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1256         (Align % 4 == 0) : true;
1257     }
1258 
1259     return true;
1260   }
1261 
1262   // Smaller than dword value must be aligned.
1263   if (Size < 32)
1264     return false;
1265 
1266   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1267   // byte-address are ignored, thus forcing Dword alignment.
1268   // This applies to private, global, and constant memory.
1269   if (IsFast)
1270     *IsFast = true;
1271 
1272   return Size >= 32 && Align >= 4;
1273 }
1274 
1275 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1276     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1277     bool *IsFast) const {
1278   if (IsFast)
1279     *IsFast = false;
1280 
1281   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1282   // which isn't a simple VT.
1283   // Until MVT is extended to handle this, simply check for the size and
1284   // rely on the condition below: allow accesses if the size is a multiple of 4.
1285   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1286                            VT.getStoreSize() > 16)) {
1287     return false;
1288   }
1289 
1290   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1291                                             Align, Flags, IsFast);
1292 }
1293 
1294 EVT SITargetLowering::getOptimalMemOpType(
1295     const MemOp &Op, const AttributeList &FuncAttributes) const {
1296   // FIXME: Should account for address space here.
1297 
1298   // The default fallback uses the private pointer size as a guess for a type to
1299   // use. Make sure we switch these to 64-bit accesses.
1300 
1301   if (Op.size() >= 16 &&
1302       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1303     return MVT::v4i32;
1304 
1305   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1306     return MVT::v2i32;
1307 
1308   // Use the default.
1309   return MVT::Other;
1310 }
1311 
1312 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1313                                            unsigned DestAS) const {
1314   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1315 }
1316 
1317 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1318   const MemSDNode *MemNode = cast<MemSDNode>(N);
1319   const Value *Ptr = MemNode->getMemOperand()->getValue();
1320   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1321   return I && I->getMetadata("amdgpu.noclobber");
1322 }
1323 
1324 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1325                                            unsigned DestAS) const {
1326   // Flat -> private/local is a simple truncate.
1327   // Flat -> global is no-op
1328   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1329     return true;
1330 
1331   return isNoopAddrSpaceCast(SrcAS, DestAS);
1332 }
1333 
1334 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1335   const MemSDNode *MemNode = cast<MemSDNode>(N);
1336 
1337   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1338 }
1339 
1340 TargetLoweringBase::LegalizeTypeAction
1341 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1342   int NumElts = VT.getVectorNumElements();
1343   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1344     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1345   return TargetLoweringBase::getPreferredVectorAction(VT);
1346 }
1347 
1348 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1349                                                          Type *Ty) const {
1350   // FIXME: Could be smarter if called for vector constants.
1351   return true;
1352 }
1353 
1354 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1355   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1356     switch (Op) {
1357     case ISD::LOAD:
1358     case ISD::STORE:
1359 
1360     // These operations are done with 32-bit instructions anyway.
1361     case ISD::AND:
1362     case ISD::OR:
1363     case ISD::XOR:
1364     case ISD::SELECT:
1365       // TODO: Extensions?
1366       return true;
1367     default:
1368       return false;
1369     }
1370   }
1371 
1372   // SimplifySetCC uses this function to determine whether or not it should
1373   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1374   if (VT == MVT::i1 && Op == ISD::SETCC)
1375     return false;
1376 
1377   return TargetLowering::isTypeDesirableForOp(Op, VT);
1378 }
1379 
1380 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1381                                                    const SDLoc &SL,
1382                                                    SDValue Chain,
1383                                                    uint64_t Offset) const {
1384   const DataLayout &DL = DAG.getDataLayout();
1385   MachineFunction &MF = DAG.getMachineFunction();
1386   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1387 
1388   const ArgDescriptor *InputPtrReg;
1389   const TargetRegisterClass *RC;
1390 
1391   std::tie(InputPtrReg, RC)
1392     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1393 
1394   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1395   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1396   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1397     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1398 
1399   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1400 }
1401 
1402 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1403                                             const SDLoc &SL) const {
1404   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1405                                                FIRST_IMPLICIT);
1406   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1407 }
1408 
1409 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1410                                          const SDLoc &SL, SDValue Val,
1411                                          bool Signed,
1412                                          const ISD::InputArg *Arg) const {
1413   // First, if it is a widened vector, narrow it.
1414   if (VT.isVector() &&
1415       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1416     EVT NarrowedVT =
1417         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1418                          VT.getVectorNumElements());
1419     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1420                       DAG.getConstant(0, SL, MVT::i32));
1421   }
1422 
1423   // Then convert the vector elements or scalar value.
1424   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1425       VT.bitsLT(MemVT)) {
1426     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1427     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1428   }
1429 
1430   if (MemVT.isFloatingPoint())
1431     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1432   else if (Signed)
1433     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1434   else
1435     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1436 
1437   return Val;
1438 }
1439 
1440 SDValue SITargetLowering::lowerKernargMemParameter(
1441   SelectionDAG &DAG, EVT VT, EVT MemVT,
1442   const SDLoc &SL, SDValue Chain,
1443   uint64_t Offset, unsigned Align, bool Signed,
1444   const ISD::InputArg *Arg) const {
1445   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1446 
1447   // Try to avoid using an extload by loading earlier than the argument address,
1448   // and extracting the relevant bits. The load should hopefully be merged with
1449   // the previous argument.
1450   if (MemVT.getStoreSize() < 4 && Align < 4) {
1451     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1452     int64_t AlignDownOffset = alignDown(Offset, 4);
1453     int64_t OffsetDiff = Offset - AlignDownOffset;
1454 
1455     EVT IntVT = MemVT.changeTypeToInteger();
1456 
1457     // TODO: If we passed in the base kernel offset we could have a better
1458     // alignment than 4, but we don't really need it.
1459     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1460     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1461                                MachineMemOperand::MODereferenceable |
1462                                MachineMemOperand::MOInvariant);
1463 
1464     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1465     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1466 
1467     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1468     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1469     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1470 
1471 
1472     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1473   }
1474 
1475   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1476   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1477                              MachineMemOperand::MODereferenceable |
1478                              MachineMemOperand::MOInvariant);
1479 
1480   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1481   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1482 }
1483 
1484 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1485                                               const SDLoc &SL, SDValue Chain,
1486                                               const ISD::InputArg &Arg) const {
1487   MachineFunction &MF = DAG.getMachineFunction();
1488   MachineFrameInfo &MFI = MF.getFrameInfo();
1489 
1490   if (Arg.Flags.isByVal()) {
1491     unsigned Size = Arg.Flags.getByValSize();
1492     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1493     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1494   }
1495 
1496   unsigned ArgOffset = VA.getLocMemOffset();
1497   unsigned ArgSize = VA.getValVT().getStoreSize();
1498 
1499   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1500 
1501   // Create load nodes to retrieve arguments from the stack.
1502   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1503   SDValue ArgValue;
1504 
1505   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1506   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1507   MVT MemVT = VA.getValVT();
1508 
1509   switch (VA.getLocInfo()) {
1510   default:
1511     break;
1512   case CCValAssign::BCvt:
1513     MemVT = VA.getLocVT();
1514     break;
1515   case CCValAssign::SExt:
1516     ExtType = ISD::SEXTLOAD;
1517     break;
1518   case CCValAssign::ZExt:
1519     ExtType = ISD::ZEXTLOAD;
1520     break;
1521   case CCValAssign::AExt:
1522     ExtType = ISD::EXTLOAD;
1523     break;
1524   }
1525 
1526   ArgValue = DAG.getExtLoad(
1527     ExtType, SL, VA.getLocVT(), Chain, FIN,
1528     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1529     MemVT);
1530   return ArgValue;
1531 }
1532 
1533 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1534   const SIMachineFunctionInfo &MFI,
1535   EVT VT,
1536   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1537   const ArgDescriptor *Reg;
1538   const TargetRegisterClass *RC;
1539 
1540   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1541   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1542 }
1543 
1544 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1545                                    CallingConv::ID CallConv,
1546                                    ArrayRef<ISD::InputArg> Ins,
1547                                    BitVector &Skipped,
1548                                    FunctionType *FType,
1549                                    SIMachineFunctionInfo *Info) {
1550   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1551     const ISD::InputArg *Arg = &Ins[I];
1552 
1553     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1554            "vector type argument should have been split");
1555 
1556     // First check if it's a PS input addr.
1557     if (CallConv == CallingConv::AMDGPU_PS &&
1558         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1559       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1560 
1561       // Inconveniently only the first part of the split is marked as isSplit,
1562       // so skip to the end. We only want to increment PSInputNum once for the
1563       // entire split argument.
1564       if (Arg->Flags.isSplit()) {
1565         while (!Arg->Flags.isSplitEnd()) {
1566           assert((!Arg->VT.isVector() ||
1567                   Arg->VT.getScalarSizeInBits() == 16) &&
1568                  "unexpected vector split in ps argument type");
1569           if (!SkipArg)
1570             Splits.push_back(*Arg);
1571           Arg = &Ins[++I];
1572         }
1573       }
1574 
1575       if (SkipArg) {
1576         // We can safely skip PS inputs.
1577         Skipped.set(Arg->getOrigArgIndex());
1578         ++PSInputNum;
1579         continue;
1580       }
1581 
1582       Info->markPSInputAllocated(PSInputNum);
1583       if (Arg->Used)
1584         Info->markPSInputEnabled(PSInputNum);
1585 
1586       ++PSInputNum;
1587     }
1588 
1589     Splits.push_back(*Arg);
1590   }
1591 }
1592 
1593 // Allocate special inputs passed in VGPRs.
1594 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1595                                                       MachineFunction &MF,
1596                                                       const SIRegisterInfo &TRI,
1597                                                       SIMachineFunctionInfo &Info) const {
1598   const LLT S32 = LLT::scalar(32);
1599   MachineRegisterInfo &MRI = MF.getRegInfo();
1600 
1601   if (Info.hasWorkItemIDX()) {
1602     Register Reg = AMDGPU::VGPR0;
1603     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1604 
1605     CCInfo.AllocateReg(Reg);
1606     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1607   }
1608 
1609   if (Info.hasWorkItemIDY()) {
1610     Register Reg = AMDGPU::VGPR1;
1611     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1612 
1613     CCInfo.AllocateReg(Reg);
1614     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1615   }
1616 
1617   if (Info.hasWorkItemIDZ()) {
1618     Register Reg = AMDGPU::VGPR2;
1619     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1620 
1621     CCInfo.AllocateReg(Reg);
1622     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1623   }
1624 }
1625 
1626 // Try to allocate a VGPR at the end of the argument list, or if no argument
1627 // VGPRs are left allocating a stack slot.
1628 // If \p Mask is is given it indicates bitfield position in the register.
1629 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1630 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1631                                          ArgDescriptor Arg = ArgDescriptor()) {
1632   if (Arg.isSet())
1633     return ArgDescriptor::createArg(Arg, Mask);
1634 
1635   ArrayRef<MCPhysReg> ArgVGPRs
1636     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1637   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1638   if (RegIdx == ArgVGPRs.size()) {
1639     // Spill to stack required.
1640     int64_t Offset = CCInfo.AllocateStack(4, 4);
1641 
1642     return ArgDescriptor::createStack(Offset, Mask);
1643   }
1644 
1645   unsigned Reg = ArgVGPRs[RegIdx];
1646   Reg = CCInfo.AllocateReg(Reg);
1647   assert(Reg != AMDGPU::NoRegister);
1648 
1649   MachineFunction &MF = CCInfo.getMachineFunction();
1650   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1651   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1652   return ArgDescriptor::createRegister(Reg, Mask);
1653 }
1654 
1655 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1656                                              const TargetRegisterClass *RC,
1657                                              unsigned NumArgRegs) {
1658   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1659   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1660   if (RegIdx == ArgSGPRs.size())
1661     report_fatal_error("ran out of SGPRs for arguments");
1662 
1663   unsigned Reg = ArgSGPRs[RegIdx];
1664   Reg = CCInfo.AllocateReg(Reg);
1665   assert(Reg != AMDGPU::NoRegister);
1666 
1667   MachineFunction &MF = CCInfo.getMachineFunction();
1668   MF.addLiveIn(Reg, RC);
1669   return ArgDescriptor::createRegister(Reg);
1670 }
1671 
1672 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1673   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1674 }
1675 
1676 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1677   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1678 }
1679 
1680 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo,
1681                                                  MachineFunction &MF,
1682                                                  const SIRegisterInfo &TRI,
1683                                                  SIMachineFunctionInfo &Info) const {
1684   const unsigned Mask = 0x3ff;
1685   ArgDescriptor Arg;
1686 
1687   if (Info.hasWorkItemIDX()) {
1688     Arg = allocateVGPR32Input(CCInfo, Mask);
1689     Info.setWorkItemIDX(Arg);
1690   }
1691 
1692   if (Info.hasWorkItemIDY()) {
1693     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1694     Info.setWorkItemIDY(Arg);
1695   }
1696 
1697   if (Info.hasWorkItemIDZ())
1698     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1699 }
1700 
1701 void SITargetLowering::allocateSpecialInputSGPRs(
1702   CCState &CCInfo,
1703   MachineFunction &MF,
1704   const SIRegisterInfo &TRI,
1705   SIMachineFunctionInfo &Info) const {
1706   auto &ArgInfo = Info.getArgInfo();
1707 
1708   // TODO: Unify handling with private memory pointers.
1709 
1710   if (Info.hasDispatchPtr())
1711     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1712 
1713   if (Info.hasQueuePtr())
1714     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1715 
1716   if (Info.hasKernargSegmentPtr())
1717     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1718 
1719   if (Info.hasDispatchID())
1720     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1721 
1722   // flat_scratch_init is not applicable for non-kernel functions.
1723 
1724   if (Info.hasWorkGroupIDX())
1725     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1726 
1727   if (Info.hasWorkGroupIDY())
1728     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1729 
1730   if (Info.hasWorkGroupIDZ())
1731     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1732 
1733   if (Info.hasImplicitArgPtr())
1734     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1735 }
1736 
1737 // Allocate special inputs passed in user SGPRs.
1738 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1739                                             MachineFunction &MF,
1740                                             const SIRegisterInfo &TRI,
1741                                             SIMachineFunctionInfo &Info) const {
1742   if (Info.hasImplicitBufferPtr()) {
1743     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1744     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1745     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1746   }
1747 
1748   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1749   if (Info.hasPrivateSegmentBuffer()) {
1750     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1751     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1752     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1753   }
1754 
1755   if (Info.hasDispatchPtr()) {
1756     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1757     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1758     CCInfo.AllocateReg(DispatchPtrReg);
1759   }
1760 
1761   if (Info.hasQueuePtr()) {
1762     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1763     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1764     CCInfo.AllocateReg(QueuePtrReg);
1765   }
1766 
1767   if (Info.hasKernargSegmentPtr()) {
1768     MachineRegisterInfo &MRI = MF.getRegInfo();
1769     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1770     CCInfo.AllocateReg(InputPtrReg);
1771 
1772     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1773     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1774   }
1775 
1776   if (Info.hasDispatchID()) {
1777     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1778     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1779     CCInfo.AllocateReg(DispatchIDReg);
1780   }
1781 
1782   if (Info.hasFlatScratchInit()) {
1783     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1784     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1785     CCInfo.AllocateReg(FlatScratchInitReg);
1786   }
1787 
1788   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1789   // these from the dispatch pointer.
1790 }
1791 
1792 // Allocate special input registers that are initialized per-wave.
1793 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1794                                            MachineFunction &MF,
1795                                            SIMachineFunctionInfo &Info,
1796                                            CallingConv::ID CallConv,
1797                                            bool IsShader) const {
1798   if (Info.hasWorkGroupIDX()) {
1799     unsigned Reg = Info.addWorkGroupIDX();
1800     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1801     CCInfo.AllocateReg(Reg);
1802   }
1803 
1804   if (Info.hasWorkGroupIDY()) {
1805     unsigned Reg = Info.addWorkGroupIDY();
1806     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1807     CCInfo.AllocateReg(Reg);
1808   }
1809 
1810   if (Info.hasWorkGroupIDZ()) {
1811     unsigned Reg = Info.addWorkGroupIDZ();
1812     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1813     CCInfo.AllocateReg(Reg);
1814   }
1815 
1816   if (Info.hasWorkGroupInfo()) {
1817     unsigned Reg = Info.addWorkGroupInfo();
1818     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1819     CCInfo.AllocateReg(Reg);
1820   }
1821 
1822   if (Info.hasPrivateSegmentWaveByteOffset()) {
1823     // Scratch wave offset passed in system SGPR.
1824     unsigned PrivateSegmentWaveByteOffsetReg;
1825 
1826     if (IsShader) {
1827       PrivateSegmentWaveByteOffsetReg =
1828         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1829 
1830       // This is true if the scratch wave byte offset doesn't have a fixed
1831       // location.
1832       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1833         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1834         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1835       }
1836     } else
1837       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1838 
1839     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1840     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1841   }
1842 }
1843 
1844 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1845                                      MachineFunction &MF,
1846                                      const SIRegisterInfo &TRI,
1847                                      SIMachineFunctionInfo &Info) {
1848   // Now that we've figured out where the scratch register inputs are, see if
1849   // should reserve the arguments and use them directly.
1850   MachineFrameInfo &MFI = MF.getFrameInfo();
1851   bool HasStackObjects = MFI.hasStackObjects();
1852   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1853 
1854   // Record that we know we have non-spill stack objects so we don't need to
1855   // check all stack objects later.
1856   if (HasStackObjects)
1857     Info.setHasNonSpillStackObjects(true);
1858 
1859   // Everything live out of a block is spilled with fast regalloc, so it's
1860   // almost certain that spilling will be required.
1861   if (TM.getOptLevel() == CodeGenOpt::None)
1862     HasStackObjects = true;
1863 
1864   // For now assume stack access is needed in any callee functions, so we need
1865   // the scratch registers to pass in.
1866   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1867 
1868   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1869     // If we have stack objects, we unquestionably need the private buffer
1870     // resource. For the Code Object V2 ABI, this will be the first 4 user
1871     // SGPR inputs. We can reserve those and use them directly.
1872 
1873     Register PrivateSegmentBufferReg =
1874         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1875     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1876   } else {
1877     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1878     // We tentatively reserve the last registers (skipping the last registers
1879     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1880     // we'll replace these with the ones immediately after those which were
1881     // really allocated. In the prologue copies will be inserted from the
1882     // argument to these reserved registers.
1883 
1884     // Without HSA, relocations are used for the scratch pointer and the
1885     // buffer resource setup is always inserted in the prologue. Scratch wave
1886     // offset is still in an input SGPR.
1887     Info.setScratchRSrcReg(ReservedBufferReg);
1888   }
1889 
1890   // hasFP should be accurate for kernels even before the frame is finalized.
1891   if (ST.getFrameLowering()->hasFP(MF)) {
1892     MachineRegisterInfo &MRI = MF.getRegInfo();
1893 
1894     // Try to use s32 as the SP, but move it if it would interfere with input
1895     // arguments. This won't work with calls though.
1896     //
1897     // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1898     // registers.
1899     if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1900       Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1901     } else {
1902       assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1903 
1904       if (MFI.hasCalls())
1905         report_fatal_error("call in graphics shader with too many input SGPRs");
1906 
1907       for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1908         if (!MRI.isLiveIn(Reg)) {
1909           Info.setStackPtrOffsetReg(Reg);
1910           break;
1911         }
1912       }
1913 
1914       if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1915         report_fatal_error("failed to find register for SP");
1916     }
1917 
1918     if (MFI.hasCalls()) {
1919       Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
1920       Info.setFrameOffsetReg(AMDGPU::SGPR33);
1921     } else {
1922       unsigned ReservedOffsetReg =
1923         TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1924       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1925       Info.setFrameOffsetReg(ReservedOffsetReg);
1926     }
1927   } else if (RequiresStackAccess) {
1928     assert(!MFI.hasCalls());
1929     // We know there are accesses and they will be done relative to SP, so just
1930     // pin it to the input.
1931     //
1932     // FIXME: Should not do this if inline asm is reading/writing these
1933     // registers.
1934     Register PreloadedSP = Info.getPreloadedReg(
1935         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1936 
1937     Info.setStackPtrOffsetReg(PreloadedSP);
1938     Info.setScratchWaveOffsetReg(PreloadedSP);
1939     Info.setFrameOffsetReg(PreloadedSP);
1940   } else {
1941     assert(!MFI.hasCalls());
1942 
1943     // There may not be stack access at all. There may still be spills, or
1944     // access of a constant pointer (in which cases an extra copy will be
1945     // emitted in the prolog).
1946     unsigned ReservedOffsetReg
1947       = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1948     Info.setStackPtrOffsetReg(ReservedOffsetReg);
1949     Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1950     Info.setFrameOffsetReg(ReservedOffsetReg);
1951   }
1952 }
1953 
1954 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1955   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1956   return !Info->isEntryFunction();
1957 }
1958 
1959 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1960 
1961 }
1962 
1963 void SITargetLowering::insertCopiesSplitCSR(
1964   MachineBasicBlock *Entry,
1965   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1966   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1967 
1968   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1969   if (!IStart)
1970     return;
1971 
1972   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1973   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1974   MachineBasicBlock::iterator MBBI = Entry->begin();
1975   for (const MCPhysReg *I = IStart; *I; ++I) {
1976     const TargetRegisterClass *RC = nullptr;
1977     if (AMDGPU::SReg_64RegClass.contains(*I))
1978       RC = &AMDGPU::SGPR_64RegClass;
1979     else if (AMDGPU::SReg_32RegClass.contains(*I))
1980       RC = &AMDGPU::SGPR_32RegClass;
1981     else
1982       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1983 
1984     Register NewVR = MRI->createVirtualRegister(RC);
1985     // Create copy from CSR to a virtual register.
1986     Entry->addLiveIn(*I);
1987     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1988       .addReg(*I);
1989 
1990     // Insert the copy-back instructions right before the terminator.
1991     for (auto *Exit : Exits)
1992       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1993               TII->get(TargetOpcode::COPY), *I)
1994         .addReg(NewVR);
1995   }
1996 }
1997 
1998 SDValue SITargetLowering::LowerFormalArguments(
1999     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2000     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2001     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2002   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2003 
2004   MachineFunction &MF = DAG.getMachineFunction();
2005   const Function &Fn = MF.getFunction();
2006   FunctionType *FType = MF.getFunction().getFunctionType();
2007   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2008 
2009   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2010     DiagnosticInfoUnsupported NoGraphicsHSA(
2011         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2012     DAG.getContext()->diagnose(NoGraphicsHSA);
2013     return DAG.getEntryNode();
2014   }
2015 
2016   SmallVector<ISD::InputArg, 16> Splits;
2017   SmallVector<CCValAssign, 16> ArgLocs;
2018   BitVector Skipped(Ins.size());
2019   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2020                  *DAG.getContext());
2021 
2022   bool IsShader = AMDGPU::isShader(CallConv);
2023   bool IsKernel = AMDGPU::isKernel(CallConv);
2024   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2025 
2026   if (IsShader) {
2027     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2028 
2029     // At least one interpolation mode must be enabled or else the GPU will
2030     // hang.
2031     //
2032     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2033     // set PSInputAddr, the user wants to enable some bits after the compilation
2034     // based on run-time states. Since we can't know what the final PSInputEna
2035     // will look like, so we shouldn't do anything here and the user should take
2036     // responsibility for the correct programming.
2037     //
2038     // Otherwise, the following restrictions apply:
2039     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2040     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2041     //   enabled too.
2042     if (CallConv == CallingConv::AMDGPU_PS) {
2043       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2044            ((Info->getPSInputAddr() & 0xF) == 0 &&
2045             Info->isPSInputAllocated(11))) {
2046         CCInfo.AllocateReg(AMDGPU::VGPR0);
2047         CCInfo.AllocateReg(AMDGPU::VGPR1);
2048         Info->markPSInputAllocated(0);
2049         Info->markPSInputEnabled(0);
2050       }
2051       if (Subtarget->isAmdPalOS()) {
2052         // For isAmdPalOS, the user does not enable some bits after compilation
2053         // based on run-time states; the register values being generated here are
2054         // the final ones set in hardware. Therefore we need to apply the
2055         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2056         // a bit is set in PSInputAddr but not PSInputEnable is where the
2057         // frontend set up an input arg for a particular interpolation mode, but
2058         // nothing uses that input arg. Really we should have an earlier pass
2059         // that removes such an arg.)
2060         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2061         if ((PsInputBits & 0x7F) == 0 ||
2062             ((PsInputBits & 0xF) == 0 &&
2063              (PsInputBits >> 11 & 1)))
2064           Info->markPSInputEnabled(
2065               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2066       }
2067     }
2068 
2069     assert(!Info->hasDispatchPtr() &&
2070            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2071            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2072            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2073            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2074            !Info->hasWorkItemIDZ());
2075   } else if (IsKernel) {
2076     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2077   } else {
2078     Splits.append(Ins.begin(), Ins.end());
2079   }
2080 
2081   if (IsEntryFunc) {
2082     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2083     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2084   }
2085 
2086   if (IsKernel) {
2087     analyzeFormalArgumentsCompute(CCInfo, Ins);
2088   } else {
2089     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2090     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2091   }
2092 
2093   SmallVector<SDValue, 16> Chains;
2094 
2095   // FIXME: This is the minimum kernel argument alignment. We should improve
2096   // this to the maximum alignment of the arguments.
2097   //
2098   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2099   // kern arg offset.
2100   const unsigned KernelArgBaseAlign = 16;
2101 
2102    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2103     const ISD::InputArg &Arg = Ins[i];
2104     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2105       InVals.push_back(DAG.getUNDEF(Arg.VT));
2106       continue;
2107     }
2108 
2109     CCValAssign &VA = ArgLocs[ArgIdx++];
2110     MVT VT = VA.getLocVT();
2111 
2112     if (IsEntryFunc && VA.isMemLoc()) {
2113       VT = Ins[i].VT;
2114       EVT MemVT = VA.getLocVT();
2115 
2116       const uint64_t Offset = VA.getLocMemOffset();
2117       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2118 
2119       SDValue Arg = lowerKernargMemParameter(
2120         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2121       Chains.push_back(Arg.getValue(1));
2122 
2123       auto *ParamTy =
2124         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2125       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2126           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2127                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2128         // On SI local pointers are just offsets into LDS, so they are always
2129         // less than 16-bits.  On CI and newer they could potentially be
2130         // real pointers, so we can't guarantee their size.
2131         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2132                           DAG.getValueType(MVT::i16));
2133       }
2134 
2135       InVals.push_back(Arg);
2136       continue;
2137     } else if (!IsEntryFunc && VA.isMemLoc()) {
2138       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2139       InVals.push_back(Val);
2140       if (!Arg.Flags.isByVal())
2141         Chains.push_back(Val.getValue(1));
2142       continue;
2143     }
2144 
2145     assert(VA.isRegLoc() && "Parameter must be in a register!");
2146 
2147     Register Reg = VA.getLocReg();
2148     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2149     EVT ValVT = VA.getValVT();
2150 
2151     Reg = MF.addLiveIn(Reg, RC);
2152     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2153 
2154     if (Arg.Flags.isSRet()) {
2155       // The return object should be reasonably addressable.
2156 
2157       // FIXME: This helps when the return is a real sret. If it is a
2158       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2159       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2160       unsigned NumBits
2161         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2162       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2163         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2164     }
2165 
2166     // If this is an 8 or 16-bit value, it is really passed promoted
2167     // to 32 bits. Insert an assert[sz]ext to capture this, then
2168     // truncate to the right size.
2169     switch (VA.getLocInfo()) {
2170     case CCValAssign::Full:
2171       break;
2172     case CCValAssign::BCvt:
2173       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2174       break;
2175     case CCValAssign::SExt:
2176       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2177                         DAG.getValueType(ValVT));
2178       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2179       break;
2180     case CCValAssign::ZExt:
2181       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2182                         DAG.getValueType(ValVT));
2183       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2184       break;
2185     case CCValAssign::AExt:
2186       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2187       break;
2188     default:
2189       llvm_unreachable("Unknown loc info!");
2190     }
2191 
2192     InVals.push_back(Val);
2193   }
2194 
2195   if (!IsEntryFunc) {
2196     // Special inputs come after user arguments.
2197     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2198   }
2199 
2200   // Start adding system SGPRs.
2201   if (IsEntryFunc) {
2202     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2203   } else {
2204     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2205     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2206     CCInfo.AllocateReg(Info->getFrameOffsetReg());
2207     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2208   }
2209 
2210   auto &ArgUsageInfo =
2211     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2212   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2213 
2214   unsigned StackArgSize = CCInfo.getNextStackOffset();
2215   Info->setBytesInStackArgArea(StackArgSize);
2216 
2217   return Chains.empty() ? Chain :
2218     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2219 }
2220 
2221 // TODO: If return values can't fit in registers, we should return as many as
2222 // possible in registers before passing on stack.
2223 bool SITargetLowering::CanLowerReturn(
2224   CallingConv::ID CallConv,
2225   MachineFunction &MF, bool IsVarArg,
2226   const SmallVectorImpl<ISD::OutputArg> &Outs,
2227   LLVMContext &Context) const {
2228   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2229   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2230   // for shaders. Vector types should be explicitly handled by CC.
2231   if (AMDGPU::isEntryFunctionCC(CallConv))
2232     return true;
2233 
2234   SmallVector<CCValAssign, 16> RVLocs;
2235   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2236   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2237 }
2238 
2239 SDValue
2240 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2241                               bool isVarArg,
2242                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2243                               const SmallVectorImpl<SDValue> &OutVals,
2244                               const SDLoc &DL, SelectionDAG &DAG) const {
2245   MachineFunction &MF = DAG.getMachineFunction();
2246   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2247 
2248   if (AMDGPU::isKernel(CallConv)) {
2249     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2250                                              OutVals, DL, DAG);
2251   }
2252 
2253   bool IsShader = AMDGPU::isShader(CallConv);
2254 
2255   Info->setIfReturnsVoid(Outs.empty());
2256   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2257 
2258   // CCValAssign - represent the assignment of the return value to a location.
2259   SmallVector<CCValAssign, 48> RVLocs;
2260   SmallVector<ISD::OutputArg, 48> Splits;
2261 
2262   // CCState - Info about the registers and stack slots.
2263   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2264                  *DAG.getContext());
2265 
2266   // Analyze outgoing return values.
2267   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2268 
2269   SDValue Flag;
2270   SmallVector<SDValue, 48> RetOps;
2271   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2272 
2273   // Add return address for callable functions.
2274   if (!Info->isEntryFunction()) {
2275     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2276     SDValue ReturnAddrReg = CreateLiveInRegister(
2277       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2278 
2279     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2280         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2281         MVT::i64);
2282     Chain =
2283         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2284     Flag = Chain.getValue(1);
2285     RetOps.push_back(ReturnAddrVirtualReg);
2286   }
2287 
2288   // Copy the result values into the output registers.
2289   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2290        ++I, ++RealRVLocIdx) {
2291     CCValAssign &VA = RVLocs[I];
2292     assert(VA.isRegLoc() && "Can only return in registers!");
2293     // TODO: Partially return in registers if return values don't fit.
2294     SDValue Arg = OutVals[RealRVLocIdx];
2295 
2296     // Copied from other backends.
2297     switch (VA.getLocInfo()) {
2298     case CCValAssign::Full:
2299       break;
2300     case CCValAssign::BCvt:
2301       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2302       break;
2303     case CCValAssign::SExt:
2304       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2305       break;
2306     case CCValAssign::ZExt:
2307       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2308       break;
2309     case CCValAssign::AExt:
2310       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2311       break;
2312     default:
2313       llvm_unreachable("Unknown loc info!");
2314     }
2315 
2316     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2317     Flag = Chain.getValue(1);
2318     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2319   }
2320 
2321   // FIXME: Does sret work properly?
2322   if (!Info->isEntryFunction()) {
2323     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2324     const MCPhysReg *I =
2325       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2326     if (I) {
2327       for (; *I; ++I) {
2328         if (AMDGPU::SReg_64RegClass.contains(*I))
2329           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2330         else if (AMDGPU::SReg_32RegClass.contains(*I))
2331           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2332         else
2333           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2334       }
2335     }
2336   }
2337 
2338   // Update chain and glue.
2339   RetOps[0] = Chain;
2340   if (Flag.getNode())
2341     RetOps.push_back(Flag);
2342 
2343   unsigned Opc = AMDGPUISD::ENDPGM;
2344   if (!IsWaveEnd)
2345     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2346   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2347 }
2348 
2349 SDValue SITargetLowering::LowerCallResult(
2350     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2351     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2352     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2353     SDValue ThisVal) const {
2354   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2355 
2356   // Assign locations to each value returned by this call.
2357   SmallVector<CCValAssign, 16> RVLocs;
2358   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2359                  *DAG.getContext());
2360   CCInfo.AnalyzeCallResult(Ins, RetCC);
2361 
2362   // Copy all of the result registers out of their specified physreg.
2363   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2364     CCValAssign VA = RVLocs[i];
2365     SDValue Val;
2366 
2367     if (VA.isRegLoc()) {
2368       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2369       Chain = Val.getValue(1);
2370       InFlag = Val.getValue(2);
2371     } else if (VA.isMemLoc()) {
2372       report_fatal_error("TODO: return values in memory");
2373     } else
2374       llvm_unreachable("unknown argument location type");
2375 
2376     switch (VA.getLocInfo()) {
2377     case CCValAssign::Full:
2378       break;
2379     case CCValAssign::BCvt:
2380       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2381       break;
2382     case CCValAssign::ZExt:
2383       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2384                         DAG.getValueType(VA.getValVT()));
2385       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2386       break;
2387     case CCValAssign::SExt:
2388       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2389                         DAG.getValueType(VA.getValVT()));
2390       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2391       break;
2392     case CCValAssign::AExt:
2393       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2394       break;
2395     default:
2396       llvm_unreachable("Unknown loc info!");
2397     }
2398 
2399     InVals.push_back(Val);
2400   }
2401 
2402   return Chain;
2403 }
2404 
2405 // Add code to pass special inputs required depending on used features separate
2406 // from the explicit user arguments present in the IR.
2407 void SITargetLowering::passSpecialInputs(
2408     CallLoweringInfo &CLI,
2409     CCState &CCInfo,
2410     const SIMachineFunctionInfo &Info,
2411     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2412     SmallVectorImpl<SDValue> &MemOpChains,
2413     SDValue Chain) const {
2414   // If we don't have a call site, this was a call inserted by
2415   // legalization. These can never use special inputs.
2416   if (!CLI.CS)
2417     return;
2418 
2419   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2420   assert(CalleeFunc);
2421 
2422   SelectionDAG &DAG = CLI.DAG;
2423   const SDLoc &DL = CLI.DL;
2424 
2425   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2426 
2427   auto &ArgUsageInfo =
2428     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2429   const AMDGPUFunctionArgInfo &CalleeArgInfo
2430     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2431 
2432   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2433 
2434   // TODO: Unify with private memory register handling. This is complicated by
2435   // the fact that at least in kernels, the input argument is not necessarily
2436   // in the same location as the input.
2437   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2438     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2439     AMDGPUFunctionArgInfo::QUEUE_PTR,
2440     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2441     AMDGPUFunctionArgInfo::DISPATCH_ID,
2442     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2443     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2444     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2445     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2446   };
2447 
2448   for (auto InputID : InputRegs) {
2449     const ArgDescriptor *OutgoingArg;
2450     const TargetRegisterClass *ArgRC;
2451 
2452     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2453     if (!OutgoingArg)
2454       continue;
2455 
2456     const ArgDescriptor *IncomingArg;
2457     const TargetRegisterClass *IncomingArgRC;
2458     std::tie(IncomingArg, IncomingArgRC)
2459       = CallerArgInfo.getPreloadedValue(InputID);
2460     assert(IncomingArgRC == ArgRC);
2461 
2462     // All special arguments are ints for now.
2463     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2464     SDValue InputReg;
2465 
2466     if (IncomingArg) {
2467       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2468     } else {
2469       // The implicit arg ptr is special because it doesn't have a corresponding
2470       // input for kernels, and is computed from the kernarg segment pointer.
2471       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2472       InputReg = getImplicitArgPtr(DAG, DL);
2473     }
2474 
2475     if (OutgoingArg->isRegister()) {
2476       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2477     } else {
2478       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2479       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2480                                               SpecialArgOffset);
2481       MemOpChains.push_back(ArgStore);
2482     }
2483   }
2484 
2485   // Pack workitem IDs into a single register or pass it as is if already
2486   // packed.
2487   const ArgDescriptor *OutgoingArg;
2488   const TargetRegisterClass *ArgRC;
2489 
2490   std::tie(OutgoingArg, ArgRC) =
2491     CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2492   if (!OutgoingArg)
2493     std::tie(OutgoingArg, ArgRC) =
2494       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2495   if (!OutgoingArg)
2496     std::tie(OutgoingArg, ArgRC) =
2497       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2498   if (!OutgoingArg)
2499     return;
2500 
2501   const ArgDescriptor *IncomingArgX
2502     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2503   const ArgDescriptor *IncomingArgY
2504     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2505   const ArgDescriptor *IncomingArgZ
2506     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2507 
2508   SDValue InputReg;
2509   SDLoc SL;
2510 
2511   // If incoming ids are not packed we need to pack them.
2512   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX)
2513     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2514 
2515   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) {
2516     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2517     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2518                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2519     InputReg = InputReg.getNode() ?
2520                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2521   }
2522 
2523   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) {
2524     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2525     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2526                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2527     InputReg = InputReg.getNode() ?
2528                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2529   }
2530 
2531   if (!InputReg.getNode()) {
2532     // Workitem ids are already packed, any of present incoming arguments
2533     // will carry all required fields.
2534     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2535       IncomingArgX ? *IncomingArgX :
2536       IncomingArgY ? *IncomingArgY :
2537                      *IncomingArgZ, ~0u);
2538     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2539   }
2540 
2541   if (OutgoingArg->isRegister()) {
2542     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2543   } else {
2544     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2545     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2546                                             SpecialArgOffset);
2547     MemOpChains.push_back(ArgStore);
2548   }
2549 }
2550 
2551 static bool canGuaranteeTCO(CallingConv::ID CC) {
2552   return CC == CallingConv::Fast;
2553 }
2554 
2555 /// Return true if we might ever do TCO for calls with this calling convention.
2556 static bool mayTailCallThisCC(CallingConv::ID CC) {
2557   switch (CC) {
2558   case CallingConv::C:
2559     return true;
2560   default:
2561     return canGuaranteeTCO(CC);
2562   }
2563 }
2564 
2565 bool SITargetLowering::isEligibleForTailCallOptimization(
2566     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2567     const SmallVectorImpl<ISD::OutputArg> &Outs,
2568     const SmallVectorImpl<SDValue> &OutVals,
2569     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2570   if (!mayTailCallThisCC(CalleeCC))
2571     return false;
2572 
2573   MachineFunction &MF = DAG.getMachineFunction();
2574   const Function &CallerF = MF.getFunction();
2575   CallingConv::ID CallerCC = CallerF.getCallingConv();
2576   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2577   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2578 
2579   // Kernels aren't callable, and don't have a live in return address so it
2580   // doesn't make sense to do a tail call with entry functions.
2581   if (!CallerPreserved)
2582     return false;
2583 
2584   bool CCMatch = CallerCC == CalleeCC;
2585 
2586   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2587     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2588       return true;
2589     return false;
2590   }
2591 
2592   // TODO: Can we handle var args?
2593   if (IsVarArg)
2594     return false;
2595 
2596   for (const Argument &Arg : CallerF.args()) {
2597     if (Arg.hasByValAttr())
2598       return false;
2599   }
2600 
2601   LLVMContext &Ctx = *DAG.getContext();
2602 
2603   // Check that the call results are passed in the same way.
2604   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2605                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2606                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2607     return false;
2608 
2609   // The callee has to preserve all registers the caller needs to preserve.
2610   if (!CCMatch) {
2611     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2612     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2613       return false;
2614   }
2615 
2616   // Nothing more to check if the callee is taking no arguments.
2617   if (Outs.empty())
2618     return true;
2619 
2620   SmallVector<CCValAssign, 16> ArgLocs;
2621   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2622 
2623   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2624 
2625   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2626   // If the stack arguments for this call do not fit into our own save area then
2627   // the call cannot be made tail.
2628   // TODO: Is this really necessary?
2629   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2630     return false;
2631 
2632   const MachineRegisterInfo &MRI = MF.getRegInfo();
2633   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2634 }
2635 
2636 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2637   if (!CI->isTailCall())
2638     return false;
2639 
2640   const Function *ParentFn = CI->getParent()->getParent();
2641   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2642     return false;
2643   return true;
2644 }
2645 
2646 // The wave scratch offset register is used as the global base pointer.
2647 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2648                                     SmallVectorImpl<SDValue> &InVals) const {
2649   SelectionDAG &DAG = CLI.DAG;
2650   const SDLoc &DL = CLI.DL;
2651   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2652   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2653   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2654   SDValue Chain = CLI.Chain;
2655   SDValue Callee = CLI.Callee;
2656   bool &IsTailCall = CLI.IsTailCall;
2657   CallingConv::ID CallConv = CLI.CallConv;
2658   bool IsVarArg = CLI.IsVarArg;
2659   bool IsSibCall = false;
2660   bool IsThisReturn = false;
2661   MachineFunction &MF = DAG.getMachineFunction();
2662 
2663   if (Callee.isUndef() || isNullConstant(Callee)) {
2664     if (!CLI.IsTailCall) {
2665       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2666         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2667     }
2668 
2669     return Chain;
2670   }
2671 
2672   if (IsVarArg) {
2673     return lowerUnhandledCall(CLI, InVals,
2674                               "unsupported call to variadic function ");
2675   }
2676 
2677   if (!CLI.CS.getInstruction())
2678     report_fatal_error("unsupported libcall legalization");
2679 
2680   if (!CLI.CS.getCalledFunction()) {
2681     return lowerUnhandledCall(CLI, InVals,
2682                               "unsupported indirect call to function ");
2683   }
2684 
2685   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2686     return lowerUnhandledCall(CLI, InVals,
2687                               "unsupported required tail call to function ");
2688   }
2689 
2690   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2691     // Note the issue is with the CC of the calling function, not of the call
2692     // itself.
2693     return lowerUnhandledCall(CLI, InVals,
2694                           "unsupported call from graphics shader of function ");
2695   }
2696 
2697   if (IsTailCall) {
2698     IsTailCall = isEligibleForTailCallOptimization(
2699       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2700     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2701       report_fatal_error("failed to perform tail call elimination on a call "
2702                          "site marked musttail");
2703     }
2704 
2705     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2706 
2707     // A sibling call is one where we're under the usual C ABI and not planning
2708     // to change that but can still do a tail call:
2709     if (!TailCallOpt && IsTailCall)
2710       IsSibCall = true;
2711 
2712     if (IsTailCall)
2713       ++NumTailCalls;
2714   }
2715 
2716   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2717 
2718   // Analyze operands of the call, assigning locations to each operand.
2719   SmallVector<CCValAssign, 16> ArgLocs;
2720   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2721   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2722 
2723   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2724 
2725   // Get a count of how many bytes are to be pushed on the stack.
2726   unsigned NumBytes = CCInfo.getNextStackOffset();
2727 
2728   if (IsSibCall) {
2729     // Since we're not changing the ABI to make this a tail call, the memory
2730     // operands are already available in the caller's incoming argument space.
2731     NumBytes = 0;
2732   }
2733 
2734   // FPDiff is the byte offset of the call's argument area from the callee's.
2735   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2736   // by this amount for a tail call. In a sibling call it must be 0 because the
2737   // caller will deallocate the entire stack and the callee still expects its
2738   // arguments to begin at SP+0. Completely unused for non-tail calls.
2739   int32_t FPDiff = 0;
2740   MachineFrameInfo &MFI = MF.getFrameInfo();
2741   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2742 
2743   // Adjust the stack pointer for the new arguments...
2744   // These operations are automatically eliminated by the prolog/epilog pass
2745   if (!IsSibCall) {
2746     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2747 
2748     SmallVector<SDValue, 4> CopyFromChains;
2749 
2750     // In the HSA case, this should be an identity copy.
2751     SDValue ScratchRSrcReg
2752       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2753     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2754     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2755     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2756   }
2757 
2758   SmallVector<SDValue, 8> MemOpChains;
2759   MVT PtrVT = MVT::i32;
2760 
2761   // Walk the register/memloc assignments, inserting copies/loads.
2762   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2763     CCValAssign &VA = ArgLocs[i];
2764     SDValue Arg = OutVals[i];
2765 
2766     // Promote the value if needed.
2767     switch (VA.getLocInfo()) {
2768     case CCValAssign::Full:
2769       break;
2770     case CCValAssign::BCvt:
2771       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2772       break;
2773     case CCValAssign::ZExt:
2774       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2775       break;
2776     case CCValAssign::SExt:
2777       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2778       break;
2779     case CCValAssign::AExt:
2780       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2781       break;
2782     case CCValAssign::FPExt:
2783       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2784       break;
2785     default:
2786       llvm_unreachable("Unknown loc info!");
2787     }
2788 
2789     if (VA.isRegLoc()) {
2790       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2791     } else {
2792       assert(VA.isMemLoc());
2793 
2794       SDValue DstAddr;
2795       MachinePointerInfo DstInfo;
2796 
2797       unsigned LocMemOffset = VA.getLocMemOffset();
2798       int32_t Offset = LocMemOffset;
2799 
2800       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2801       MaybeAlign Alignment;
2802 
2803       if (IsTailCall) {
2804         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2805         unsigned OpSize = Flags.isByVal() ?
2806           Flags.getByValSize() : VA.getValVT().getStoreSize();
2807 
2808         // FIXME: We can have better than the minimum byval required alignment.
2809         Alignment =
2810             Flags.isByVal()
2811                 ? Flags.getNonZeroByValAlign()
2812                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2813 
2814         Offset = Offset + FPDiff;
2815         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2816 
2817         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2818         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2819 
2820         // Make sure any stack arguments overlapping with where we're storing
2821         // are loaded before this eventual operation. Otherwise they'll be
2822         // clobbered.
2823 
2824         // FIXME: Why is this really necessary? This seems to just result in a
2825         // lot of code to copy the stack and write them back to the same
2826         // locations, which are supposed to be immutable?
2827         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2828       } else {
2829         DstAddr = PtrOff;
2830         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2831         Alignment =
2832             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2833       }
2834 
2835       if (Outs[i].Flags.isByVal()) {
2836         SDValue SizeNode =
2837             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2838         SDValue Cpy =
2839             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2840                           Outs[i].Flags.getNonZeroByValAlign(),
2841                           /*isVol = */ false, /*AlwaysInline = */ true,
2842                           /*isTailCall = */ false, DstInfo,
2843                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2844 
2845         MemOpChains.push_back(Cpy);
2846       } else {
2847         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2848                                      Alignment ? Alignment->value() : 0);
2849         MemOpChains.push_back(Store);
2850       }
2851     }
2852   }
2853 
2854   // Copy special input registers after user input arguments.
2855   passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2856 
2857   if (!MemOpChains.empty())
2858     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2859 
2860   // Build a sequence of copy-to-reg nodes chained together with token chain
2861   // and flag operands which copy the outgoing args into the appropriate regs.
2862   SDValue InFlag;
2863   for (auto &RegToPass : RegsToPass) {
2864     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2865                              RegToPass.second, InFlag);
2866     InFlag = Chain.getValue(1);
2867   }
2868 
2869 
2870   SDValue PhysReturnAddrReg;
2871   if (IsTailCall) {
2872     // Since the return is being combined with the call, we need to pass on the
2873     // return address.
2874 
2875     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2876     SDValue ReturnAddrReg = CreateLiveInRegister(
2877       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2878 
2879     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2880                                         MVT::i64);
2881     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2882     InFlag = Chain.getValue(1);
2883   }
2884 
2885   // We don't usually want to end the call-sequence here because we would tidy
2886   // the frame up *after* the call, however in the ABI-changing tail-call case
2887   // we've carefully laid out the parameters so that when sp is reset they'll be
2888   // in the correct location.
2889   if (IsTailCall && !IsSibCall) {
2890     Chain = DAG.getCALLSEQ_END(Chain,
2891                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2892                                DAG.getTargetConstant(0, DL, MVT::i32),
2893                                InFlag, DL);
2894     InFlag = Chain.getValue(1);
2895   }
2896 
2897   std::vector<SDValue> Ops;
2898   Ops.push_back(Chain);
2899   Ops.push_back(Callee);
2900   // Add a redundant copy of the callee global which will not be legalized, as
2901   // we need direct access to the callee later.
2902   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2903   const GlobalValue *GV = GSD->getGlobal();
2904   Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2905 
2906   if (IsTailCall) {
2907     // Each tail call may have to adjust the stack by a different amount, so
2908     // this information must travel along with the operation for eventual
2909     // consumption by emitEpilogue.
2910     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2911 
2912     Ops.push_back(PhysReturnAddrReg);
2913   }
2914 
2915   // Add argument registers to the end of the list so that they are known live
2916   // into the call.
2917   for (auto &RegToPass : RegsToPass) {
2918     Ops.push_back(DAG.getRegister(RegToPass.first,
2919                                   RegToPass.second.getValueType()));
2920   }
2921 
2922   // Add a register mask operand representing the call-preserved registers.
2923 
2924   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2925   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2926   assert(Mask && "Missing call preserved mask for calling convention");
2927   Ops.push_back(DAG.getRegisterMask(Mask));
2928 
2929   if (InFlag.getNode())
2930     Ops.push_back(InFlag);
2931 
2932   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2933 
2934   // If we're doing a tall call, use a TC_RETURN here rather than an
2935   // actual call instruction.
2936   if (IsTailCall) {
2937     MFI.setHasTailCall();
2938     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2939   }
2940 
2941   // Returns a chain and a flag for retval copy to use.
2942   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2943   Chain = Call.getValue(0);
2944   InFlag = Call.getValue(1);
2945 
2946   uint64_t CalleePopBytes = NumBytes;
2947   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2948                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2949                              InFlag, DL);
2950   if (!Ins.empty())
2951     InFlag = Chain.getValue(1);
2952 
2953   // Handle result values, copying them out of physregs into vregs that we
2954   // return.
2955   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2956                          InVals, IsThisReturn,
2957                          IsThisReturn ? OutVals[0] : SDValue());
2958 }
2959 
2960 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
2961                                              const MachineFunction &MF) const {
2962   Register Reg = StringSwitch<Register>(RegName)
2963     .Case("m0", AMDGPU::M0)
2964     .Case("exec", AMDGPU::EXEC)
2965     .Case("exec_lo", AMDGPU::EXEC_LO)
2966     .Case("exec_hi", AMDGPU::EXEC_HI)
2967     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2968     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2969     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2970     .Default(Register());
2971 
2972   if (Reg == AMDGPU::NoRegister) {
2973     report_fatal_error(Twine("invalid register name \""
2974                              + StringRef(RegName)  + "\"."));
2975 
2976   }
2977 
2978   if (!Subtarget->hasFlatScrRegister() &&
2979        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2980     report_fatal_error(Twine("invalid register \""
2981                              + StringRef(RegName)  + "\" for subtarget."));
2982   }
2983 
2984   switch (Reg) {
2985   case AMDGPU::M0:
2986   case AMDGPU::EXEC_LO:
2987   case AMDGPU::EXEC_HI:
2988   case AMDGPU::FLAT_SCR_LO:
2989   case AMDGPU::FLAT_SCR_HI:
2990     if (VT.getSizeInBits() == 32)
2991       return Reg;
2992     break;
2993   case AMDGPU::EXEC:
2994   case AMDGPU::FLAT_SCR:
2995     if (VT.getSizeInBits() == 64)
2996       return Reg;
2997     break;
2998   default:
2999     llvm_unreachable("missing register type checking");
3000   }
3001 
3002   report_fatal_error(Twine("invalid type for register \""
3003                            + StringRef(RegName) + "\"."));
3004 }
3005 
3006 // If kill is not the last instruction, split the block so kill is always a
3007 // proper terminator.
3008 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3009                                                     MachineBasicBlock *BB) const {
3010   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3011 
3012   MachineBasicBlock::iterator SplitPoint(&MI);
3013   ++SplitPoint;
3014 
3015   if (SplitPoint == BB->end()) {
3016     // Don't bother with a new block.
3017     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3018     return BB;
3019   }
3020 
3021   MachineFunction *MF = BB->getParent();
3022   MachineBasicBlock *SplitBB
3023     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3024 
3025   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3026   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3027 
3028   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3029   BB->addSuccessor(SplitBB);
3030 
3031   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3032   return SplitBB;
3033 }
3034 
3035 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3036 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3037 // be the first instruction in the remainder block.
3038 //
3039 /// \returns { LoopBody, Remainder }
3040 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3041 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3042   MachineFunction *MF = MBB.getParent();
3043   MachineBasicBlock::iterator I(&MI);
3044 
3045   // To insert the loop we need to split the block. Move everything after this
3046   // point to a new block, and insert a new empty block between the two.
3047   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3048   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3049   MachineFunction::iterator MBBI(MBB);
3050   ++MBBI;
3051 
3052   MF->insert(MBBI, LoopBB);
3053   MF->insert(MBBI, RemainderBB);
3054 
3055   LoopBB->addSuccessor(LoopBB);
3056   LoopBB->addSuccessor(RemainderBB);
3057 
3058   // Move the rest of the block into a new block.
3059   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3060 
3061   if (InstInLoop) {
3062     auto Next = std::next(I);
3063 
3064     // Move instruction to loop body.
3065     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3066 
3067     // Move the rest of the block.
3068     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3069   } else {
3070     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3071   }
3072 
3073   MBB.addSuccessor(LoopBB);
3074 
3075   return std::make_pair(LoopBB, RemainderBB);
3076 }
3077 
3078 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3079 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3080   MachineBasicBlock *MBB = MI.getParent();
3081   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3082   auto I = MI.getIterator();
3083   auto E = std::next(I);
3084 
3085   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3086     .addImm(0);
3087 
3088   MIBundleBuilder Bundler(*MBB, I, E);
3089   finalizeBundle(*MBB, Bundler.begin());
3090 }
3091 
3092 MachineBasicBlock *
3093 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3094                                          MachineBasicBlock *BB) const {
3095   const DebugLoc &DL = MI.getDebugLoc();
3096 
3097   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3098 
3099   MachineBasicBlock *LoopBB;
3100   MachineBasicBlock *RemainderBB;
3101   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3102 
3103   // Apparently kill flags are only valid if the def is in the same block?
3104   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3105     Src->setIsKill(false);
3106 
3107   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3108 
3109   MachineBasicBlock::iterator I = LoopBB->end();
3110 
3111   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3112     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3113 
3114   // Clear TRAP_STS.MEM_VIOL
3115   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3116     .addImm(0)
3117     .addImm(EncodedReg);
3118 
3119   bundleInstWithWaitcnt(MI);
3120 
3121   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3122 
3123   // Load and check TRAP_STS.MEM_VIOL
3124   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3125     .addImm(EncodedReg);
3126 
3127   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3128   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3129     .addReg(Reg, RegState::Kill)
3130     .addImm(0);
3131   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3132     .addMBB(LoopBB);
3133 
3134   return RemainderBB;
3135 }
3136 
3137 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3138 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3139 // will only do one iteration. In the worst case, this will loop 64 times.
3140 //
3141 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3142 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3143   const SIInstrInfo *TII,
3144   MachineRegisterInfo &MRI,
3145   MachineBasicBlock &OrigBB,
3146   MachineBasicBlock &LoopBB,
3147   const DebugLoc &DL,
3148   const MachineOperand &IdxReg,
3149   unsigned InitReg,
3150   unsigned ResultReg,
3151   unsigned PhiReg,
3152   unsigned InitSaveExecReg,
3153   int Offset,
3154   bool UseGPRIdxMode,
3155   bool IsIndirectSrc) {
3156   MachineFunction *MF = OrigBB.getParent();
3157   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3158   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3159   MachineBasicBlock::iterator I = LoopBB.begin();
3160 
3161   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3162   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3163   Register NewExec = MRI.createVirtualRegister(BoolRC);
3164   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3165   Register CondReg = MRI.createVirtualRegister(BoolRC);
3166 
3167   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3168     .addReg(InitReg)
3169     .addMBB(&OrigBB)
3170     .addReg(ResultReg)
3171     .addMBB(&LoopBB);
3172 
3173   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3174     .addReg(InitSaveExecReg)
3175     .addMBB(&OrigBB)
3176     .addReg(NewExec)
3177     .addMBB(&LoopBB);
3178 
3179   // Read the next variant <- also loop target.
3180   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3181     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3182 
3183   // Compare the just read M0 value to all possible Idx values.
3184   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3185     .addReg(CurrentIdxReg)
3186     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3187 
3188   // Update EXEC, save the original EXEC value to VCC.
3189   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3190                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3191           NewExec)
3192     .addReg(CondReg, RegState::Kill);
3193 
3194   MRI.setSimpleHint(NewExec, CondReg);
3195 
3196   if (UseGPRIdxMode) {
3197     unsigned IdxReg;
3198     if (Offset == 0) {
3199       IdxReg = CurrentIdxReg;
3200     } else {
3201       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3202       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3203         .addReg(CurrentIdxReg, RegState::Kill)
3204         .addImm(Offset);
3205     }
3206     unsigned IdxMode = IsIndirectSrc ?
3207       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3208     MachineInstr *SetOn =
3209       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3210       .addReg(IdxReg, RegState::Kill)
3211       .addImm(IdxMode);
3212     SetOn->getOperand(3).setIsUndef();
3213   } else {
3214     // Move index from VCC into M0
3215     if (Offset == 0) {
3216       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3217         .addReg(CurrentIdxReg, RegState::Kill);
3218     } else {
3219       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3220         .addReg(CurrentIdxReg, RegState::Kill)
3221         .addImm(Offset);
3222     }
3223   }
3224 
3225   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3226   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3227   MachineInstr *InsertPt =
3228     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3229                                                   : AMDGPU::S_XOR_B64_term), Exec)
3230       .addReg(Exec)
3231       .addReg(NewExec);
3232 
3233   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3234   // s_cbranch_scc0?
3235 
3236   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3237   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3238     .addMBB(&LoopBB);
3239 
3240   return InsertPt->getIterator();
3241 }
3242 
3243 // This has slightly sub-optimal regalloc when the source vector is killed by
3244 // the read. The register allocator does not understand that the kill is
3245 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3246 // subregister from it, using 1 more VGPR than necessary. This was saved when
3247 // this was expanded after register allocation.
3248 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3249                                                   MachineBasicBlock &MBB,
3250                                                   MachineInstr &MI,
3251                                                   unsigned InitResultReg,
3252                                                   unsigned PhiReg,
3253                                                   int Offset,
3254                                                   bool UseGPRIdxMode,
3255                                                   bool IsIndirectSrc) {
3256   MachineFunction *MF = MBB.getParent();
3257   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3258   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3259   MachineRegisterInfo &MRI = MF->getRegInfo();
3260   const DebugLoc &DL = MI.getDebugLoc();
3261   MachineBasicBlock::iterator I(&MI);
3262 
3263   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3264   Register DstReg = MI.getOperand(0).getReg();
3265   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3266   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3267   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3268   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3269 
3270   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3271 
3272   // Save the EXEC mask
3273   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3274     .addReg(Exec);
3275 
3276   MachineBasicBlock *LoopBB;
3277   MachineBasicBlock *RemainderBB;
3278   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3279 
3280   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3281 
3282   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3283                                       InitResultReg, DstReg, PhiReg, TmpExec,
3284                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3285 
3286   MachineBasicBlock::iterator First = RemainderBB->begin();
3287   BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
3288     .addReg(SaveExec);
3289 
3290   return InsPt;
3291 }
3292 
3293 // Returns subreg index, offset
3294 static std::pair<unsigned, int>
3295 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3296                             const TargetRegisterClass *SuperRC,
3297                             unsigned VecReg,
3298                             int Offset) {
3299   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3300 
3301   // Skip out of bounds offsets, or else we would end up using an undefined
3302   // register.
3303   if (Offset >= NumElts || Offset < 0)
3304     return std::make_pair(AMDGPU::sub0, Offset);
3305 
3306   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3307 }
3308 
3309 // Return true if the index is an SGPR and was set.
3310 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3311                                  MachineRegisterInfo &MRI,
3312                                  MachineInstr &MI,
3313                                  int Offset,
3314                                  bool UseGPRIdxMode,
3315                                  bool IsIndirectSrc) {
3316   MachineBasicBlock *MBB = MI.getParent();
3317   const DebugLoc &DL = MI.getDebugLoc();
3318   MachineBasicBlock::iterator I(&MI);
3319 
3320   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3321   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3322 
3323   assert(Idx->getReg() != AMDGPU::NoRegister);
3324 
3325   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3326     return false;
3327 
3328   if (UseGPRIdxMode) {
3329     unsigned IdxMode = IsIndirectSrc ?
3330       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3331     if (Offset == 0) {
3332       MachineInstr *SetOn =
3333           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3334               .add(*Idx)
3335               .addImm(IdxMode);
3336 
3337       SetOn->getOperand(3).setIsUndef();
3338     } else {
3339       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3340       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3341           .add(*Idx)
3342           .addImm(Offset);
3343       MachineInstr *SetOn =
3344         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3345         .addReg(Tmp, RegState::Kill)
3346         .addImm(IdxMode);
3347 
3348       SetOn->getOperand(3).setIsUndef();
3349     }
3350 
3351     return true;
3352   }
3353 
3354   if (Offset == 0) {
3355     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3356       .add(*Idx);
3357   } else {
3358     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3359       .add(*Idx)
3360       .addImm(Offset);
3361   }
3362 
3363   return true;
3364 }
3365 
3366 // Control flow needs to be inserted if indexing with a VGPR.
3367 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3368                                           MachineBasicBlock &MBB,
3369                                           const GCNSubtarget &ST) {
3370   const SIInstrInfo *TII = ST.getInstrInfo();
3371   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3372   MachineFunction *MF = MBB.getParent();
3373   MachineRegisterInfo &MRI = MF->getRegInfo();
3374 
3375   Register Dst = MI.getOperand(0).getReg();
3376   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3377   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3378 
3379   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3380 
3381   unsigned SubReg;
3382   std::tie(SubReg, Offset)
3383     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3384 
3385   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3386 
3387   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3388     MachineBasicBlock::iterator I(&MI);
3389     const DebugLoc &DL = MI.getDebugLoc();
3390 
3391     if (UseGPRIdxMode) {
3392       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3393       // to avoid interfering with other uses, so probably requires a new
3394       // optimization pass.
3395       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3396         .addReg(SrcReg, RegState::Undef, SubReg)
3397         .addReg(SrcReg, RegState::Implicit)
3398         .addReg(AMDGPU::M0, RegState::Implicit);
3399       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3400     } else {
3401       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3402         .addReg(SrcReg, RegState::Undef, SubReg)
3403         .addReg(SrcReg, RegState::Implicit);
3404     }
3405 
3406     MI.eraseFromParent();
3407 
3408     return &MBB;
3409   }
3410 
3411   const DebugLoc &DL = MI.getDebugLoc();
3412   MachineBasicBlock::iterator I(&MI);
3413 
3414   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3415   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3416 
3417   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3418 
3419   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3420                               Offset, UseGPRIdxMode, true);
3421   MachineBasicBlock *LoopBB = InsPt->getParent();
3422 
3423   if (UseGPRIdxMode) {
3424     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3425       .addReg(SrcReg, RegState::Undef, SubReg)
3426       .addReg(SrcReg, RegState::Implicit)
3427       .addReg(AMDGPU::M0, RegState::Implicit);
3428     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3429   } else {
3430     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3431       .addReg(SrcReg, RegState::Undef, SubReg)
3432       .addReg(SrcReg, RegState::Implicit);
3433   }
3434 
3435   MI.eraseFromParent();
3436 
3437   return LoopBB;
3438 }
3439 
3440 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3441                                           MachineBasicBlock &MBB,
3442                                           const GCNSubtarget &ST) {
3443   const SIInstrInfo *TII = ST.getInstrInfo();
3444   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3445   MachineFunction *MF = MBB.getParent();
3446   MachineRegisterInfo &MRI = MF->getRegInfo();
3447 
3448   Register Dst = MI.getOperand(0).getReg();
3449   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3450   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3451   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3452   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3453   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3454 
3455   // This can be an immediate, but will be folded later.
3456   assert(Val->getReg());
3457 
3458   unsigned SubReg;
3459   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3460                                                          SrcVec->getReg(),
3461                                                          Offset);
3462   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3463 
3464   if (Idx->getReg() == AMDGPU::NoRegister) {
3465     MachineBasicBlock::iterator I(&MI);
3466     const DebugLoc &DL = MI.getDebugLoc();
3467 
3468     assert(Offset == 0);
3469 
3470     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3471         .add(*SrcVec)
3472         .add(*Val)
3473         .addImm(SubReg);
3474 
3475     MI.eraseFromParent();
3476     return &MBB;
3477   }
3478 
3479   const MCInstrDesc &MovRelDesc
3480     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3481 
3482   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3483     MachineBasicBlock::iterator I(&MI);
3484     const DebugLoc &DL = MI.getDebugLoc();
3485     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3486       .addReg(SrcVec->getReg())
3487       .add(*Val)
3488       .addImm(SubReg);
3489     if (UseGPRIdxMode)
3490       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3491 
3492     MI.eraseFromParent();
3493     return &MBB;
3494   }
3495 
3496   if (Val->isReg())
3497     MRI.clearKillFlags(Val->getReg());
3498 
3499   const DebugLoc &DL = MI.getDebugLoc();
3500 
3501   Register PhiReg = MRI.createVirtualRegister(VecRC);
3502 
3503   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3504                               Offset, UseGPRIdxMode, false);
3505   MachineBasicBlock *LoopBB = InsPt->getParent();
3506 
3507   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3508     .addReg(PhiReg)
3509     .add(*Val)
3510     .addImm(AMDGPU::sub0);
3511   if (UseGPRIdxMode)
3512     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3513 
3514   MI.eraseFromParent();
3515   return LoopBB;
3516 }
3517 
3518 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3519   MachineInstr &MI, MachineBasicBlock *BB) const {
3520 
3521   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3522   MachineFunction *MF = BB->getParent();
3523   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3524 
3525   if (TII->isMIMG(MI)) {
3526     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3527       report_fatal_error("missing mem operand from MIMG instruction");
3528     }
3529     // Add a memoperand for mimg instructions so that they aren't assumed to
3530     // be ordered memory instuctions.
3531 
3532     return BB;
3533   }
3534 
3535   switch (MI.getOpcode()) {
3536   case AMDGPU::S_ADD_U64_PSEUDO:
3537   case AMDGPU::S_SUB_U64_PSEUDO: {
3538     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3539     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3540     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3541     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3542     const DebugLoc &DL = MI.getDebugLoc();
3543 
3544     MachineOperand &Dest = MI.getOperand(0);
3545     MachineOperand &Src0 = MI.getOperand(1);
3546     MachineOperand &Src1 = MI.getOperand(2);
3547 
3548     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3549     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3550 
3551     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3552      Src0, BoolRC, AMDGPU::sub0,
3553      &AMDGPU::SReg_32RegClass);
3554     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3555       Src0, BoolRC, AMDGPU::sub1,
3556       &AMDGPU::SReg_32RegClass);
3557 
3558     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3559       Src1, BoolRC, AMDGPU::sub0,
3560       &AMDGPU::SReg_32RegClass);
3561     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3562       Src1, BoolRC, AMDGPU::sub1,
3563       &AMDGPU::SReg_32RegClass);
3564 
3565     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3566 
3567     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3568     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3569     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3570       .add(Src0Sub0)
3571       .add(Src1Sub0);
3572     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3573       .add(Src0Sub1)
3574       .add(Src1Sub1);
3575     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3576       .addReg(DestSub0)
3577       .addImm(AMDGPU::sub0)
3578       .addReg(DestSub1)
3579       .addImm(AMDGPU::sub1);
3580     MI.eraseFromParent();
3581     return BB;
3582   }
3583   case AMDGPU::SI_INIT_M0: {
3584     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3585             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3586         .add(MI.getOperand(0));
3587     MI.eraseFromParent();
3588     return BB;
3589   }
3590   case AMDGPU::SI_INIT_EXEC:
3591     // This should be before all vector instructions.
3592     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3593             AMDGPU::EXEC)
3594         .addImm(MI.getOperand(0).getImm());
3595     MI.eraseFromParent();
3596     return BB;
3597 
3598   case AMDGPU::SI_INIT_EXEC_LO:
3599     // This should be before all vector instructions.
3600     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3601             AMDGPU::EXEC_LO)
3602         .addImm(MI.getOperand(0).getImm());
3603     MI.eraseFromParent();
3604     return BB;
3605 
3606   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3607     // Extract the thread count from an SGPR input and set EXEC accordingly.
3608     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3609     //
3610     // S_BFE_U32 count, input, {shift, 7}
3611     // S_BFM_B64 exec, count, 0
3612     // S_CMP_EQ_U32 count, 64
3613     // S_CMOV_B64 exec, -1
3614     MachineInstr *FirstMI = &*BB->begin();
3615     MachineRegisterInfo &MRI = MF->getRegInfo();
3616     Register InputReg = MI.getOperand(0).getReg();
3617     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3618     bool Found = false;
3619 
3620     // Move the COPY of the input reg to the beginning, so that we can use it.
3621     for (auto I = BB->begin(); I != &MI; I++) {
3622       if (I->getOpcode() != TargetOpcode::COPY ||
3623           I->getOperand(0).getReg() != InputReg)
3624         continue;
3625 
3626       if (I == FirstMI) {
3627         FirstMI = &*++BB->begin();
3628       } else {
3629         I->removeFromParent();
3630         BB->insert(FirstMI, &*I);
3631       }
3632       Found = true;
3633       break;
3634     }
3635     assert(Found);
3636     (void)Found;
3637 
3638     // This should be before all vector instructions.
3639     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3640     bool isWave32 = getSubtarget()->isWave32();
3641     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3642     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3643         .addReg(InputReg)
3644         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3645     BuildMI(*BB, FirstMI, DebugLoc(),
3646             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3647             Exec)
3648         .addReg(CountReg)
3649         .addImm(0);
3650     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3651         .addReg(CountReg, RegState::Kill)
3652         .addImm(getSubtarget()->getWavefrontSize());
3653     BuildMI(*BB, FirstMI, DebugLoc(),
3654             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3655             Exec)
3656         .addImm(-1);
3657     MI.eraseFromParent();
3658     return BB;
3659   }
3660 
3661   case AMDGPU::GET_GROUPSTATICSIZE: {
3662     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3663            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3664     DebugLoc DL = MI.getDebugLoc();
3665     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3666         .add(MI.getOperand(0))
3667         .addImm(MFI->getLDSSize());
3668     MI.eraseFromParent();
3669     return BB;
3670   }
3671   case AMDGPU::SI_INDIRECT_SRC_V1:
3672   case AMDGPU::SI_INDIRECT_SRC_V2:
3673   case AMDGPU::SI_INDIRECT_SRC_V4:
3674   case AMDGPU::SI_INDIRECT_SRC_V8:
3675   case AMDGPU::SI_INDIRECT_SRC_V16:
3676     return emitIndirectSrc(MI, *BB, *getSubtarget());
3677   case AMDGPU::SI_INDIRECT_DST_V1:
3678   case AMDGPU::SI_INDIRECT_DST_V2:
3679   case AMDGPU::SI_INDIRECT_DST_V4:
3680   case AMDGPU::SI_INDIRECT_DST_V8:
3681   case AMDGPU::SI_INDIRECT_DST_V16:
3682     return emitIndirectDst(MI, *BB, *getSubtarget());
3683   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3684   case AMDGPU::SI_KILL_I1_PSEUDO:
3685     return splitKillBlock(MI, BB);
3686   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3687     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3688     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3689     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3690 
3691     Register Dst = MI.getOperand(0).getReg();
3692     Register Src0 = MI.getOperand(1).getReg();
3693     Register Src1 = MI.getOperand(2).getReg();
3694     const DebugLoc &DL = MI.getDebugLoc();
3695     Register SrcCond = MI.getOperand(3).getReg();
3696 
3697     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3698     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3699     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3700     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3701 
3702     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3703       .addReg(SrcCond);
3704     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3705       .addImm(0)
3706       .addReg(Src0, 0, AMDGPU::sub0)
3707       .addImm(0)
3708       .addReg(Src1, 0, AMDGPU::sub0)
3709       .addReg(SrcCondCopy);
3710     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3711       .addImm(0)
3712       .addReg(Src0, 0, AMDGPU::sub1)
3713       .addImm(0)
3714       .addReg(Src1, 0, AMDGPU::sub1)
3715       .addReg(SrcCondCopy);
3716 
3717     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3718       .addReg(DstLo)
3719       .addImm(AMDGPU::sub0)
3720       .addReg(DstHi)
3721       .addImm(AMDGPU::sub1);
3722     MI.eraseFromParent();
3723     return BB;
3724   }
3725   case AMDGPU::SI_BR_UNDEF: {
3726     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3727     const DebugLoc &DL = MI.getDebugLoc();
3728     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3729                            .add(MI.getOperand(0));
3730     Br->getOperand(1).setIsUndef(true); // read undef SCC
3731     MI.eraseFromParent();
3732     return BB;
3733   }
3734   case AMDGPU::ADJCALLSTACKUP:
3735   case AMDGPU::ADJCALLSTACKDOWN: {
3736     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3737     MachineInstrBuilder MIB(*MF, &MI);
3738 
3739     // Add an implicit use of the frame offset reg to prevent the restore copy
3740     // inserted after the call from being reorderd after stack operations in the
3741     // the caller's frame.
3742     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3743         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3744         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3745     return BB;
3746   }
3747   case AMDGPU::SI_CALL_ISEL: {
3748     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3749     const DebugLoc &DL = MI.getDebugLoc();
3750 
3751     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3752 
3753     MachineInstrBuilder MIB;
3754     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3755 
3756     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3757       MIB.add(MI.getOperand(I));
3758 
3759     MIB.cloneMemRefs(MI);
3760     MI.eraseFromParent();
3761     return BB;
3762   }
3763   case AMDGPU::V_ADD_I32_e32:
3764   case AMDGPU::V_SUB_I32_e32:
3765   case AMDGPU::V_SUBREV_I32_e32: {
3766     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3767     const DebugLoc &DL = MI.getDebugLoc();
3768     unsigned Opc = MI.getOpcode();
3769 
3770     bool NeedClampOperand = false;
3771     if (TII->pseudoToMCOpcode(Opc) == -1) {
3772       Opc = AMDGPU::getVOPe64(Opc);
3773       NeedClampOperand = true;
3774     }
3775 
3776     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3777     if (TII->isVOP3(*I)) {
3778       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3779       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3780       I.addReg(TRI->getVCC(), RegState::Define);
3781     }
3782     I.add(MI.getOperand(1))
3783      .add(MI.getOperand(2));
3784     if (NeedClampOperand)
3785       I.addImm(0); // clamp bit for e64 encoding
3786 
3787     TII->legalizeOperands(*I);
3788 
3789     MI.eraseFromParent();
3790     return BB;
3791   }
3792   case AMDGPU::DS_GWS_INIT:
3793   case AMDGPU::DS_GWS_SEMA_V:
3794   case AMDGPU::DS_GWS_SEMA_BR:
3795   case AMDGPU::DS_GWS_SEMA_P:
3796   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3797   case AMDGPU::DS_GWS_BARRIER:
3798     // A s_waitcnt 0 is required to be the instruction immediately following.
3799     if (getSubtarget()->hasGWSAutoReplay()) {
3800       bundleInstWithWaitcnt(MI);
3801       return BB;
3802     }
3803 
3804     return emitGWSMemViolTestLoop(MI, BB);
3805   default:
3806     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3807   }
3808 }
3809 
3810 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3811   return isTypeLegal(VT.getScalarType());
3812 }
3813 
3814 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3815   // This currently forces unfolding various combinations of fsub into fma with
3816   // free fneg'd operands. As long as we have fast FMA (controlled by
3817   // isFMAFasterThanFMulAndFAdd), we should perform these.
3818 
3819   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3820   // most of these combines appear to be cycle neutral but save on instruction
3821   // count / code size.
3822   return true;
3823 }
3824 
3825 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3826                                          EVT VT) const {
3827   if (!VT.isVector()) {
3828     return MVT::i1;
3829   }
3830   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3831 }
3832 
3833 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3834   // TODO: Should i16 be used always if legal? For now it would force VALU
3835   // shifts.
3836   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3837 }
3838 
3839 // Answering this is somewhat tricky and depends on the specific device which
3840 // have different rates for fma or all f64 operations.
3841 //
3842 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3843 // regardless of which device (although the number of cycles differs between
3844 // devices), so it is always profitable for f64.
3845 //
3846 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3847 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3848 // which we can always do even without fused FP ops since it returns the same
3849 // result as the separate operations and since it is always full
3850 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3851 // however does not support denormals, so we do report fma as faster if we have
3852 // a fast fma device and require denormals.
3853 //
3854 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
3855                                                   EVT VT) const {
3856   VT = VT.getScalarType();
3857 
3858   switch (VT.getSimpleVT().SimpleTy) {
3859   case MVT::f32: {
3860     // This is as fast on some subtargets. However, we always have full rate f32
3861     // mad available which returns the same result as the separate operations
3862     // which we should prefer over fma. We can't use this if we want to support
3863     // denormals, so only report this in these cases.
3864     if (hasFP32Denormals(MF))
3865       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3866 
3867     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3868     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3869   }
3870   case MVT::f64:
3871     return true;
3872   case MVT::f16:
3873     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
3874   default:
3875     break;
3876   }
3877 
3878   return false;
3879 }
3880 
3881 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG,
3882                                               const SDNode *N) const {
3883   // TODO: Check future ftz flag
3884   // v_mad_f32/v_mac_f32 do not support denormals.
3885   EVT VT = N->getValueType(0);
3886   if (VT == MVT::f32)
3887     return !hasFP32Denormals(DAG.getMachineFunction());
3888   if (VT == MVT::f16) {
3889     return Subtarget->hasMadF16() &&
3890            !hasFP64FP16Denormals(DAG.getMachineFunction());
3891   }
3892 
3893   return false;
3894 }
3895 
3896 //===----------------------------------------------------------------------===//
3897 // Custom DAG Lowering Operations
3898 //===----------------------------------------------------------------------===//
3899 
3900 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3901 // wider vector type is legal.
3902 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3903                                              SelectionDAG &DAG) const {
3904   unsigned Opc = Op.getOpcode();
3905   EVT VT = Op.getValueType();
3906   assert(VT == MVT::v4f16);
3907 
3908   SDValue Lo, Hi;
3909   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3910 
3911   SDLoc SL(Op);
3912   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3913                              Op->getFlags());
3914   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3915                              Op->getFlags());
3916 
3917   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3918 }
3919 
3920 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3921 // wider vector type is legal.
3922 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3923                                               SelectionDAG &DAG) const {
3924   unsigned Opc = Op.getOpcode();
3925   EVT VT = Op.getValueType();
3926   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3927 
3928   SDValue Lo0, Hi0;
3929   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3930   SDValue Lo1, Hi1;
3931   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3932 
3933   SDLoc SL(Op);
3934 
3935   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3936                              Op->getFlags());
3937   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3938                              Op->getFlags());
3939 
3940   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3941 }
3942 
3943 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
3944                                               SelectionDAG &DAG) const {
3945   unsigned Opc = Op.getOpcode();
3946   EVT VT = Op.getValueType();
3947   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3948 
3949   SDValue Lo0, Hi0;
3950   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3951   SDValue Lo1, Hi1;
3952   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3953   SDValue Lo2, Hi2;
3954   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
3955 
3956   SDLoc SL(Op);
3957 
3958   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
3959                              Op->getFlags());
3960   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
3961                              Op->getFlags());
3962 
3963   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3964 }
3965 
3966 
3967 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3968   switch (Op.getOpcode()) {
3969   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3970   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3971   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3972   case ISD::LOAD: {
3973     SDValue Result = LowerLOAD(Op, DAG);
3974     assert((!Result.getNode() ||
3975             Result.getNode()->getNumValues() == 2) &&
3976            "Load should return a value and a chain");
3977     return Result;
3978   }
3979 
3980   case ISD::FSIN:
3981   case ISD::FCOS:
3982     return LowerTrig(Op, DAG);
3983   case ISD::SELECT: return LowerSELECT(Op, DAG);
3984   case ISD::FDIV: return LowerFDIV(Op, DAG);
3985   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3986   case ISD::STORE: return LowerSTORE(Op, DAG);
3987   case ISD::GlobalAddress: {
3988     MachineFunction &MF = DAG.getMachineFunction();
3989     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3990     return LowerGlobalAddress(MFI, Op, DAG);
3991   }
3992   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3993   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3994   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3995   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3996   case ISD::INSERT_SUBVECTOR:
3997     return lowerINSERT_SUBVECTOR(Op, DAG);
3998   case ISD::INSERT_VECTOR_ELT:
3999     return lowerINSERT_VECTOR_ELT(Op, DAG);
4000   case ISD::EXTRACT_VECTOR_ELT:
4001     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4002   case ISD::VECTOR_SHUFFLE:
4003     return lowerVECTOR_SHUFFLE(Op, DAG);
4004   case ISD::BUILD_VECTOR:
4005     return lowerBUILD_VECTOR(Op, DAG);
4006   case ISD::FP_ROUND:
4007     return lowerFP_ROUND(Op, DAG);
4008   case ISD::TRAP:
4009     return lowerTRAP(Op, DAG);
4010   case ISD::DEBUGTRAP:
4011     return lowerDEBUGTRAP(Op, DAG);
4012   case ISD::FABS:
4013   case ISD::FNEG:
4014   case ISD::FCANONICALIZE:
4015     return splitUnaryVectorOp(Op, DAG);
4016   case ISD::FMINNUM:
4017   case ISD::FMAXNUM:
4018     return lowerFMINNUM_FMAXNUM(Op, DAG);
4019   case ISD::FMA:
4020     return splitTernaryVectorOp(Op, DAG);
4021   case ISD::SHL:
4022   case ISD::SRA:
4023   case ISD::SRL:
4024   case ISD::ADD:
4025   case ISD::SUB:
4026   case ISD::MUL:
4027   case ISD::SMIN:
4028   case ISD::SMAX:
4029   case ISD::UMIN:
4030   case ISD::UMAX:
4031   case ISD::FADD:
4032   case ISD::FMUL:
4033   case ISD::FMINNUM_IEEE:
4034   case ISD::FMAXNUM_IEEE:
4035     return splitBinaryVectorOp(Op, DAG);
4036   }
4037   return SDValue();
4038 }
4039 
4040 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4041                                        const SDLoc &DL,
4042                                        SelectionDAG &DAG, bool Unpacked) {
4043   if (!LoadVT.isVector())
4044     return Result;
4045 
4046   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4047     // Truncate to v2i16/v4i16.
4048     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4049 
4050     // Workaround legalizer not scalarizing truncate after vector op
4051     // legalization byt not creating intermediate vector trunc.
4052     SmallVector<SDValue, 4> Elts;
4053     DAG.ExtractVectorElements(Result, Elts);
4054     for (SDValue &Elt : Elts)
4055       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4056 
4057     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4058 
4059     // Bitcast to original type (v2f16/v4f16).
4060     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4061   }
4062 
4063   // Cast back to the original packed type.
4064   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4065 }
4066 
4067 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4068                                               MemSDNode *M,
4069                                               SelectionDAG &DAG,
4070                                               ArrayRef<SDValue> Ops,
4071                                               bool IsIntrinsic) const {
4072   SDLoc DL(M);
4073 
4074   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4075   EVT LoadVT = M->getValueType(0);
4076 
4077   EVT EquivLoadVT = LoadVT;
4078   if (Unpacked && LoadVT.isVector()) {
4079     EquivLoadVT = LoadVT.isVector() ?
4080       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4081                        LoadVT.getVectorNumElements()) : LoadVT;
4082   }
4083 
4084   // Change from v4f16/v2f16 to EquivLoadVT.
4085   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4086 
4087   SDValue Load
4088     = DAG.getMemIntrinsicNode(
4089       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4090       VTList, Ops, M->getMemoryVT(),
4091       M->getMemOperand());
4092   if (!Unpacked) // Just adjusted the opcode.
4093     return Load;
4094 
4095   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4096 
4097   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4098 }
4099 
4100 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4101                                              SelectionDAG &DAG,
4102                                              ArrayRef<SDValue> Ops) const {
4103   SDLoc DL(M);
4104   EVT LoadVT = M->getValueType(0);
4105   EVT EltType = LoadVT.getScalarType();
4106   EVT IntVT = LoadVT.changeTypeToInteger();
4107 
4108   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4109 
4110   unsigned Opc =
4111       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4112 
4113   if (IsD16) {
4114     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4115   }
4116 
4117   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4118   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4119     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4120 
4121   if (isTypeLegal(LoadVT)) {
4122     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4123                                M->getMemOperand(), DAG);
4124   }
4125 
4126   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4127   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4128   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4129                                         M->getMemOperand(), DAG);
4130   return DAG.getMergeValues(
4131       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4132       DL);
4133 }
4134 
4135 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4136                                   SDNode *N, SelectionDAG &DAG) {
4137   EVT VT = N->getValueType(0);
4138   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4139   int CondCode = CD->getSExtValue();
4140   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4141       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4142     return DAG.getUNDEF(VT);
4143 
4144   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4145 
4146   SDValue LHS = N->getOperand(1);
4147   SDValue RHS = N->getOperand(2);
4148 
4149   SDLoc DL(N);
4150 
4151   EVT CmpVT = LHS.getValueType();
4152   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4153     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4154       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4155     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4156     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4157   }
4158 
4159   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4160 
4161   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4162   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4163 
4164   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4165                               DAG.getCondCode(CCOpcode));
4166   if (VT.bitsEq(CCVT))
4167     return SetCC;
4168   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4169 }
4170 
4171 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4172                                   SDNode *N, SelectionDAG &DAG) {
4173   EVT VT = N->getValueType(0);
4174   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4175 
4176   int CondCode = CD->getSExtValue();
4177   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4178       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4179     return DAG.getUNDEF(VT);
4180   }
4181 
4182   SDValue Src0 = N->getOperand(1);
4183   SDValue Src1 = N->getOperand(2);
4184   EVT CmpVT = Src0.getValueType();
4185   SDLoc SL(N);
4186 
4187   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4188     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4189     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4190   }
4191 
4192   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4193   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4194   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4195   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4196   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4197                               Src1, DAG.getCondCode(CCOpcode));
4198   if (VT.bitsEq(CCVT))
4199     return SetCC;
4200   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4201 }
4202 
4203 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4204                                           SmallVectorImpl<SDValue> &Results,
4205                                           SelectionDAG &DAG) const {
4206   switch (N->getOpcode()) {
4207   case ISD::INSERT_VECTOR_ELT: {
4208     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4209       Results.push_back(Res);
4210     return;
4211   }
4212   case ISD::EXTRACT_VECTOR_ELT: {
4213     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4214       Results.push_back(Res);
4215     return;
4216   }
4217   case ISD::INTRINSIC_WO_CHAIN: {
4218     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4219     switch (IID) {
4220     case Intrinsic::amdgcn_cvt_pkrtz: {
4221       SDValue Src0 = N->getOperand(1);
4222       SDValue Src1 = N->getOperand(2);
4223       SDLoc SL(N);
4224       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4225                                 Src0, Src1);
4226       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4227       return;
4228     }
4229     case Intrinsic::amdgcn_cvt_pknorm_i16:
4230     case Intrinsic::amdgcn_cvt_pknorm_u16:
4231     case Intrinsic::amdgcn_cvt_pk_i16:
4232     case Intrinsic::amdgcn_cvt_pk_u16: {
4233       SDValue Src0 = N->getOperand(1);
4234       SDValue Src1 = N->getOperand(2);
4235       SDLoc SL(N);
4236       unsigned Opcode;
4237 
4238       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4239         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4240       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4241         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4242       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4243         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4244       else
4245         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4246 
4247       EVT VT = N->getValueType(0);
4248       if (isTypeLegal(VT))
4249         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4250       else {
4251         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4252         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4253       }
4254       return;
4255     }
4256     }
4257     break;
4258   }
4259   case ISD::INTRINSIC_W_CHAIN: {
4260     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4261       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4262         // FIXME: Hacky
4263         Results.push_back(Res.getOperand(0));
4264         Results.push_back(Res.getOperand(1));
4265       } else {
4266         Results.push_back(Res);
4267         Results.push_back(Res.getValue(1));
4268       }
4269       return;
4270     }
4271 
4272     break;
4273   }
4274   case ISD::SELECT: {
4275     SDLoc SL(N);
4276     EVT VT = N->getValueType(0);
4277     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4278     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4279     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4280 
4281     EVT SelectVT = NewVT;
4282     if (NewVT.bitsLT(MVT::i32)) {
4283       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4284       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4285       SelectVT = MVT::i32;
4286     }
4287 
4288     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4289                                     N->getOperand(0), LHS, RHS);
4290 
4291     if (NewVT != SelectVT)
4292       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4293     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4294     return;
4295   }
4296   case ISD::FNEG: {
4297     if (N->getValueType(0) != MVT::v2f16)
4298       break;
4299 
4300     SDLoc SL(N);
4301     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4302 
4303     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4304                              BC,
4305                              DAG.getConstant(0x80008000, SL, MVT::i32));
4306     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4307     return;
4308   }
4309   case ISD::FABS: {
4310     if (N->getValueType(0) != MVT::v2f16)
4311       break;
4312 
4313     SDLoc SL(N);
4314     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4315 
4316     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4317                              BC,
4318                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4319     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4320     return;
4321   }
4322   default:
4323     break;
4324   }
4325 }
4326 
4327 /// Helper function for LowerBRCOND
4328 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4329 
4330   SDNode *Parent = Value.getNode();
4331   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4332        I != E; ++I) {
4333 
4334     if (I.getUse().get() != Value)
4335       continue;
4336 
4337     if (I->getOpcode() == Opcode)
4338       return *I;
4339   }
4340   return nullptr;
4341 }
4342 
4343 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4344   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4345     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4346     case Intrinsic::amdgcn_if:
4347       return AMDGPUISD::IF;
4348     case Intrinsic::amdgcn_else:
4349       return AMDGPUISD::ELSE;
4350     case Intrinsic::amdgcn_loop:
4351       return AMDGPUISD::LOOP;
4352     case Intrinsic::amdgcn_end_cf:
4353       llvm_unreachable("should not occur");
4354     default:
4355       return 0;
4356     }
4357   }
4358 
4359   // break, if_break, else_break are all only used as inputs to loop, not
4360   // directly as branch conditions.
4361   return 0;
4362 }
4363 
4364 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4365   const Triple &TT = getTargetMachine().getTargetTriple();
4366   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4367           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4368          AMDGPU::shouldEmitConstantsToTextSection(TT);
4369 }
4370 
4371 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4372   // FIXME: Either avoid relying on address space here or change the default
4373   // address space for functions to avoid the explicit check.
4374   return (GV->getValueType()->isFunctionTy() ||
4375           GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4376           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4377           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4378          !shouldEmitFixup(GV) &&
4379          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4380 }
4381 
4382 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4383   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4384 }
4385 
4386 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4387   if (!GV->hasExternalLinkage())
4388     return true;
4389 
4390   const auto OS = getTargetMachine().getTargetTriple().getOS();
4391   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4392 }
4393 
4394 /// This transforms the control flow intrinsics to get the branch destination as
4395 /// last parameter, also switches branch target with BR if the need arise
4396 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4397                                       SelectionDAG &DAG) const {
4398   SDLoc DL(BRCOND);
4399 
4400   SDNode *Intr = BRCOND.getOperand(1).getNode();
4401   SDValue Target = BRCOND.getOperand(2);
4402   SDNode *BR = nullptr;
4403   SDNode *SetCC = nullptr;
4404 
4405   if (Intr->getOpcode() == ISD::SETCC) {
4406     // As long as we negate the condition everything is fine
4407     SetCC = Intr;
4408     Intr = SetCC->getOperand(0).getNode();
4409 
4410   } else {
4411     // Get the target from BR if we don't negate the condition
4412     BR = findUser(BRCOND, ISD::BR);
4413     Target = BR->getOperand(1);
4414   }
4415 
4416   // FIXME: This changes the types of the intrinsics instead of introducing new
4417   // nodes with the correct types.
4418   // e.g. llvm.amdgcn.loop
4419 
4420   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4421   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4422 
4423   unsigned CFNode = isCFIntrinsic(Intr);
4424   if (CFNode == 0) {
4425     // This is a uniform branch so we don't need to legalize.
4426     return BRCOND;
4427   }
4428 
4429   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4430                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4431 
4432   assert(!SetCC ||
4433         (SetCC->getConstantOperandVal(1) == 1 &&
4434          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4435                                                              ISD::SETNE));
4436 
4437   // operands of the new intrinsic call
4438   SmallVector<SDValue, 4> Ops;
4439   if (HaveChain)
4440     Ops.push_back(BRCOND.getOperand(0));
4441 
4442   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4443   Ops.push_back(Target);
4444 
4445   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4446 
4447   // build the new intrinsic call
4448   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4449 
4450   if (!HaveChain) {
4451     SDValue Ops[] =  {
4452       SDValue(Result, 0),
4453       BRCOND.getOperand(0)
4454     };
4455 
4456     Result = DAG.getMergeValues(Ops, DL).getNode();
4457   }
4458 
4459   if (BR) {
4460     // Give the branch instruction our target
4461     SDValue Ops[] = {
4462       BR->getOperand(0),
4463       BRCOND.getOperand(2)
4464     };
4465     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4466     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4467     BR = NewBR.getNode();
4468   }
4469 
4470   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4471 
4472   // Copy the intrinsic results to registers
4473   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4474     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4475     if (!CopyToReg)
4476       continue;
4477 
4478     Chain = DAG.getCopyToReg(
4479       Chain, DL,
4480       CopyToReg->getOperand(1),
4481       SDValue(Result, i - 1),
4482       SDValue());
4483 
4484     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4485   }
4486 
4487   // Remove the old intrinsic from the chain
4488   DAG.ReplaceAllUsesOfValueWith(
4489     SDValue(Intr, Intr->getNumValues() - 1),
4490     Intr->getOperand(0));
4491 
4492   return Chain;
4493 }
4494 
4495 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4496                                           SelectionDAG &DAG) const {
4497   MVT VT = Op.getSimpleValueType();
4498   SDLoc DL(Op);
4499   // Checking the depth
4500   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4501     return DAG.getConstant(0, DL, VT);
4502 
4503   MachineFunction &MF = DAG.getMachineFunction();
4504   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4505   // Check for kernel and shader functions
4506   if (Info->isEntryFunction())
4507     return DAG.getConstant(0, DL, VT);
4508 
4509   MachineFrameInfo &MFI = MF.getFrameInfo();
4510   // There is a call to @llvm.returnaddress in this function
4511   MFI.setReturnAddressIsTaken(true);
4512 
4513   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4514   // Get the return address reg and mark it as an implicit live-in
4515   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4516 
4517   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4518 }
4519 
4520 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4521                                             SDValue Op,
4522                                             const SDLoc &DL,
4523                                             EVT VT) const {
4524   return Op.getValueType().bitsLE(VT) ?
4525       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4526       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4527 }
4528 
4529 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4530   assert(Op.getValueType() == MVT::f16 &&
4531          "Do not know how to custom lower FP_ROUND for non-f16 type");
4532 
4533   SDValue Src = Op.getOperand(0);
4534   EVT SrcVT = Src.getValueType();
4535   if (SrcVT != MVT::f64)
4536     return Op;
4537 
4538   SDLoc DL(Op);
4539 
4540   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4541   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4542   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4543 }
4544 
4545 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4546                                                SelectionDAG &DAG) const {
4547   EVT VT = Op.getValueType();
4548   const MachineFunction &MF = DAG.getMachineFunction();
4549   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4550   bool IsIEEEMode = Info->getMode().IEEE;
4551 
4552   // FIXME: Assert during eslection that this is only selected for
4553   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4554   // mode functions, but this happens to be OK since it's only done in cases
4555   // where there is known no sNaN.
4556   if (IsIEEEMode)
4557     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4558 
4559   if (VT == MVT::v4f16)
4560     return splitBinaryVectorOp(Op, DAG);
4561   return Op;
4562 }
4563 
4564 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4565   SDLoc SL(Op);
4566   SDValue Chain = Op.getOperand(0);
4567 
4568   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4569       !Subtarget->isTrapHandlerEnabled())
4570     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4571 
4572   MachineFunction &MF = DAG.getMachineFunction();
4573   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4574   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4575   assert(UserSGPR != AMDGPU::NoRegister);
4576   SDValue QueuePtr = CreateLiveInRegister(
4577     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4578   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4579   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4580                                    QueuePtr, SDValue());
4581   SDValue Ops[] = {
4582     ToReg,
4583     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4584     SGPR01,
4585     ToReg.getValue(1)
4586   };
4587   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4588 }
4589 
4590 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4591   SDLoc SL(Op);
4592   SDValue Chain = Op.getOperand(0);
4593   MachineFunction &MF = DAG.getMachineFunction();
4594 
4595   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4596       !Subtarget->isTrapHandlerEnabled()) {
4597     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4598                                      "debugtrap handler not supported",
4599                                      Op.getDebugLoc(),
4600                                      DS_Warning);
4601     LLVMContext &Ctx = MF.getFunction().getContext();
4602     Ctx.diagnose(NoTrap);
4603     return Chain;
4604   }
4605 
4606   SDValue Ops[] = {
4607     Chain,
4608     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4609   };
4610   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4611 }
4612 
4613 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4614                                              SelectionDAG &DAG) const {
4615   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4616   if (Subtarget->hasApertureRegs()) {
4617     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4618         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4619         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4620     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4621         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4622         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4623     unsigned Encoding =
4624         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4625         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4626         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4627 
4628     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4629     SDValue ApertureReg = SDValue(
4630         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4631     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4632     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4633   }
4634 
4635   MachineFunction &MF = DAG.getMachineFunction();
4636   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4637   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4638   assert(UserSGPR != AMDGPU::NoRegister);
4639 
4640   SDValue QueuePtr = CreateLiveInRegister(
4641     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4642 
4643   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4644   // private_segment_aperture_base_hi.
4645   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4646 
4647   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4648 
4649   // TODO: Use custom target PseudoSourceValue.
4650   // TODO: We should use the value from the IR intrinsic call, but it might not
4651   // be available and how do we get it?
4652   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4653   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4654                      MinAlign(64, StructOffset),
4655                      MachineMemOperand::MODereferenceable |
4656                          MachineMemOperand::MOInvariant);
4657 }
4658 
4659 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4660                                              SelectionDAG &DAG) const {
4661   SDLoc SL(Op);
4662   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4663 
4664   SDValue Src = ASC->getOperand(0);
4665   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4666 
4667   const AMDGPUTargetMachine &TM =
4668     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4669 
4670   // flat -> local/private
4671   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4672     unsigned DestAS = ASC->getDestAddressSpace();
4673 
4674     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4675         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4676       unsigned NullVal = TM.getNullPointerValue(DestAS);
4677       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4678       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4679       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4680 
4681       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4682                          NonNull, Ptr, SegmentNullPtr);
4683     }
4684   }
4685 
4686   // local/private -> flat
4687   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4688     unsigned SrcAS = ASC->getSrcAddressSpace();
4689 
4690     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4691         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4692       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4693       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4694 
4695       SDValue NonNull
4696         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4697 
4698       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4699       SDValue CvtPtr
4700         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4701 
4702       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4703                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4704                          FlatNullPtr);
4705     }
4706   }
4707 
4708   // global <-> flat are no-ops and never emitted.
4709 
4710   const MachineFunction &MF = DAG.getMachineFunction();
4711   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4712     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4713   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4714 
4715   return DAG.getUNDEF(ASC->getValueType(0));
4716 }
4717 
4718 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4719 // the small vector and inserting them into the big vector. That is better than
4720 // the default expansion of doing it via a stack slot. Even though the use of
4721 // the stack slot would be optimized away afterwards, the stack slot itself
4722 // remains.
4723 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4724                                                 SelectionDAG &DAG) const {
4725   SDValue Vec = Op.getOperand(0);
4726   SDValue Ins = Op.getOperand(1);
4727   SDValue Idx = Op.getOperand(2);
4728   EVT VecVT = Vec.getValueType();
4729   EVT InsVT = Ins.getValueType();
4730   EVT EltVT = VecVT.getVectorElementType();
4731   unsigned InsNumElts = InsVT.getVectorNumElements();
4732   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4733   SDLoc SL(Op);
4734 
4735   for (unsigned I = 0; I != InsNumElts; ++I) {
4736     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4737                               DAG.getConstant(I, SL, MVT::i32));
4738     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4739                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4740   }
4741   return Vec;
4742 }
4743 
4744 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4745                                                  SelectionDAG &DAG) const {
4746   SDValue Vec = Op.getOperand(0);
4747   SDValue InsVal = Op.getOperand(1);
4748   SDValue Idx = Op.getOperand(2);
4749   EVT VecVT = Vec.getValueType();
4750   EVT EltVT = VecVT.getVectorElementType();
4751   unsigned VecSize = VecVT.getSizeInBits();
4752   unsigned EltSize = EltVT.getSizeInBits();
4753 
4754 
4755   assert(VecSize <= 64);
4756 
4757   unsigned NumElts = VecVT.getVectorNumElements();
4758   SDLoc SL(Op);
4759   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4760 
4761   if (NumElts == 4 && EltSize == 16 && KIdx) {
4762     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4763 
4764     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4765                                  DAG.getConstant(0, SL, MVT::i32));
4766     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4767                                  DAG.getConstant(1, SL, MVT::i32));
4768 
4769     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4770     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4771 
4772     unsigned Idx = KIdx->getZExtValue();
4773     bool InsertLo = Idx < 2;
4774     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4775       InsertLo ? LoVec : HiVec,
4776       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4777       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4778 
4779     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4780 
4781     SDValue Concat = InsertLo ?
4782       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4783       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4784 
4785     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4786   }
4787 
4788   if (isa<ConstantSDNode>(Idx))
4789     return SDValue();
4790 
4791   MVT IntVT = MVT::getIntegerVT(VecSize);
4792 
4793   // Avoid stack access for dynamic indexing.
4794   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4795 
4796   // Create a congruent vector with the target value in each element so that
4797   // the required element can be masked and ORed into the target vector.
4798   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4799                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4800 
4801   assert(isPowerOf2_32(EltSize));
4802   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4803 
4804   // Convert vector index to bit-index.
4805   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4806 
4807   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4808   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4809                             DAG.getConstant(0xffff, SL, IntVT),
4810                             ScaledIdx);
4811 
4812   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4813   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4814                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4815 
4816   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4817   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4818 }
4819 
4820 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4821                                                   SelectionDAG &DAG) const {
4822   SDLoc SL(Op);
4823 
4824   EVT ResultVT = Op.getValueType();
4825   SDValue Vec = Op.getOperand(0);
4826   SDValue Idx = Op.getOperand(1);
4827   EVT VecVT = Vec.getValueType();
4828   unsigned VecSize = VecVT.getSizeInBits();
4829   EVT EltVT = VecVT.getVectorElementType();
4830   assert(VecSize <= 64);
4831 
4832   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4833 
4834   // Make sure we do any optimizations that will make it easier to fold
4835   // source modifiers before obscuring it with bit operations.
4836 
4837   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4838   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4839     return Combined;
4840 
4841   unsigned EltSize = EltVT.getSizeInBits();
4842   assert(isPowerOf2_32(EltSize));
4843 
4844   MVT IntVT = MVT::getIntegerVT(VecSize);
4845   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4846 
4847   // Convert vector index to bit-index (* EltSize)
4848   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4849 
4850   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4851   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4852 
4853   if (ResultVT == MVT::f16) {
4854     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4855     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4856   }
4857 
4858   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4859 }
4860 
4861 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4862   assert(Elt % 2 == 0);
4863   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4864 }
4865 
4866 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4867                                               SelectionDAG &DAG) const {
4868   SDLoc SL(Op);
4869   EVT ResultVT = Op.getValueType();
4870   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4871 
4872   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4873   EVT EltVT = PackVT.getVectorElementType();
4874   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4875 
4876   // vector_shuffle <0,1,6,7> lhs, rhs
4877   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4878   //
4879   // vector_shuffle <6,7,2,3> lhs, rhs
4880   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4881   //
4882   // vector_shuffle <6,7,0,1> lhs, rhs
4883   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4884 
4885   // Avoid scalarizing when both halves are reading from consecutive elements.
4886   SmallVector<SDValue, 4> Pieces;
4887   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4888     if (elementPairIsContiguous(SVN->getMask(), I)) {
4889       const int Idx = SVN->getMaskElt(I);
4890       int VecIdx = Idx < SrcNumElts ? 0 : 1;
4891       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4892       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4893                                     PackVT, SVN->getOperand(VecIdx),
4894                                     DAG.getConstant(EltIdx, SL, MVT::i32));
4895       Pieces.push_back(SubVec);
4896     } else {
4897       const int Idx0 = SVN->getMaskElt(I);
4898       const int Idx1 = SVN->getMaskElt(I + 1);
4899       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4900       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
4901       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
4902       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
4903 
4904       SDValue Vec0 = SVN->getOperand(VecIdx0);
4905       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4906                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
4907 
4908       SDValue Vec1 = SVN->getOperand(VecIdx1);
4909       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4910                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
4911       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
4912     }
4913   }
4914 
4915   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
4916 }
4917 
4918 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4919                                             SelectionDAG &DAG) const {
4920   SDLoc SL(Op);
4921   EVT VT = Op.getValueType();
4922 
4923   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4924     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4925 
4926     // Turn into pair of packed build_vectors.
4927     // TODO: Special case for constants that can be materialized with s_mov_b64.
4928     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4929                                     { Op.getOperand(0), Op.getOperand(1) });
4930     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4931                                     { Op.getOperand(2), Op.getOperand(3) });
4932 
4933     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4934     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4935 
4936     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4937     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4938   }
4939 
4940   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4941   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4942 
4943   SDValue Lo = Op.getOperand(0);
4944   SDValue Hi = Op.getOperand(1);
4945 
4946   // Avoid adding defined bits with the zero_extend.
4947   if (Hi.isUndef()) {
4948     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4949     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4950     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4951   }
4952 
4953   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4954   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4955 
4956   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4957                               DAG.getConstant(16, SL, MVT::i32));
4958   if (Lo.isUndef())
4959     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4960 
4961   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4962   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4963 
4964   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4965   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4966 }
4967 
4968 bool
4969 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4970   // We can fold offsets for anything that doesn't require a GOT relocation.
4971   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4972           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4973           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4974          !shouldEmitGOTReloc(GA->getGlobal());
4975 }
4976 
4977 static SDValue
4978 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4979                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
4980                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
4981   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4982   // lowered to the following code sequence:
4983   //
4984   // For constant address space:
4985   //   s_getpc_b64 s[0:1]
4986   //   s_add_u32 s0, s0, $symbol
4987   //   s_addc_u32 s1, s1, 0
4988   //
4989   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4990   //   a fixup or relocation is emitted to replace $symbol with a literal
4991   //   constant, which is a pc-relative offset from the encoding of the $symbol
4992   //   operand to the global variable.
4993   //
4994   // For global address space:
4995   //   s_getpc_b64 s[0:1]
4996   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4997   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4998   //
4999   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5000   //   fixups or relocations are emitted to replace $symbol@*@lo and
5001   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5002   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5003   //   operand to the global variable.
5004   //
5005   // What we want here is an offset from the value returned by s_getpc
5006   // (which is the address of the s_add_u32 instruction) to the global
5007   // variable, but since the encoding of $symbol starts 4 bytes after the start
5008   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5009   // small. This requires us to add 4 to the global variable offset in order to
5010   // compute the correct address.
5011   SDValue PtrLo =
5012       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5013   SDValue PtrHi;
5014   if (GAFlags == SIInstrInfo::MO_NONE) {
5015     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5016   } else {
5017     PtrHi =
5018         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5019   }
5020   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5021 }
5022 
5023 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5024                                              SDValue Op,
5025                                              SelectionDAG &DAG) const {
5026   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5027   const GlobalValue *GV = GSD->getGlobal();
5028   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5029        shouldUseLDSConstAddress(GV)) ||
5030       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5031       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5032     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5033 
5034   SDLoc DL(GSD);
5035   EVT PtrVT = Op.getValueType();
5036 
5037   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5038     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5039                                             SIInstrInfo::MO_ABS32_LO);
5040     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5041   }
5042 
5043   if (shouldEmitFixup(GV))
5044     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5045   else if (shouldEmitPCReloc(GV))
5046     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5047                                    SIInstrInfo::MO_REL32);
5048 
5049   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5050                                             SIInstrInfo::MO_GOTPCREL32);
5051 
5052   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5053   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5054   const DataLayout &DataLayout = DAG.getDataLayout();
5055   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5056   MachinePointerInfo PtrInfo
5057     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5058 
5059   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5060                      MachineMemOperand::MODereferenceable |
5061                          MachineMemOperand::MOInvariant);
5062 }
5063 
5064 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5065                                    const SDLoc &DL, SDValue V) const {
5066   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5067   // the destination register.
5068   //
5069   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5070   // so we will end up with redundant moves to m0.
5071   //
5072   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5073 
5074   // A Null SDValue creates a glue result.
5075   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5076                                   V, Chain);
5077   return SDValue(M0, 0);
5078 }
5079 
5080 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5081                                                  SDValue Op,
5082                                                  MVT VT,
5083                                                  unsigned Offset) const {
5084   SDLoc SL(Op);
5085   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5086                                            DAG.getEntryNode(), Offset, 4, false);
5087   // The local size values will have the hi 16-bits as zero.
5088   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5089                      DAG.getValueType(VT));
5090 }
5091 
5092 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5093                                         EVT VT) {
5094   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5095                                       "non-hsa intrinsic with hsa target",
5096                                       DL.getDebugLoc());
5097   DAG.getContext()->diagnose(BadIntrin);
5098   return DAG.getUNDEF(VT);
5099 }
5100 
5101 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5102                                          EVT VT) {
5103   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5104                                       "intrinsic not supported on subtarget",
5105                                       DL.getDebugLoc());
5106   DAG.getContext()->diagnose(BadIntrin);
5107   return DAG.getUNDEF(VT);
5108 }
5109 
5110 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5111                                     ArrayRef<SDValue> Elts) {
5112   assert(!Elts.empty());
5113   MVT Type;
5114   unsigned NumElts;
5115 
5116   if (Elts.size() == 1) {
5117     Type = MVT::f32;
5118     NumElts = 1;
5119   } else if (Elts.size() == 2) {
5120     Type = MVT::v2f32;
5121     NumElts = 2;
5122   } else if (Elts.size() == 3) {
5123     Type = MVT::v3f32;
5124     NumElts = 3;
5125   } else if (Elts.size() <= 4) {
5126     Type = MVT::v4f32;
5127     NumElts = 4;
5128   } else if (Elts.size() <= 8) {
5129     Type = MVT::v8f32;
5130     NumElts = 8;
5131   } else {
5132     assert(Elts.size() <= 16);
5133     Type = MVT::v16f32;
5134     NumElts = 16;
5135   }
5136 
5137   SmallVector<SDValue, 16> VecElts(NumElts);
5138   for (unsigned i = 0; i < Elts.size(); ++i) {
5139     SDValue Elt = Elts[i];
5140     if (Elt.getValueType() != MVT::f32)
5141       Elt = DAG.getBitcast(MVT::f32, Elt);
5142     VecElts[i] = Elt;
5143   }
5144   for (unsigned i = Elts.size(); i < NumElts; ++i)
5145     VecElts[i] = DAG.getUNDEF(MVT::f32);
5146 
5147   if (NumElts == 1)
5148     return VecElts[0];
5149   return DAG.getBuildVector(Type, DL, VecElts);
5150 }
5151 
5152 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5153                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5154   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5155 
5156   uint64_t Value = CachePolicyConst->getZExtValue();
5157   SDLoc DL(CachePolicy);
5158   if (GLC) {
5159     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5160     Value &= ~(uint64_t)0x1;
5161   }
5162   if (SLC) {
5163     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5164     Value &= ~(uint64_t)0x2;
5165   }
5166   if (DLC) {
5167     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5168     Value &= ~(uint64_t)0x4;
5169   }
5170 
5171   return Value == 0;
5172 }
5173 
5174 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5175                               SDValue Src, int ExtraElts) {
5176   EVT SrcVT = Src.getValueType();
5177 
5178   SmallVector<SDValue, 8> Elts;
5179 
5180   if (SrcVT.isVector())
5181     DAG.ExtractVectorElements(Src, Elts);
5182   else
5183     Elts.push_back(Src);
5184 
5185   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5186   while (ExtraElts--)
5187     Elts.push_back(Undef);
5188 
5189   return DAG.getBuildVector(CastVT, DL, Elts);
5190 }
5191 
5192 // Re-construct the required return value for a image load intrinsic.
5193 // This is more complicated due to the optional use TexFailCtrl which means the required
5194 // return type is an aggregate
5195 static SDValue constructRetValue(SelectionDAG &DAG,
5196                                  MachineSDNode *Result,
5197                                  ArrayRef<EVT> ResultTypes,
5198                                  bool IsTexFail, bool Unpacked, bool IsD16,
5199                                  int DMaskPop, int NumVDataDwords,
5200                                  const SDLoc &DL, LLVMContext &Context) {
5201   // Determine the required return type. This is the same regardless of IsTexFail flag
5202   EVT ReqRetVT = ResultTypes[0];
5203   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5204   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5205     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5206 
5207   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5208     DMaskPop : (DMaskPop + 1) / 2;
5209 
5210   MVT DataDwordVT = NumDataDwords == 1 ?
5211     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5212 
5213   MVT MaskPopVT = MaskPopDwords == 1 ?
5214     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5215 
5216   SDValue Data(Result, 0);
5217   SDValue TexFail;
5218 
5219   if (IsTexFail) {
5220     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5221     if (MaskPopVT.isVector()) {
5222       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5223                          SDValue(Result, 0), ZeroIdx);
5224     } else {
5225       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5226                          SDValue(Result, 0), ZeroIdx);
5227     }
5228 
5229     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5230                           SDValue(Result, 0),
5231                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5232   }
5233 
5234   if (DataDwordVT.isVector())
5235     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5236                           NumDataDwords - MaskPopDwords);
5237 
5238   if (IsD16)
5239     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5240 
5241   if (!ReqRetVT.isVector())
5242     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5243 
5244   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5245 
5246   if (TexFail)
5247     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5248 
5249   if (Result->getNumValues() == 1)
5250     return Data;
5251 
5252   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5253 }
5254 
5255 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5256                          SDValue *LWE, bool &IsTexFail) {
5257   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5258 
5259   uint64_t Value = TexFailCtrlConst->getZExtValue();
5260   if (Value) {
5261     IsTexFail = true;
5262   }
5263 
5264   SDLoc DL(TexFailCtrlConst);
5265   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5266   Value &= ~(uint64_t)0x1;
5267   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5268   Value &= ~(uint64_t)0x2;
5269 
5270   return Value == 0;
5271 }
5272 
5273 SDValue SITargetLowering::lowerImage(SDValue Op,
5274                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5275                                      SelectionDAG &DAG) const {
5276   SDLoc DL(Op);
5277   MachineFunction &MF = DAG.getMachineFunction();
5278   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5279   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5280       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5281   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5282   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5283       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5284   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5285       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5286   unsigned IntrOpcode = Intr->BaseOpcode;
5287   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5288 
5289   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5290   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5291   bool IsD16 = false;
5292   bool IsA16 = false;
5293   SDValue VData;
5294   int NumVDataDwords;
5295   bool AdjustRetType = false;
5296 
5297   unsigned AddrIdx; // Index of first address argument
5298   unsigned DMask;
5299   unsigned DMaskLanes = 0;
5300 
5301   if (BaseOpcode->Atomic) {
5302     VData = Op.getOperand(2);
5303 
5304     bool Is64Bit = VData.getValueType() == MVT::i64;
5305     if (BaseOpcode->AtomicX2) {
5306       SDValue VData2 = Op.getOperand(3);
5307       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5308                                  {VData, VData2});
5309       if (Is64Bit)
5310         VData = DAG.getBitcast(MVT::v4i32, VData);
5311 
5312       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5313       DMask = Is64Bit ? 0xf : 0x3;
5314       NumVDataDwords = Is64Bit ? 4 : 2;
5315       AddrIdx = 4;
5316     } else {
5317       DMask = Is64Bit ? 0x3 : 0x1;
5318       NumVDataDwords = Is64Bit ? 2 : 1;
5319       AddrIdx = 3;
5320     }
5321   } else {
5322     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5323     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5324     DMask = DMaskConst->getZExtValue();
5325     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5326 
5327     if (BaseOpcode->Store) {
5328       VData = Op.getOperand(2);
5329 
5330       MVT StoreVT = VData.getSimpleValueType();
5331       if (StoreVT.getScalarType() == MVT::f16) {
5332         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5333           return Op; // D16 is unsupported for this instruction
5334 
5335         IsD16 = true;
5336         VData = handleD16VData(VData, DAG);
5337       }
5338 
5339       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5340     } else {
5341       // Work out the num dwords based on the dmask popcount and underlying type
5342       // and whether packing is supported.
5343       MVT LoadVT = ResultTypes[0].getSimpleVT();
5344       if (LoadVT.getScalarType() == MVT::f16) {
5345         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5346           return Op; // D16 is unsupported for this instruction
5347 
5348         IsD16 = true;
5349       }
5350 
5351       // Confirm that the return type is large enough for the dmask specified
5352       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5353           (!LoadVT.isVector() && DMaskLanes > 1))
5354           return Op;
5355 
5356       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5357         NumVDataDwords = (DMaskLanes + 1) / 2;
5358       else
5359         NumVDataDwords = DMaskLanes;
5360 
5361       AdjustRetType = true;
5362     }
5363 
5364     AddrIdx = DMaskIdx + 1;
5365   }
5366 
5367   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5368   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5369   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5370   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5371                        NumCoords + NumLCM;
5372   unsigned NumMIVAddrs = NumVAddrs;
5373 
5374   SmallVector<SDValue, 4> VAddrs;
5375 
5376   // Optimize _L to _LZ when _L is zero
5377   if (LZMappingInfo) {
5378     if (auto ConstantLod =
5379          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5380       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5381         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5382         NumMIVAddrs--;               // remove 'lod'
5383       }
5384     }
5385   }
5386 
5387   // Optimize _mip away, when 'lod' is zero
5388   if (MIPMappingInfo) {
5389     if (auto ConstantLod =
5390          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5391       if (ConstantLod->isNullValue()) {
5392         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5393         NumMIVAddrs--;               // remove 'lod'
5394       }
5395     }
5396   }
5397 
5398   // Check for 16 bit addresses and pack if true.
5399   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5400   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5401   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5402   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5403     // Illegal to use a16 images
5404     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5405       return Op;
5406 
5407     IsA16 = true;
5408     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5409     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5410       SDValue AddrLo;
5411       // Push back extra arguments.
5412       if (i < DimIdx) {
5413         AddrLo = Op.getOperand(i);
5414       } else {
5415         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5416         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5417         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5418             ((NumGradients / 2) % 2 == 1 &&
5419             (i == DimIdx + (NumGradients / 2) - 1 ||
5420              i == DimIdx + NumGradients - 1))) {
5421           AddrLo = Op.getOperand(i);
5422           if (AddrLo.getValueType() != MVT::i16)
5423             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5424           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5425         } else {
5426           AddrLo = DAG.getBuildVector(VectorVT, DL,
5427                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5428           i++;
5429         }
5430         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5431       }
5432       VAddrs.push_back(AddrLo);
5433     }
5434   } else {
5435     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5436       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5437   }
5438 
5439   // If the register allocator cannot place the address registers contiguously
5440   // without introducing moves, then using the non-sequential address encoding
5441   // is always preferable, since it saves VALU instructions and is usually a
5442   // wash in terms of code size or even better.
5443   //
5444   // However, we currently have no way of hinting to the register allocator that
5445   // MIMG addresses should be placed contiguously when it is possible to do so,
5446   // so force non-NSA for the common 2-address case as a heuristic.
5447   //
5448   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5449   // allocation when possible.
5450   bool UseNSA =
5451       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5452   SDValue VAddr;
5453   if (!UseNSA)
5454     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5455 
5456   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5457   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5458   unsigned CtrlIdx; // Index of texfailctrl argument
5459   SDValue Unorm;
5460   if (!BaseOpcode->Sampler) {
5461     Unorm = True;
5462     CtrlIdx = AddrIdx + NumVAddrs + 1;
5463   } else {
5464     auto UnormConst =
5465         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5466 
5467     Unorm = UnormConst->getZExtValue() ? True : False;
5468     CtrlIdx = AddrIdx + NumVAddrs + 3;
5469   }
5470 
5471   SDValue TFE;
5472   SDValue LWE;
5473   SDValue TexFail = Op.getOperand(CtrlIdx);
5474   bool IsTexFail = false;
5475   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5476     return Op;
5477 
5478   if (IsTexFail) {
5479     if (!DMaskLanes) {
5480       // Expecting to get an error flag since TFC is on - and dmask is 0
5481       // Force dmask to be at least 1 otherwise the instruction will fail
5482       DMask = 0x1;
5483       DMaskLanes = 1;
5484       NumVDataDwords = 1;
5485     }
5486     NumVDataDwords += 1;
5487     AdjustRetType = true;
5488   }
5489 
5490   // Has something earlier tagged that the return type needs adjusting
5491   // This happens if the instruction is a load or has set TexFailCtrl flags
5492   if (AdjustRetType) {
5493     // NumVDataDwords reflects the true number of dwords required in the return type
5494     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5495       // This is a no-op load. This can be eliminated
5496       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5497       if (isa<MemSDNode>(Op))
5498         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5499       return Undef;
5500     }
5501 
5502     EVT NewVT = NumVDataDwords > 1 ?
5503                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5504                 : MVT::i32;
5505 
5506     ResultTypes[0] = NewVT;
5507     if (ResultTypes.size() == 3) {
5508       // Original result was aggregate type used for TexFailCtrl results
5509       // The actual instruction returns as a vector type which has now been
5510       // created. Remove the aggregate result.
5511       ResultTypes.erase(&ResultTypes[1]);
5512     }
5513   }
5514 
5515   SDValue GLC;
5516   SDValue SLC;
5517   SDValue DLC;
5518   if (BaseOpcode->Atomic) {
5519     GLC = True; // TODO no-return optimization
5520     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5521                           IsGFX10 ? &DLC : nullptr))
5522       return Op;
5523   } else {
5524     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5525                           IsGFX10 ? &DLC : nullptr))
5526       return Op;
5527   }
5528 
5529   SmallVector<SDValue, 26> Ops;
5530   if (BaseOpcode->Store || BaseOpcode->Atomic)
5531     Ops.push_back(VData); // vdata
5532   if (UseNSA) {
5533     for (const SDValue &Addr : VAddrs)
5534       Ops.push_back(Addr);
5535   } else {
5536     Ops.push_back(VAddr);
5537   }
5538   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5539   if (BaseOpcode->Sampler)
5540     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5541   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5542   if (IsGFX10)
5543     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5544   Ops.push_back(Unorm);
5545   if (IsGFX10)
5546     Ops.push_back(DLC);
5547   Ops.push_back(GLC);
5548   Ops.push_back(SLC);
5549   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5550                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5551   if (IsGFX10)
5552     Ops.push_back(IsA16 ? True : False);
5553   Ops.push_back(TFE);
5554   Ops.push_back(LWE);
5555   if (!IsGFX10)
5556     Ops.push_back(DimInfo->DA ? True : False);
5557   if (BaseOpcode->HasD16)
5558     Ops.push_back(IsD16 ? True : False);
5559   if (isa<MemSDNode>(Op))
5560     Ops.push_back(Op.getOperand(0)); // chain
5561 
5562   int NumVAddrDwords =
5563       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5564   int Opcode = -1;
5565 
5566   if (IsGFX10) {
5567     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5568                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5569                                           : AMDGPU::MIMGEncGfx10Default,
5570                                    NumVDataDwords, NumVAddrDwords);
5571   } else {
5572     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5573       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5574                                      NumVDataDwords, NumVAddrDwords);
5575     if (Opcode == -1)
5576       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5577                                      NumVDataDwords, NumVAddrDwords);
5578   }
5579   assert(Opcode != -1);
5580 
5581   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5582   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5583     MachineMemOperand *MemRef = MemOp->getMemOperand();
5584     DAG.setNodeMemRefs(NewNode, {MemRef});
5585   }
5586 
5587   if (BaseOpcode->AtomicX2) {
5588     SmallVector<SDValue, 1> Elt;
5589     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5590     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5591   } else if (!BaseOpcode->Store) {
5592     return constructRetValue(DAG, NewNode,
5593                              OrigResultTypes, IsTexFail,
5594                              Subtarget->hasUnpackedD16VMem(), IsD16,
5595                              DMaskLanes, NumVDataDwords, DL,
5596                              *DAG.getContext());
5597   }
5598 
5599   return SDValue(NewNode, 0);
5600 }
5601 
5602 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5603                                        SDValue Offset, SDValue CachePolicy,
5604                                        SelectionDAG &DAG) const {
5605   MachineFunction &MF = DAG.getMachineFunction();
5606 
5607   const DataLayout &DataLayout = DAG.getDataLayout();
5608   unsigned Align =
5609       DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5610 
5611   MachineMemOperand *MMO = MF.getMachineMemOperand(
5612       MachinePointerInfo(),
5613       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5614           MachineMemOperand::MOInvariant,
5615       VT.getStoreSize(), Align);
5616 
5617   if (!Offset->isDivergent()) {
5618     SDValue Ops[] = {
5619         Rsrc,
5620         Offset, // Offset
5621         CachePolicy
5622     };
5623 
5624     // Widen vec3 load to vec4.
5625     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5626       EVT WidenedVT =
5627           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5628       auto WidenedOp = DAG.getMemIntrinsicNode(
5629           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5630           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5631       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5632                                    DAG.getVectorIdxConstant(0, DL));
5633       return Subvector;
5634     }
5635 
5636     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5637                                    DAG.getVTList(VT), Ops, VT, MMO);
5638   }
5639 
5640   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5641   // assume that the buffer is unswizzled.
5642   SmallVector<SDValue, 4> Loads;
5643   unsigned NumLoads = 1;
5644   MVT LoadVT = VT.getSimpleVT();
5645   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5646   assert((LoadVT.getScalarType() == MVT::i32 ||
5647           LoadVT.getScalarType() == MVT::f32));
5648 
5649   if (NumElts == 8 || NumElts == 16) {
5650     NumLoads = NumElts / 4;
5651     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5652   }
5653 
5654   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5655   SDValue Ops[] = {
5656       DAG.getEntryNode(),                               // Chain
5657       Rsrc,                                             // rsrc
5658       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5659       {},                                               // voffset
5660       {},                                               // soffset
5661       {},                                               // offset
5662       CachePolicy,                                      // cachepolicy
5663       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5664   };
5665 
5666   // Use the alignment to ensure that the required offsets will fit into the
5667   // immediate offsets.
5668   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5669 
5670   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5671   for (unsigned i = 0; i < NumLoads; ++i) {
5672     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5673     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5674                                         LoadVT, MMO, DAG));
5675   }
5676 
5677   if (NumElts == 8 || NumElts == 16)
5678     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5679 
5680   return Loads[0];
5681 }
5682 
5683 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5684                                                   SelectionDAG &DAG) const {
5685   MachineFunction &MF = DAG.getMachineFunction();
5686   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5687 
5688   EVT VT = Op.getValueType();
5689   SDLoc DL(Op);
5690   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5691 
5692   // TODO: Should this propagate fast-math-flags?
5693 
5694   switch (IntrinsicID) {
5695   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5696     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5697       return emitNonHSAIntrinsicError(DAG, DL, VT);
5698     return getPreloadedValue(DAG, *MFI, VT,
5699                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5700   }
5701   case Intrinsic::amdgcn_dispatch_ptr:
5702   case Intrinsic::amdgcn_queue_ptr: {
5703     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5704       DiagnosticInfoUnsupported BadIntrin(
5705           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5706           DL.getDebugLoc());
5707       DAG.getContext()->diagnose(BadIntrin);
5708       return DAG.getUNDEF(VT);
5709     }
5710 
5711     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5712       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5713     return getPreloadedValue(DAG, *MFI, VT, RegID);
5714   }
5715   case Intrinsic::amdgcn_implicitarg_ptr: {
5716     if (MFI->isEntryFunction())
5717       return getImplicitArgPtr(DAG, DL);
5718     return getPreloadedValue(DAG, *MFI, VT,
5719                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5720   }
5721   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5722     return getPreloadedValue(DAG, *MFI, VT,
5723                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5724   }
5725   case Intrinsic::amdgcn_dispatch_id: {
5726     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5727   }
5728   case Intrinsic::amdgcn_rcp:
5729     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5730   case Intrinsic::amdgcn_rsq:
5731     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5732   case Intrinsic::amdgcn_rsq_legacy:
5733     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5734       return emitRemovedIntrinsicError(DAG, DL, VT);
5735 
5736     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5737   case Intrinsic::amdgcn_rcp_legacy:
5738     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5739       return emitRemovedIntrinsicError(DAG, DL, VT);
5740     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5741   case Intrinsic::amdgcn_rsq_clamp: {
5742     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5743       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5744 
5745     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5746     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5747     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5748 
5749     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5750     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5751                               DAG.getConstantFP(Max, DL, VT));
5752     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5753                        DAG.getConstantFP(Min, DL, VT));
5754   }
5755   case Intrinsic::r600_read_ngroups_x:
5756     if (Subtarget->isAmdHsaOS())
5757       return emitNonHSAIntrinsicError(DAG, DL, VT);
5758 
5759     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5760                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5761   case Intrinsic::r600_read_ngroups_y:
5762     if (Subtarget->isAmdHsaOS())
5763       return emitNonHSAIntrinsicError(DAG, DL, VT);
5764 
5765     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5766                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5767   case Intrinsic::r600_read_ngroups_z:
5768     if (Subtarget->isAmdHsaOS())
5769       return emitNonHSAIntrinsicError(DAG, DL, VT);
5770 
5771     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5772                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5773   case Intrinsic::r600_read_global_size_x:
5774     if (Subtarget->isAmdHsaOS())
5775       return emitNonHSAIntrinsicError(DAG, DL, VT);
5776 
5777     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5778                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5779   case Intrinsic::r600_read_global_size_y:
5780     if (Subtarget->isAmdHsaOS())
5781       return emitNonHSAIntrinsicError(DAG, DL, VT);
5782 
5783     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5784                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5785   case Intrinsic::r600_read_global_size_z:
5786     if (Subtarget->isAmdHsaOS())
5787       return emitNonHSAIntrinsicError(DAG, DL, VT);
5788 
5789     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5790                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5791   case Intrinsic::r600_read_local_size_x:
5792     if (Subtarget->isAmdHsaOS())
5793       return emitNonHSAIntrinsicError(DAG, DL, VT);
5794 
5795     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5796                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5797   case Intrinsic::r600_read_local_size_y:
5798     if (Subtarget->isAmdHsaOS())
5799       return emitNonHSAIntrinsicError(DAG, DL, VT);
5800 
5801     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5802                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5803   case Intrinsic::r600_read_local_size_z:
5804     if (Subtarget->isAmdHsaOS())
5805       return emitNonHSAIntrinsicError(DAG, DL, VT);
5806 
5807     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5808                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5809   case Intrinsic::amdgcn_workgroup_id_x:
5810     return getPreloadedValue(DAG, *MFI, VT,
5811                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5812   case Intrinsic::amdgcn_workgroup_id_y:
5813     return getPreloadedValue(DAG, *MFI, VT,
5814                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5815   case Intrinsic::amdgcn_workgroup_id_z:
5816     return getPreloadedValue(DAG, *MFI, VT,
5817                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5818   case Intrinsic::amdgcn_workitem_id_x:
5819     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5820                           SDLoc(DAG.getEntryNode()),
5821                           MFI->getArgInfo().WorkItemIDX);
5822   case Intrinsic::amdgcn_workitem_id_y:
5823     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5824                           SDLoc(DAG.getEntryNode()),
5825                           MFI->getArgInfo().WorkItemIDY);
5826   case Intrinsic::amdgcn_workitem_id_z:
5827     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5828                           SDLoc(DAG.getEntryNode()),
5829                           MFI->getArgInfo().WorkItemIDZ);
5830   case Intrinsic::amdgcn_wavefrontsize:
5831     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5832                            SDLoc(Op), MVT::i32);
5833   case Intrinsic::amdgcn_s_buffer_load: {
5834     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5835     SDValue GLC;
5836     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5837     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5838                           IsGFX10 ? &DLC : nullptr))
5839       return Op;
5840     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5841                         DAG);
5842   }
5843   case Intrinsic::amdgcn_fdiv_fast:
5844     return lowerFDIV_FAST(Op, DAG);
5845   case Intrinsic::amdgcn_sin:
5846     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5847 
5848   case Intrinsic::amdgcn_cos:
5849     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5850 
5851   case Intrinsic::amdgcn_mul_u24:
5852     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5853   case Intrinsic::amdgcn_mul_i24:
5854     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5855 
5856   case Intrinsic::amdgcn_log_clamp: {
5857     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5858       return SDValue();
5859 
5860     DiagnosticInfoUnsupported BadIntrin(
5861       MF.getFunction(), "intrinsic not supported on subtarget",
5862       DL.getDebugLoc());
5863       DAG.getContext()->diagnose(BadIntrin);
5864       return DAG.getUNDEF(VT);
5865   }
5866   case Intrinsic::amdgcn_ldexp:
5867     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5868                        Op.getOperand(1), Op.getOperand(2));
5869 
5870   case Intrinsic::amdgcn_fract:
5871     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5872 
5873   case Intrinsic::amdgcn_class:
5874     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5875                        Op.getOperand(1), Op.getOperand(2));
5876   case Intrinsic::amdgcn_div_fmas:
5877     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5878                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5879                        Op.getOperand(4));
5880 
5881   case Intrinsic::amdgcn_div_fixup:
5882     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5883                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5884 
5885   case Intrinsic::amdgcn_trig_preop:
5886     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5887                        Op.getOperand(1), Op.getOperand(2));
5888   case Intrinsic::amdgcn_div_scale: {
5889     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5890 
5891     // Translate to the operands expected by the machine instruction. The
5892     // first parameter must be the same as the first instruction.
5893     SDValue Numerator = Op.getOperand(1);
5894     SDValue Denominator = Op.getOperand(2);
5895 
5896     // Note this order is opposite of the machine instruction's operations,
5897     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5898     // intrinsic has the numerator as the first operand to match a normal
5899     // division operation.
5900 
5901     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5902 
5903     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5904                        Denominator, Numerator);
5905   }
5906   case Intrinsic::amdgcn_icmp: {
5907     // There is a Pat that handles this variant, so return it as-is.
5908     if (Op.getOperand(1).getValueType() == MVT::i1 &&
5909         Op.getConstantOperandVal(2) == 0 &&
5910         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
5911       return Op;
5912     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
5913   }
5914   case Intrinsic::amdgcn_fcmp: {
5915     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
5916   }
5917   case Intrinsic::amdgcn_fmed3:
5918     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
5919                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5920   case Intrinsic::amdgcn_fdot2:
5921     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
5922                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5923                        Op.getOperand(4));
5924   case Intrinsic::amdgcn_fmul_legacy:
5925     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
5926                        Op.getOperand(1), Op.getOperand(2));
5927   case Intrinsic::amdgcn_sffbh:
5928     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
5929   case Intrinsic::amdgcn_sbfe:
5930     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
5931                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5932   case Intrinsic::amdgcn_ubfe:
5933     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
5934                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5935   case Intrinsic::amdgcn_cvt_pkrtz:
5936   case Intrinsic::amdgcn_cvt_pknorm_i16:
5937   case Intrinsic::amdgcn_cvt_pknorm_u16:
5938   case Intrinsic::amdgcn_cvt_pk_i16:
5939   case Intrinsic::amdgcn_cvt_pk_u16: {
5940     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
5941     EVT VT = Op.getValueType();
5942     unsigned Opcode;
5943 
5944     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
5945       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
5946     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
5947       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5948     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
5949       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5950     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
5951       Opcode = AMDGPUISD::CVT_PK_I16_I32;
5952     else
5953       Opcode = AMDGPUISD::CVT_PK_U16_U32;
5954 
5955     if (isTypeLegal(VT))
5956       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
5957 
5958     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
5959                                Op.getOperand(1), Op.getOperand(2));
5960     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
5961   }
5962   case Intrinsic::amdgcn_fmad_ftz:
5963     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
5964                        Op.getOperand(2), Op.getOperand(3));
5965 
5966   case Intrinsic::amdgcn_if_break:
5967     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
5968                                       Op->getOperand(1), Op->getOperand(2)), 0);
5969 
5970   case Intrinsic::amdgcn_groupstaticsize: {
5971     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
5972     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
5973       return Op;
5974 
5975     const Module *M = MF.getFunction().getParent();
5976     const GlobalValue *GV =
5977         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
5978     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
5979                                             SIInstrInfo::MO_ABS32_LO);
5980     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
5981   }
5982   case Intrinsic::amdgcn_is_shared:
5983   case Intrinsic::amdgcn_is_private: {
5984     SDLoc SL(Op);
5985     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
5986       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
5987     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
5988     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
5989                                  Op.getOperand(1));
5990 
5991     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
5992                                 DAG.getConstant(1, SL, MVT::i32));
5993     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
5994   }
5995   default:
5996     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5997             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5998       return lowerImage(Op, ImageDimIntr, DAG);
5999 
6000     return Op;
6001   }
6002 }
6003 
6004 // This function computes an appropriate offset to pass to
6005 // MachineMemOperand::setOffset() based on the offset inputs to
6006 // an intrinsic.  If any of the offsets are non-contstant or
6007 // if VIndex is non-zero then this function returns 0.  Otherwise,
6008 // it returns the sum of VOffset, SOffset, and Offset.
6009 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6010                                       SDValue SOffset,
6011                                       SDValue Offset,
6012                                       SDValue VIndex = SDValue()) {
6013 
6014   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6015       !isa<ConstantSDNode>(Offset))
6016     return 0;
6017 
6018   if (VIndex) {
6019     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6020       return 0;
6021   }
6022 
6023   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6024          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6025          cast<ConstantSDNode>(Offset)->getSExtValue();
6026 }
6027 
6028 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6029   switch (MF.getFunction().getCallingConv()) {
6030   case CallingConv::AMDGPU_PS:
6031     return 1;
6032   case CallingConv::AMDGPU_VS:
6033     return 2;
6034   case CallingConv::AMDGPU_GS:
6035     return 3;
6036   case CallingConv::AMDGPU_HS:
6037   case CallingConv::AMDGPU_LS:
6038   case CallingConv::AMDGPU_ES:
6039     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6040   case CallingConv::AMDGPU_CS:
6041   case CallingConv::AMDGPU_KERNEL:
6042   case CallingConv::C:
6043   case CallingConv::Fast:
6044   default:
6045     // Assume other calling conventions are various compute callable functions
6046     return 0;
6047   }
6048 }
6049 
6050 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6051                                                  SelectionDAG &DAG) const {
6052   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6053   SDLoc DL(Op);
6054 
6055   switch (IntrID) {
6056   case Intrinsic::amdgcn_ds_ordered_add:
6057   case Intrinsic::amdgcn_ds_ordered_swap: {
6058     MemSDNode *M = cast<MemSDNode>(Op);
6059     SDValue Chain = M->getOperand(0);
6060     SDValue M0 = M->getOperand(2);
6061     SDValue Value = M->getOperand(3);
6062     unsigned IndexOperand = M->getConstantOperandVal(7);
6063     unsigned WaveRelease = M->getConstantOperandVal(8);
6064     unsigned WaveDone = M->getConstantOperandVal(9);
6065 
6066     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6067     IndexOperand &= ~0x3f;
6068     unsigned CountDw = 0;
6069 
6070     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6071       CountDw = (IndexOperand >> 24) & 0xf;
6072       IndexOperand &= ~(0xf << 24);
6073 
6074       if (CountDw < 1 || CountDw > 4) {
6075         report_fatal_error(
6076             "ds_ordered_count: dword count must be between 1 and 4");
6077       }
6078     }
6079 
6080     if (IndexOperand)
6081       report_fatal_error("ds_ordered_count: bad index operand");
6082 
6083     if (WaveDone && !WaveRelease)
6084       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6085 
6086     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6087     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6088     unsigned Offset0 = OrderedCountIndex << 2;
6089     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6090                        (Instruction << 4);
6091 
6092     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6093       Offset1 |= (CountDw - 1) << 6;
6094 
6095     unsigned Offset = Offset0 | (Offset1 << 8);
6096 
6097     SDValue Ops[] = {
6098       Chain,
6099       Value,
6100       DAG.getTargetConstant(Offset, DL, MVT::i16),
6101       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6102     };
6103     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6104                                    M->getVTList(), Ops, M->getMemoryVT(),
6105                                    M->getMemOperand());
6106   }
6107   case Intrinsic::amdgcn_ds_fadd: {
6108     MemSDNode *M = cast<MemSDNode>(Op);
6109     unsigned Opc;
6110     switch (IntrID) {
6111     case Intrinsic::amdgcn_ds_fadd:
6112       Opc = ISD::ATOMIC_LOAD_FADD;
6113       break;
6114     }
6115 
6116     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6117                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6118                          M->getMemOperand());
6119   }
6120   case Intrinsic::amdgcn_atomic_inc:
6121   case Intrinsic::amdgcn_atomic_dec:
6122   case Intrinsic::amdgcn_ds_fmin:
6123   case Intrinsic::amdgcn_ds_fmax: {
6124     MemSDNode *M = cast<MemSDNode>(Op);
6125     unsigned Opc;
6126     switch (IntrID) {
6127     case Intrinsic::amdgcn_atomic_inc:
6128       Opc = AMDGPUISD::ATOMIC_INC;
6129       break;
6130     case Intrinsic::amdgcn_atomic_dec:
6131       Opc = AMDGPUISD::ATOMIC_DEC;
6132       break;
6133     case Intrinsic::amdgcn_ds_fmin:
6134       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6135       break;
6136     case Intrinsic::amdgcn_ds_fmax:
6137       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6138       break;
6139     default:
6140       llvm_unreachable("Unknown intrinsic!");
6141     }
6142     SDValue Ops[] = {
6143       M->getOperand(0), // Chain
6144       M->getOperand(2), // Ptr
6145       M->getOperand(3)  // Value
6146     };
6147 
6148     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6149                                    M->getMemoryVT(), M->getMemOperand());
6150   }
6151   case Intrinsic::amdgcn_buffer_load:
6152   case Intrinsic::amdgcn_buffer_load_format: {
6153     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6154     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6155     unsigned IdxEn = 1;
6156     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6157       IdxEn = Idx->getZExtValue() != 0;
6158     SDValue Ops[] = {
6159       Op.getOperand(0), // Chain
6160       Op.getOperand(2), // rsrc
6161       Op.getOperand(3), // vindex
6162       SDValue(),        // voffset -- will be set by setBufferOffsets
6163       SDValue(),        // soffset -- will be set by setBufferOffsets
6164       SDValue(),        // offset -- will be set by setBufferOffsets
6165       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6166       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6167     };
6168 
6169     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6170     // We don't know the offset if vindex is non-zero, so clear it.
6171     if (IdxEn)
6172       Offset = 0;
6173 
6174     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6175         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6176 
6177     EVT VT = Op.getValueType();
6178     EVT IntVT = VT.changeTypeToInteger();
6179     auto *M = cast<MemSDNode>(Op);
6180     M->getMemOperand()->setOffset(Offset);
6181     EVT LoadVT = Op.getValueType();
6182 
6183     if (LoadVT.getScalarType() == MVT::f16)
6184       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6185                                  M, DAG, Ops);
6186 
6187     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6188     if (LoadVT.getScalarType() == MVT::i8 ||
6189         LoadVT.getScalarType() == MVT::i16)
6190       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6191 
6192     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6193                                M->getMemOperand(), DAG);
6194   }
6195   case Intrinsic::amdgcn_raw_buffer_load:
6196   case Intrinsic::amdgcn_raw_buffer_load_format: {
6197     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6198 
6199     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6200     SDValue Ops[] = {
6201       Op.getOperand(0), // Chain
6202       Op.getOperand(2), // rsrc
6203       DAG.getConstant(0, DL, MVT::i32), // vindex
6204       Offsets.first,    // voffset
6205       Op.getOperand(4), // soffset
6206       Offsets.second,   // offset
6207       Op.getOperand(5), // cachepolicy, swizzled buffer
6208       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6209     };
6210 
6211     auto *M = cast<MemSDNode>(Op);
6212     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6213     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6214   }
6215   case Intrinsic::amdgcn_struct_buffer_load:
6216   case Intrinsic::amdgcn_struct_buffer_load_format: {
6217     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6218 
6219     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6220     SDValue Ops[] = {
6221       Op.getOperand(0), // Chain
6222       Op.getOperand(2), // rsrc
6223       Op.getOperand(3), // vindex
6224       Offsets.first,    // voffset
6225       Op.getOperand(5), // soffset
6226       Offsets.second,   // offset
6227       Op.getOperand(6), // cachepolicy, swizzled buffer
6228       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6229     };
6230 
6231     auto *M = cast<MemSDNode>(Op);
6232     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6233                                                         Ops[2]));
6234     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6235   }
6236   case Intrinsic::amdgcn_tbuffer_load: {
6237     MemSDNode *M = cast<MemSDNode>(Op);
6238     EVT LoadVT = Op.getValueType();
6239 
6240     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6241     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6242     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6243     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6244     unsigned IdxEn = 1;
6245     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6246       IdxEn = Idx->getZExtValue() != 0;
6247     SDValue Ops[] = {
6248       Op.getOperand(0),  // Chain
6249       Op.getOperand(2),  // rsrc
6250       Op.getOperand(3),  // vindex
6251       Op.getOperand(4),  // voffset
6252       Op.getOperand(5),  // soffset
6253       Op.getOperand(6),  // offset
6254       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6255       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6256       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6257     };
6258 
6259     if (LoadVT.getScalarType() == MVT::f16)
6260       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6261                                  M, DAG, Ops);
6262     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6263                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6264                                DAG);
6265   }
6266   case Intrinsic::amdgcn_raw_tbuffer_load: {
6267     MemSDNode *M = cast<MemSDNode>(Op);
6268     EVT LoadVT = Op.getValueType();
6269     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6270 
6271     SDValue Ops[] = {
6272       Op.getOperand(0),  // Chain
6273       Op.getOperand(2),  // rsrc
6274       DAG.getConstant(0, DL, MVT::i32), // vindex
6275       Offsets.first,     // voffset
6276       Op.getOperand(4),  // soffset
6277       Offsets.second,    // offset
6278       Op.getOperand(5),  // format
6279       Op.getOperand(6),  // cachepolicy, swizzled buffer
6280       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6281     };
6282 
6283     if (LoadVT.getScalarType() == MVT::f16)
6284       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6285                                  M, DAG, Ops);
6286     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6287                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6288                                DAG);
6289   }
6290   case Intrinsic::amdgcn_struct_tbuffer_load: {
6291     MemSDNode *M = cast<MemSDNode>(Op);
6292     EVT LoadVT = Op.getValueType();
6293     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6294 
6295     SDValue Ops[] = {
6296       Op.getOperand(0),  // Chain
6297       Op.getOperand(2),  // rsrc
6298       Op.getOperand(3),  // vindex
6299       Offsets.first,     // voffset
6300       Op.getOperand(5),  // soffset
6301       Offsets.second,    // offset
6302       Op.getOperand(6),  // format
6303       Op.getOperand(7),  // cachepolicy, swizzled buffer
6304       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6305     };
6306 
6307     if (LoadVT.getScalarType() == MVT::f16)
6308       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6309                                  M, DAG, Ops);
6310     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6311                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6312                                DAG);
6313   }
6314   case Intrinsic::amdgcn_buffer_atomic_swap:
6315   case Intrinsic::amdgcn_buffer_atomic_add:
6316   case Intrinsic::amdgcn_buffer_atomic_sub:
6317   case Intrinsic::amdgcn_buffer_atomic_smin:
6318   case Intrinsic::amdgcn_buffer_atomic_umin:
6319   case Intrinsic::amdgcn_buffer_atomic_smax:
6320   case Intrinsic::amdgcn_buffer_atomic_umax:
6321   case Intrinsic::amdgcn_buffer_atomic_and:
6322   case Intrinsic::amdgcn_buffer_atomic_or:
6323   case Intrinsic::amdgcn_buffer_atomic_xor: {
6324     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6325     unsigned IdxEn = 1;
6326     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6327       IdxEn = Idx->getZExtValue() != 0;
6328     SDValue Ops[] = {
6329       Op.getOperand(0), // Chain
6330       Op.getOperand(2), // vdata
6331       Op.getOperand(3), // rsrc
6332       Op.getOperand(4), // vindex
6333       SDValue(),        // voffset -- will be set by setBufferOffsets
6334       SDValue(),        // soffset -- will be set by setBufferOffsets
6335       SDValue(),        // offset -- will be set by setBufferOffsets
6336       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6337       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6338     };
6339     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6340     // We don't know the offset if vindex is non-zero, so clear it.
6341     if (IdxEn)
6342       Offset = 0;
6343     EVT VT = Op.getValueType();
6344 
6345     auto *M = cast<MemSDNode>(Op);
6346     M->getMemOperand()->setOffset(Offset);
6347     unsigned Opcode = 0;
6348 
6349     switch (IntrID) {
6350     case Intrinsic::amdgcn_buffer_atomic_swap:
6351       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6352       break;
6353     case Intrinsic::amdgcn_buffer_atomic_add:
6354       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6355       break;
6356     case Intrinsic::amdgcn_buffer_atomic_sub:
6357       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6358       break;
6359     case Intrinsic::amdgcn_buffer_atomic_smin:
6360       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6361       break;
6362     case Intrinsic::amdgcn_buffer_atomic_umin:
6363       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6364       break;
6365     case Intrinsic::amdgcn_buffer_atomic_smax:
6366       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6367       break;
6368     case Intrinsic::amdgcn_buffer_atomic_umax:
6369       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6370       break;
6371     case Intrinsic::amdgcn_buffer_atomic_and:
6372       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6373       break;
6374     case Intrinsic::amdgcn_buffer_atomic_or:
6375       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6376       break;
6377     case Intrinsic::amdgcn_buffer_atomic_xor:
6378       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6379       break;
6380     default:
6381       llvm_unreachable("unhandled atomic opcode");
6382     }
6383 
6384     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6385                                    M->getMemOperand());
6386   }
6387   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6388   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6389   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6390   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6391   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6392   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6393   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6394   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6395   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6396   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6397   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6398   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6399     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6400     SDValue Ops[] = {
6401       Op.getOperand(0), // Chain
6402       Op.getOperand(2), // vdata
6403       Op.getOperand(3), // rsrc
6404       DAG.getConstant(0, DL, MVT::i32), // vindex
6405       Offsets.first,    // voffset
6406       Op.getOperand(5), // soffset
6407       Offsets.second,   // offset
6408       Op.getOperand(6), // cachepolicy
6409       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6410     };
6411     EVT VT = Op.getValueType();
6412 
6413     auto *M = cast<MemSDNode>(Op);
6414     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6415     unsigned Opcode = 0;
6416 
6417     switch (IntrID) {
6418     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6419       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6420       break;
6421     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6422       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6423       break;
6424     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6425       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6426       break;
6427     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6428       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6429       break;
6430     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6431       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6432       break;
6433     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6434       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6435       break;
6436     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6437       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6438       break;
6439     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6440       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6441       break;
6442     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6443       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6444       break;
6445     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6446       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6447       break;
6448     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6449       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6450       break;
6451     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6452       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6453       break;
6454     default:
6455       llvm_unreachable("unhandled atomic opcode");
6456     }
6457 
6458     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6459                                    M->getMemOperand());
6460   }
6461   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6462   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6463   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6464   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6465   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6466   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6467   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6468   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6469   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6470   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6471   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6472   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6473     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6474     SDValue Ops[] = {
6475       Op.getOperand(0), // Chain
6476       Op.getOperand(2), // vdata
6477       Op.getOperand(3), // rsrc
6478       Op.getOperand(4), // vindex
6479       Offsets.first,    // voffset
6480       Op.getOperand(6), // soffset
6481       Offsets.second,   // offset
6482       Op.getOperand(7), // cachepolicy
6483       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6484     };
6485     EVT VT = Op.getValueType();
6486 
6487     auto *M = cast<MemSDNode>(Op);
6488     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6489                                                         Ops[3]));
6490     unsigned Opcode = 0;
6491 
6492     switch (IntrID) {
6493     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6494       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6495       break;
6496     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6497       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6498       break;
6499     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6500       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6501       break;
6502     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6503       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6504       break;
6505     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6506       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6507       break;
6508     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6509       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6510       break;
6511     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6512       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6513       break;
6514     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6515       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6516       break;
6517     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6518       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6519       break;
6520     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6521       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6522       break;
6523     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6524       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6525       break;
6526     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6527       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6528       break;
6529     default:
6530       llvm_unreachable("unhandled atomic opcode");
6531     }
6532 
6533     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6534                                    M->getMemOperand());
6535   }
6536   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6537     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6538     unsigned IdxEn = 1;
6539     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6540       IdxEn = Idx->getZExtValue() != 0;
6541     SDValue Ops[] = {
6542       Op.getOperand(0), // Chain
6543       Op.getOperand(2), // src
6544       Op.getOperand(3), // cmp
6545       Op.getOperand(4), // rsrc
6546       Op.getOperand(5), // vindex
6547       SDValue(),        // voffset -- will be set by setBufferOffsets
6548       SDValue(),        // soffset -- will be set by setBufferOffsets
6549       SDValue(),        // offset -- will be set by setBufferOffsets
6550       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6551       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6552     };
6553     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6554     // We don't know the offset if vindex is non-zero, so clear it.
6555     if (IdxEn)
6556       Offset = 0;
6557     EVT VT = Op.getValueType();
6558     auto *M = cast<MemSDNode>(Op);
6559     M->getMemOperand()->setOffset(Offset);
6560 
6561     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6562                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6563   }
6564   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6565     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6566     SDValue Ops[] = {
6567       Op.getOperand(0), // Chain
6568       Op.getOperand(2), // src
6569       Op.getOperand(3), // cmp
6570       Op.getOperand(4), // rsrc
6571       DAG.getConstant(0, DL, MVT::i32), // vindex
6572       Offsets.first,    // voffset
6573       Op.getOperand(6), // soffset
6574       Offsets.second,   // offset
6575       Op.getOperand(7), // cachepolicy
6576       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6577     };
6578     EVT VT = Op.getValueType();
6579     auto *M = cast<MemSDNode>(Op);
6580     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6581 
6582     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6583                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6584   }
6585   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6586     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6587     SDValue Ops[] = {
6588       Op.getOperand(0), // Chain
6589       Op.getOperand(2), // src
6590       Op.getOperand(3), // cmp
6591       Op.getOperand(4), // rsrc
6592       Op.getOperand(5), // vindex
6593       Offsets.first,    // voffset
6594       Op.getOperand(7), // soffset
6595       Offsets.second,   // offset
6596       Op.getOperand(8), // cachepolicy
6597       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6598     };
6599     EVT VT = Op.getValueType();
6600     auto *M = cast<MemSDNode>(Op);
6601     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6602                                                         Ops[4]));
6603 
6604     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6605                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6606   }
6607 
6608   default:
6609     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6610             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6611       return lowerImage(Op, ImageDimIntr, DAG);
6612 
6613     return SDValue();
6614   }
6615 }
6616 
6617 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6618 // dwordx4 if on SI.
6619 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6620                                               SDVTList VTList,
6621                                               ArrayRef<SDValue> Ops, EVT MemVT,
6622                                               MachineMemOperand *MMO,
6623                                               SelectionDAG &DAG) const {
6624   EVT VT = VTList.VTs[0];
6625   EVT WidenedVT = VT;
6626   EVT WidenedMemVT = MemVT;
6627   if (!Subtarget->hasDwordx3LoadStores() &&
6628       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6629     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6630                                  WidenedVT.getVectorElementType(), 4);
6631     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6632                                     WidenedMemVT.getVectorElementType(), 4);
6633     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6634   }
6635 
6636   assert(VTList.NumVTs == 2);
6637   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6638 
6639   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6640                                        WidenedMemVT, MMO);
6641   if (WidenedVT != VT) {
6642     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6643                                DAG.getVectorIdxConstant(0, DL));
6644     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6645   }
6646   return NewOp;
6647 }
6648 
6649 SDValue SITargetLowering::handleD16VData(SDValue VData,
6650                                          SelectionDAG &DAG) const {
6651   EVT StoreVT = VData.getValueType();
6652 
6653   // No change for f16 and legal vector D16 types.
6654   if (!StoreVT.isVector())
6655     return VData;
6656 
6657   SDLoc DL(VData);
6658   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6659 
6660   if (Subtarget->hasUnpackedD16VMem()) {
6661     // We need to unpack the packed data to store.
6662     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6663     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6664 
6665     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6666                                         StoreVT.getVectorNumElements());
6667     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6668     return DAG.UnrollVectorOp(ZExt.getNode());
6669   }
6670 
6671   assert(isTypeLegal(StoreVT));
6672   return VData;
6673 }
6674 
6675 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6676                                               SelectionDAG &DAG) const {
6677   SDLoc DL(Op);
6678   SDValue Chain = Op.getOperand(0);
6679   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6680   MachineFunction &MF = DAG.getMachineFunction();
6681 
6682   switch (IntrinsicID) {
6683   case Intrinsic::amdgcn_exp_compr: {
6684     SDValue Src0 = Op.getOperand(4);
6685     SDValue Src1 = Op.getOperand(5);
6686     // Hack around illegal type on SI by directly selecting it.
6687     if (isTypeLegal(Src0.getValueType()))
6688       return SDValue();
6689 
6690     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6691     SDValue Undef = DAG.getUNDEF(MVT::f32);
6692     const SDValue Ops[] = {
6693       Op.getOperand(2), // tgt
6694       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
6695       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
6696       Undef, // src2
6697       Undef, // src3
6698       Op.getOperand(7), // vm
6699       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6700       Op.getOperand(3), // en
6701       Op.getOperand(0) // Chain
6702     };
6703 
6704     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
6705     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
6706   }
6707   case Intrinsic::amdgcn_s_barrier: {
6708     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6709       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6710       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6711       if (WGSize <= ST.getWavefrontSize())
6712         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6713                                           Op.getOperand(0)), 0);
6714     }
6715     return SDValue();
6716   };
6717   case Intrinsic::amdgcn_tbuffer_store: {
6718     SDValue VData = Op.getOperand(2);
6719     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6720     if (IsD16)
6721       VData = handleD16VData(VData, DAG);
6722     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6723     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6724     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6725     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6726     unsigned IdxEn = 1;
6727     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6728       IdxEn = Idx->getZExtValue() != 0;
6729     SDValue Ops[] = {
6730       Chain,
6731       VData,             // vdata
6732       Op.getOperand(3),  // rsrc
6733       Op.getOperand(4),  // vindex
6734       Op.getOperand(5),  // voffset
6735       Op.getOperand(6),  // soffset
6736       Op.getOperand(7),  // offset
6737       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6738       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6739       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
6740     };
6741     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6742                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6743     MemSDNode *M = cast<MemSDNode>(Op);
6744     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6745                                    M->getMemoryVT(), M->getMemOperand());
6746   }
6747 
6748   case Intrinsic::amdgcn_struct_tbuffer_store: {
6749     SDValue VData = Op.getOperand(2);
6750     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6751     if (IsD16)
6752       VData = handleD16VData(VData, DAG);
6753     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6754     SDValue Ops[] = {
6755       Chain,
6756       VData,             // vdata
6757       Op.getOperand(3),  // rsrc
6758       Op.getOperand(4),  // vindex
6759       Offsets.first,     // voffset
6760       Op.getOperand(6),  // soffset
6761       Offsets.second,    // offset
6762       Op.getOperand(7),  // format
6763       Op.getOperand(8),  // cachepolicy, swizzled buffer
6764       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
6765     };
6766     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6767                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6768     MemSDNode *M = cast<MemSDNode>(Op);
6769     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6770                                    M->getMemoryVT(), M->getMemOperand());
6771   }
6772 
6773   case Intrinsic::amdgcn_raw_tbuffer_store: {
6774     SDValue VData = Op.getOperand(2);
6775     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6776     if (IsD16)
6777       VData = handleD16VData(VData, DAG);
6778     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6779     SDValue Ops[] = {
6780       Chain,
6781       VData,             // vdata
6782       Op.getOperand(3),  // rsrc
6783       DAG.getConstant(0, DL, MVT::i32), // vindex
6784       Offsets.first,     // voffset
6785       Op.getOperand(5),  // soffset
6786       Offsets.second,    // offset
6787       Op.getOperand(6),  // format
6788       Op.getOperand(7),  // cachepolicy, swizzled buffer
6789       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
6790     };
6791     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6792                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6793     MemSDNode *M = cast<MemSDNode>(Op);
6794     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6795                                    M->getMemoryVT(), M->getMemOperand());
6796   }
6797 
6798   case Intrinsic::amdgcn_buffer_store:
6799   case Intrinsic::amdgcn_buffer_store_format: {
6800     SDValue VData = Op.getOperand(2);
6801     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6802     if (IsD16)
6803       VData = handleD16VData(VData, DAG);
6804     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6805     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6806     unsigned IdxEn = 1;
6807     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6808       IdxEn = Idx->getZExtValue() != 0;
6809     SDValue Ops[] = {
6810       Chain,
6811       VData,
6812       Op.getOperand(3), // rsrc
6813       Op.getOperand(4), // vindex
6814       SDValue(), // voffset -- will be set by setBufferOffsets
6815       SDValue(), // soffset -- will be set by setBufferOffsets
6816       SDValue(), // offset -- will be set by setBufferOffsets
6817       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6818       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6819     };
6820     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6821     // We don't know the offset if vindex is non-zero, so clear it.
6822     if (IdxEn)
6823       Offset = 0;
6824     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6825                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6826     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6827     MemSDNode *M = cast<MemSDNode>(Op);
6828     M->getMemOperand()->setOffset(Offset);
6829 
6830     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6831     EVT VDataType = VData.getValueType().getScalarType();
6832     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6833       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6834 
6835     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6836                                    M->getMemoryVT(), M->getMemOperand());
6837   }
6838 
6839   case Intrinsic::amdgcn_raw_buffer_store:
6840   case Intrinsic::amdgcn_raw_buffer_store_format: {
6841     const bool IsFormat =
6842         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
6843 
6844     SDValue VData = Op.getOperand(2);
6845     EVT VDataVT = VData.getValueType();
6846     EVT EltType = VDataVT.getScalarType();
6847     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6848     if (IsD16)
6849       VData = handleD16VData(VData, DAG);
6850 
6851     if (!isTypeLegal(VDataVT)) {
6852       VData =
6853           DAG.getNode(ISD::BITCAST, DL,
6854                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6855     }
6856 
6857     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6858     SDValue Ops[] = {
6859       Chain,
6860       VData,
6861       Op.getOperand(3), // rsrc
6862       DAG.getConstant(0, DL, MVT::i32), // vindex
6863       Offsets.first,    // voffset
6864       Op.getOperand(5), // soffset
6865       Offsets.second,   // offset
6866       Op.getOperand(6), // cachepolicy, swizzled buffer
6867       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6868     };
6869     unsigned Opc =
6870         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
6871     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6872     MemSDNode *M = cast<MemSDNode>(Op);
6873     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6874 
6875     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6876     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6877       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
6878 
6879     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6880                                    M->getMemoryVT(), M->getMemOperand());
6881   }
6882 
6883   case Intrinsic::amdgcn_struct_buffer_store:
6884   case Intrinsic::amdgcn_struct_buffer_store_format: {
6885     const bool IsFormat =
6886         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
6887 
6888     SDValue VData = Op.getOperand(2);
6889     EVT VDataVT = VData.getValueType();
6890     EVT EltType = VDataVT.getScalarType();
6891     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6892 
6893     if (IsD16)
6894       VData = handleD16VData(VData, DAG);
6895 
6896     if (!isTypeLegal(VDataVT)) {
6897       VData =
6898           DAG.getNode(ISD::BITCAST, DL,
6899                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6900     }
6901 
6902     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6903     SDValue Ops[] = {
6904       Chain,
6905       VData,
6906       Op.getOperand(3), // rsrc
6907       Op.getOperand(4), // vindex
6908       Offsets.first,    // voffset
6909       Op.getOperand(6), // soffset
6910       Offsets.second,   // offset
6911       Op.getOperand(7), // cachepolicy, swizzled buffer
6912       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6913     };
6914     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6915                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6916     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6917     MemSDNode *M = cast<MemSDNode>(Op);
6918     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6919                                                         Ops[3]));
6920 
6921     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6922     EVT VDataType = VData.getValueType().getScalarType();
6923     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6924       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6925 
6926     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6927                                    M->getMemoryVT(), M->getMemOperand());
6928   }
6929 
6930   case Intrinsic::amdgcn_buffer_atomic_fadd: {
6931     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6932     unsigned IdxEn = 1;
6933     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6934       IdxEn = Idx->getZExtValue() != 0;
6935     SDValue Ops[] = {
6936       Chain,
6937       Op.getOperand(2), // vdata
6938       Op.getOperand(3), // rsrc
6939       Op.getOperand(4), // vindex
6940       SDValue(),        // voffset -- will be set by setBufferOffsets
6941       SDValue(),        // soffset -- will be set by setBufferOffsets
6942       SDValue(),        // offset -- will be set by setBufferOffsets
6943       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6944       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6945     };
6946     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6947     // We don't know the offset if vindex is non-zero, so clear it.
6948     if (IdxEn)
6949       Offset = 0;
6950     EVT VT = Op.getOperand(2).getValueType();
6951 
6952     auto *M = cast<MemSDNode>(Op);
6953     M->getMemOperand()->setOffset(Offset);
6954     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
6955                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
6956 
6957     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6958                                    M->getMemOperand());
6959   }
6960 
6961   case Intrinsic::amdgcn_global_atomic_fadd: {
6962     SDValue Ops[] = {
6963       Chain,
6964       Op.getOperand(2), // ptr
6965       Op.getOperand(3)  // vdata
6966     };
6967     EVT VT = Op.getOperand(3).getValueType();
6968 
6969     auto *M = cast<MemSDNode>(Op);
6970     if (VT.isVector()) {
6971       return DAG.getMemIntrinsicNode(
6972         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
6973         M->getMemOperand());
6974     }
6975 
6976     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
6977                          DAG.getVTList(VT, MVT::Other), Ops,
6978                          M->getMemOperand()).getValue(1);
6979   }
6980   case Intrinsic::amdgcn_end_cf:
6981     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
6982                                       Op->getOperand(2), Chain), 0);
6983 
6984   default: {
6985     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6986             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6987       return lowerImage(Op, ImageDimIntr, DAG);
6988 
6989     return Op;
6990   }
6991   }
6992 }
6993 
6994 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
6995 // offset (the offset that is included in bounds checking and swizzling, to be
6996 // split between the instruction's voffset and immoffset fields) and soffset
6997 // (the offset that is excluded from bounds checking and swizzling, to go in
6998 // the instruction's soffset field).  This function takes the first kind of
6999 // offset and figures out how to split it between voffset and immoffset.
7000 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7001     SDValue Offset, SelectionDAG &DAG) const {
7002   SDLoc DL(Offset);
7003   const unsigned MaxImm = 4095;
7004   SDValue N0 = Offset;
7005   ConstantSDNode *C1 = nullptr;
7006 
7007   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7008     N0 = SDValue();
7009   else if (DAG.isBaseWithConstantOffset(N0)) {
7010     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7011     N0 = N0.getOperand(0);
7012   }
7013 
7014   if (C1) {
7015     unsigned ImmOffset = C1->getZExtValue();
7016     // If the immediate value is too big for the immoffset field, put the value
7017     // and -4096 into the immoffset field so that the value that is copied/added
7018     // for the voffset field is a multiple of 4096, and it stands more chance
7019     // of being CSEd with the copy/add for another similar load/store.
7020     // However, do not do that rounding down to a multiple of 4096 if that is a
7021     // negative number, as it appears to be illegal to have a negative offset
7022     // in the vgpr, even if adding the immediate offset makes it positive.
7023     unsigned Overflow = ImmOffset & ~MaxImm;
7024     ImmOffset -= Overflow;
7025     if ((int32_t)Overflow < 0) {
7026       Overflow += ImmOffset;
7027       ImmOffset = 0;
7028     }
7029     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7030     if (Overflow) {
7031       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7032       if (!N0)
7033         N0 = OverflowVal;
7034       else {
7035         SDValue Ops[] = { N0, OverflowVal };
7036         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7037       }
7038     }
7039   }
7040   if (!N0)
7041     N0 = DAG.getConstant(0, DL, MVT::i32);
7042   if (!C1)
7043     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7044   return {N0, SDValue(C1, 0)};
7045 }
7046 
7047 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7048 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7049 // pointed to by Offsets.
7050 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7051                                         SelectionDAG &DAG, SDValue *Offsets,
7052                                         unsigned Align) const {
7053   SDLoc DL(CombinedOffset);
7054   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7055     uint32_t Imm = C->getZExtValue();
7056     uint32_t SOffset, ImmOffset;
7057     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7058       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7059       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7060       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7061       return SOffset + ImmOffset;
7062     }
7063   }
7064   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7065     SDValue N0 = CombinedOffset.getOperand(0);
7066     SDValue N1 = CombinedOffset.getOperand(1);
7067     uint32_t SOffset, ImmOffset;
7068     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7069     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7070                                                 Subtarget, Align)) {
7071       Offsets[0] = N0;
7072       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7073       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7074       return 0;
7075     }
7076   }
7077   Offsets[0] = CombinedOffset;
7078   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7079   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7080   return 0;
7081 }
7082 
7083 // Handle 8 bit and 16 bit buffer loads
7084 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7085                                                      EVT LoadVT, SDLoc DL,
7086                                                      ArrayRef<SDValue> Ops,
7087                                                      MemSDNode *M) const {
7088   EVT IntVT = LoadVT.changeTypeToInteger();
7089   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7090          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7091 
7092   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7093   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7094                                                Ops, IntVT,
7095                                                M->getMemOperand());
7096   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7097   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7098 
7099   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7100 }
7101 
7102 // Handle 8 bit and 16 bit buffer stores
7103 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7104                                                       EVT VDataType, SDLoc DL,
7105                                                       SDValue Ops[],
7106                                                       MemSDNode *M) const {
7107   if (VDataType == MVT::f16)
7108     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7109 
7110   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7111   Ops[1] = BufferStoreExt;
7112   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7113                                  AMDGPUISD::BUFFER_STORE_SHORT;
7114   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7115   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7116                                      M->getMemOperand());
7117 }
7118 
7119 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7120                                  ISD::LoadExtType ExtType, SDValue Op,
7121                                  const SDLoc &SL, EVT VT) {
7122   if (VT.bitsLT(Op.getValueType()))
7123     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7124 
7125   switch (ExtType) {
7126   case ISD::SEXTLOAD:
7127     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7128   case ISD::ZEXTLOAD:
7129     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7130   case ISD::EXTLOAD:
7131     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7132   case ISD::NON_EXTLOAD:
7133     return Op;
7134   }
7135 
7136   llvm_unreachable("invalid ext type");
7137 }
7138 
7139 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7140   SelectionDAG &DAG = DCI.DAG;
7141   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7142     return SDValue();
7143 
7144   // FIXME: Constant loads should all be marked invariant.
7145   unsigned AS = Ld->getAddressSpace();
7146   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7147       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7148       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7149     return SDValue();
7150 
7151   // Don't do this early, since it may interfere with adjacent load merging for
7152   // illegal types. We can avoid losing alignment information for exotic types
7153   // pre-legalize.
7154   EVT MemVT = Ld->getMemoryVT();
7155   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7156       MemVT.getSizeInBits() >= 32)
7157     return SDValue();
7158 
7159   SDLoc SL(Ld);
7160 
7161   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7162          "unexpected vector extload");
7163 
7164   // TODO: Drop only high part of range.
7165   SDValue Ptr = Ld->getBasePtr();
7166   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7167                                 MVT::i32, SL, Ld->getChain(), Ptr,
7168                                 Ld->getOffset(),
7169                                 Ld->getPointerInfo(), MVT::i32,
7170                                 Ld->getAlignment(),
7171                                 Ld->getMemOperand()->getFlags(),
7172                                 Ld->getAAInfo(),
7173                                 nullptr); // Drop ranges
7174 
7175   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7176   if (MemVT.isFloatingPoint()) {
7177     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7178            "unexpected fp extload");
7179     TruncVT = MemVT.changeTypeToInteger();
7180   }
7181 
7182   SDValue Cvt = NewLoad;
7183   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7184     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7185                       DAG.getValueType(TruncVT));
7186   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7187              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7188     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7189   } else {
7190     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7191   }
7192 
7193   EVT VT = Ld->getValueType(0);
7194   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7195 
7196   DCI.AddToWorklist(Cvt.getNode());
7197 
7198   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7199   // the appropriate extension from the 32-bit load.
7200   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7201   DCI.AddToWorklist(Cvt.getNode());
7202 
7203   // Handle conversion back to floating point if necessary.
7204   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7205 
7206   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7207 }
7208 
7209 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7210   SDLoc DL(Op);
7211   LoadSDNode *Load = cast<LoadSDNode>(Op);
7212   ISD::LoadExtType ExtType = Load->getExtensionType();
7213   EVT MemVT = Load->getMemoryVT();
7214 
7215   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7216     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7217       return SDValue();
7218 
7219     // FIXME: Copied from PPC
7220     // First, load into 32 bits, then truncate to 1 bit.
7221 
7222     SDValue Chain = Load->getChain();
7223     SDValue BasePtr = Load->getBasePtr();
7224     MachineMemOperand *MMO = Load->getMemOperand();
7225 
7226     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7227 
7228     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7229                                    BasePtr, RealMemVT, MMO);
7230 
7231     if (!MemVT.isVector()) {
7232       SDValue Ops[] = {
7233         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7234         NewLD.getValue(1)
7235       };
7236 
7237       return DAG.getMergeValues(Ops, DL);
7238     }
7239 
7240     SmallVector<SDValue, 3> Elts;
7241     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7242       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7243                                 DAG.getConstant(I, DL, MVT::i32));
7244 
7245       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7246     }
7247 
7248     SDValue Ops[] = {
7249       DAG.getBuildVector(MemVT, DL, Elts),
7250       NewLD.getValue(1)
7251     };
7252 
7253     return DAG.getMergeValues(Ops, DL);
7254   }
7255 
7256   if (!MemVT.isVector())
7257     return SDValue();
7258 
7259   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7260          "Custom lowering for non-i32 vectors hasn't been implemented.");
7261 
7262   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7263                                       MemVT, *Load->getMemOperand())) {
7264     SDValue Ops[2];
7265     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7266     return DAG.getMergeValues(Ops, DL);
7267   }
7268 
7269   unsigned Alignment = Load->getAlignment();
7270   unsigned AS = Load->getAddressSpace();
7271   if (Subtarget->hasLDSMisalignedBug() &&
7272       AS == AMDGPUAS::FLAT_ADDRESS &&
7273       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7274     return SplitVectorLoad(Op, DAG);
7275   }
7276 
7277   MachineFunction &MF = DAG.getMachineFunction();
7278   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7279   // If there is a possibilty that flat instruction access scratch memory
7280   // then we need to use the same legalization rules we use for private.
7281   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7282       !Subtarget->hasMultiDwordFlatScratchAddressing())
7283     AS = MFI->hasFlatScratchInit() ?
7284          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7285 
7286   unsigned NumElements = MemVT.getVectorNumElements();
7287 
7288   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7289       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7290     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7291       if (MemVT.isPow2VectorType())
7292         return SDValue();
7293       if (NumElements == 3)
7294         return WidenVectorLoad(Op, DAG);
7295       return SplitVectorLoad(Op, DAG);
7296     }
7297     // Non-uniform loads will be selected to MUBUF instructions, so they
7298     // have the same legalization requirements as global and private
7299     // loads.
7300     //
7301   }
7302 
7303   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7304       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7305       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7306     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7307         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7308         Alignment >= 4 && NumElements < 32) {
7309       if (MemVT.isPow2VectorType())
7310         return SDValue();
7311       if (NumElements == 3)
7312         return WidenVectorLoad(Op, DAG);
7313       return SplitVectorLoad(Op, DAG);
7314     }
7315     // Non-uniform loads will be selected to MUBUF instructions, so they
7316     // have the same legalization requirements as global and private
7317     // loads.
7318     //
7319   }
7320   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7321       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7322       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7323       AS == AMDGPUAS::FLAT_ADDRESS) {
7324     if (NumElements > 4)
7325       return SplitVectorLoad(Op, DAG);
7326     // v3 loads not supported on SI.
7327     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7328       return WidenVectorLoad(Op, DAG);
7329     // v3 and v4 loads are supported for private and global memory.
7330     return SDValue();
7331   }
7332   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7333     // Depending on the setting of the private_element_size field in the
7334     // resource descriptor, we can only make private accesses up to a certain
7335     // size.
7336     switch (Subtarget->getMaxPrivateElementSize()) {
7337     case 4: {
7338       SDValue Ops[2];
7339       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7340       return DAG.getMergeValues(Ops, DL);
7341     }
7342     case 8:
7343       if (NumElements > 2)
7344         return SplitVectorLoad(Op, DAG);
7345       return SDValue();
7346     case 16:
7347       // Same as global/flat
7348       if (NumElements > 4)
7349         return SplitVectorLoad(Op, DAG);
7350       // v3 loads not supported on SI.
7351       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7352         return WidenVectorLoad(Op, DAG);
7353       return SDValue();
7354     default:
7355       llvm_unreachable("unsupported private_element_size");
7356     }
7357   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7358     // Use ds_read_b128 if possible.
7359     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7360         MemVT.getStoreSize() == 16)
7361       return SDValue();
7362 
7363     if (NumElements > 2)
7364       return SplitVectorLoad(Op, DAG);
7365 
7366     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7367     // address is negative, then the instruction is incorrectly treated as
7368     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7369     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7370     // load later in the SILoadStoreOptimizer.
7371     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7372         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7373         Load->getAlignment() < 8) {
7374       return SplitVectorLoad(Op, DAG);
7375     }
7376   }
7377   return SDValue();
7378 }
7379 
7380 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7381   EVT VT = Op.getValueType();
7382   assert(VT.getSizeInBits() == 64);
7383 
7384   SDLoc DL(Op);
7385   SDValue Cond = Op.getOperand(0);
7386 
7387   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7388   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7389 
7390   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7391   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7392 
7393   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7394   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7395 
7396   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7397 
7398   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7399   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7400 
7401   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7402 
7403   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7404   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7405 }
7406 
7407 // Catch division cases where we can use shortcuts with rcp and rsq
7408 // instructions.
7409 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7410                                               SelectionDAG &DAG) const {
7411   SDLoc SL(Op);
7412   SDValue LHS = Op.getOperand(0);
7413   SDValue RHS = Op.getOperand(1);
7414   EVT VT = Op.getValueType();
7415   const SDNodeFlags Flags = Op->getFlags();
7416 
7417   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7418                             Flags.hasApproximateFuncs();
7419 
7420   // Without !fpmath accuracy information, we can't do more because we don't
7421   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7422   if (!AllowInaccurateRcp)
7423     return SDValue();
7424 
7425   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7426     if (CLHS->isExactlyValue(1.0)) {
7427       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7428       // the CI documentation has a worst case error of 1 ulp.
7429       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7430       // use it as long as we aren't trying to use denormals.
7431       //
7432       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7433 
7434       // 1.0 / sqrt(x) -> rsq(x)
7435 
7436       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7437       // error seems really high at 2^29 ULP.
7438       if (RHS.getOpcode() == ISD::FSQRT)
7439         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7440 
7441       // 1.0 / x -> rcp(x)
7442       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7443     }
7444 
7445     // Same as for 1.0, but expand the sign out of the constant.
7446     if (CLHS->isExactlyValue(-1.0)) {
7447       // -1.0 / x -> rcp (fneg x)
7448       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7449       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7450     }
7451   }
7452 
7453   // Turn into multiply by the reciprocal.
7454   // x / y -> x * (1.0 / y)
7455   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7456   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7457 }
7458 
7459 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7460                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7461   if (GlueChain->getNumValues() <= 1) {
7462     return DAG.getNode(Opcode, SL, VT, A, B);
7463   }
7464 
7465   assert(GlueChain->getNumValues() == 3);
7466 
7467   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7468   switch (Opcode) {
7469   default: llvm_unreachable("no chain equivalent for opcode");
7470   case ISD::FMUL:
7471     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7472     break;
7473   }
7474 
7475   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7476                      GlueChain.getValue(2));
7477 }
7478 
7479 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7480                            EVT VT, SDValue A, SDValue B, SDValue C,
7481                            SDValue GlueChain) {
7482   if (GlueChain->getNumValues() <= 1) {
7483     return DAG.getNode(Opcode, SL, VT, A, B, C);
7484   }
7485 
7486   assert(GlueChain->getNumValues() == 3);
7487 
7488   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7489   switch (Opcode) {
7490   default: llvm_unreachable("no chain equivalent for opcode");
7491   case ISD::FMA:
7492     Opcode = AMDGPUISD::FMA_W_CHAIN;
7493     break;
7494   }
7495 
7496   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7497                      GlueChain.getValue(2));
7498 }
7499 
7500 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7501   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7502     return FastLowered;
7503 
7504   SDLoc SL(Op);
7505   SDValue Src0 = Op.getOperand(0);
7506   SDValue Src1 = Op.getOperand(1);
7507 
7508   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7509   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7510 
7511   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7512   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7513 
7514   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7515   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7516 
7517   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7518 }
7519 
7520 // Faster 2.5 ULP division that does not support denormals.
7521 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7522   SDLoc SL(Op);
7523   SDValue LHS = Op.getOperand(1);
7524   SDValue RHS = Op.getOperand(2);
7525 
7526   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7527 
7528   const APFloat K0Val(BitsToFloat(0x6f800000));
7529   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7530 
7531   const APFloat K1Val(BitsToFloat(0x2f800000));
7532   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7533 
7534   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7535 
7536   EVT SetCCVT =
7537     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7538 
7539   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7540 
7541   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7542 
7543   // TODO: Should this propagate fast-math-flags?
7544   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7545 
7546   // rcp does not support denormals.
7547   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7548 
7549   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7550 
7551   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7552 }
7553 
7554 // Returns immediate value for setting the F32 denorm mode when using the
7555 // S_DENORM_MODE instruction.
7556 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7557                                           const SDLoc &SL, const GCNSubtarget *ST) {
7558   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7559   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7560                                 ? FP_DENORM_FLUSH_NONE
7561                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7562 
7563   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7564   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7565 }
7566 
7567 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7568   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7569     return FastLowered;
7570 
7571   SDLoc SL(Op);
7572   SDValue LHS = Op.getOperand(0);
7573   SDValue RHS = Op.getOperand(1);
7574 
7575   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7576 
7577   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7578 
7579   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7580                                           RHS, RHS, LHS);
7581   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7582                                         LHS, RHS, LHS);
7583 
7584   // Denominator is scaled to not be denormal, so using rcp is ok.
7585   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7586                                   DenominatorScaled);
7587   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7588                                      DenominatorScaled);
7589 
7590   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7591                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7592                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7593   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7594 
7595   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7596 
7597   if (!HasFP32Denormals) {
7598     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7599 
7600     SDValue EnableDenorm;
7601     if (Subtarget->hasDenormModeInst()) {
7602       const SDValue EnableDenormValue =
7603           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7604 
7605       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7606                                  DAG.getEntryNode(), EnableDenormValue);
7607     } else {
7608       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7609                                                         SL, MVT::i32);
7610       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7611                                  DAG.getEntryNode(), EnableDenormValue,
7612                                  BitField);
7613     }
7614 
7615     SDValue Ops[3] = {
7616       NegDivScale0,
7617       EnableDenorm.getValue(0),
7618       EnableDenorm.getValue(1)
7619     };
7620 
7621     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7622   }
7623 
7624   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7625                              ApproxRcp, One, NegDivScale0);
7626 
7627   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7628                              ApproxRcp, Fma0);
7629 
7630   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7631                            Fma1, Fma1);
7632 
7633   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7634                              NumeratorScaled, Mul);
7635 
7636   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7637 
7638   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7639                              NumeratorScaled, Fma3);
7640 
7641   if (!HasFP32Denormals) {
7642     SDValue DisableDenorm;
7643     if (Subtarget->hasDenormModeInst()) {
7644       const SDValue DisableDenormValue =
7645           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7646 
7647       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7648                                   Fma4.getValue(1), DisableDenormValue,
7649                                   Fma4.getValue(2));
7650     } else {
7651       const SDValue DisableDenormValue =
7652           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7653 
7654       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7655                                   Fma4.getValue(1), DisableDenormValue,
7656                                   BitField, Fma4.getValue(2));
7657     }
7658 
7659     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7660                                       DisableDenorm, DAG.getRoot());
7661     DAG.setRoot(OutputChain);
7662   }
7663 
7664   SDValue Scale = NumeratorScaled.getValue(1);
7665   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7666                              Fma4, Fma1, Fma3, Scale);
7667 
7668   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7669 }
7670 
7671 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7672   if (DAG.getTarget().Options.UnsafeFPMath)
7673     return lowerFastUnsafeFDIV(Op, DAG);
7674 
7675   SDLoc SL(Op);
7676   SDValue X = Op.getOperand(0);
7677   SDValue Y = Op.getOperand(1);
7678 
7679   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7680 
7681   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7682 
7683   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7684 
7685   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7686 
7687   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7688 
7689   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7690 
7691   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7692 
7693   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7694 
7695   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7696 
7697   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7698   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7699 
7700   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7701                              NegDivScale0, Mul, DivScale1);
7702 
7703   SDValue Scale;
7704 
7705   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7706     // Workaround a hardware bug on SI where the condition output from div_scale
7707     // is not usable.
7708 
7709     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7710 
7711     // Figure out if the scale to use for div_fmas.
7712     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7713     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7714     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7715     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7716 
7717     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7718     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7719 
7720     SDValue Scale0Hi
7721       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7722     SDValue Scale1Hi
7723       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7724 
7725     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7726     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7727     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7728   } else {
7729     Scale = DivScale1.getValue(1);
7730   }
7731 
7732   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7733                              Fma4, Fma3, Mul, Scale);
7734 
7735   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7736 }
7737 
7738 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7739   EVT VT = Op.getValueType();
7740 
7741   if (VT == MVT::f32)
7742     return LowerFDIV32(Op, DAG);
7743 
7744   if (VT == MVT::f64)
7745     return LowerFDIV64(Op, DAG);
7746 
7747   if (VT == MVT::f16)
7748     return LowerFDIV16(Op, DAG);
7749 
7750   llvm_unreachable("Unexpected type for fdiv");
7751 }
7752 
7753 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7754   SDLoc DL(Op);
7755   StoreSDNode *Store = cast<StoreSDNode>(Op);
7756   EVT VT = Store->getMemoryVT();
7757 
7758   if (VT == MVT::i1) {
7759     return DAG.getTruncStore(Store->getChain(), DL,
7760        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7761        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7762   }
7763 
7764   assert(VT.isVector() &&
7765          Store->getValue().getValueType().getScalarType() == MVT::i32);
7766 
7767   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7768                                       VT, *Store->getMemOperand())) {
7769     return expandUnalignedStore(Store, DAG);
7770   }
7771 
7772   unsigned AS = Store->getAddressSpace();
7773   if (Subtarget->hasLDSMisalignedBug() &&
7774       AS == AMDGPUAS::FLAT_ADDRESS &&
7775       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7776     return SplitVectorStore(Op, DAG);
7777   }
7778 
7779   MachineFunction &MF = DAG.getMachineFunction();
7780   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7781   // If there is a possibilty that flat instruction access scratch memory
7782   // then we need to use the same legalization rules we use for private.
7783   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7784       !Subtarget->hasMultiDwordFlatScratchAddressing())
7785     AS = MFI->hasFlatScratchInit() ?
7786          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7787 
7788   unsigned NumElements = VT.getVectorNumElements();
7789   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7790       AS == AMDGPUAS::FLAT_ADDRESS) {
7791     if (NumElements > 4)
7792       return SplitVectorStore(Op, DAG);
7793     // v3 stores not supported on SI.
7794     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7795       return SplitVectorStore(Op, DAG);
7796     return SDValue();
7797   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7798     switch (Subtarget->getMaxPrivateElementSize()) {
7799     case 4:
7800       return scalarizeVectorStore(Store, DAG);
7801     case 8:
7802       if (NumElements > 2)
7803         return SplitVectorStore(Op, DAG);
7804       return SDValue();
7805     case 16:
7806       if (NumElements > 4 || NumElements == 3)
7807         return SplitVectorStore(Op, DAG);
7808       return SDValue();
7809     default:
7810       llvm_unreachable("unsupported private_element_size");
7811     }
7812   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7813     // Use ds_write_b128 if possible.
7814     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7815         VT.getStoreSize() == 16 && NumElements != 3)
7816       return SDValue();
7817 
7818     if (NumElements > 2)
7819       return SplitVectorStore(Op, DAG);
7820 
7821     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7822     // address is negative, then the instruction is incorrectly treated as
7823     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7824     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7825     // store later in the SILoadStoreOptimizer.
7826     if (!Subtarget->hasUsableDSOffset() &&
7827         NumElements == 2 && VT.getStoreSize() == 8 &&
7828         Store->getAlignment() < 8) {
7829       return SplitVectorStore(Op, DAG);
7830     }
7831 
7832     return SDValue();
7833   } else {
7834     llvm_unreachable("unhandled address space");
7835   }
7836 }
7837 
7838 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7839   SDLoc DL(Op);
7840   EVT VT = Op.getValueType();
7841   SDValue Arg = Op.getOperand(0);
7842   SDValue TrigVal;
7843 
7844   // TODO: Should this propagate fast-math-flags?
7845 
7846   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7847 
7848   if (Subtarget->hasTrigReducedRange()) {
7849     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7850     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7851   } else {
7852     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7853   }
7854 
7855   switch (Op.getOpcode()) {
7856   case ISD::FCOS:
7857     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7858   case ISD::FSIN:
7859     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7860   default:
7861     llvm_unreachable("Wrong trig opcode");
7862   }
7863 }
7864 
7865 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7866   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7867   assert(AtomicNode->isCompareAndSwap());
7868   unsigned AS = AtomicNode->getAddressSpace();
7869 
7870   // No custom lowering required for local address space
7871   if (!isFlatGlobalAddrSpace(AS))
7872     return Op;
7873 
7874   // Non-local address space requires custom lowering for atomic compare
7875   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7876   SDLoc DL(Op);
7877   SDValue ChainIn = Op.getOperand(0);
7878   SDValue Addr = Op.getOperand(1);
7879   SDValue Old = Op.getOperand(2);
7880   SDValue New = Op.getOperand(3);
7881   EVT VT = Op.getValueType();
7882   MVT SimpleVT = VT.getSimpleVT();
7883   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7884 
7885   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
7886   SDValue Ops[] = { ChainIn, Addr, NewOld };
7887 
7888   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7889                                  Ops, VT, AtomicNode->getMemOperand());
7890 }
7891 
7892 //===----------------------------------------------------------------------===//
7893 // Custom DAG optimizations
7894 //===----------------------------------------------------------------------===//
7895 
7896 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
7897                                                      DAGCombinerInfo &DCI) const {
7898   EVT VT = N->getValueType(0);
7899   EVT ScalarVT = VT.getScalarType();
7900   if (ScalarVT != MVT::f32)
7901     return SDValue();
7902 
7903   SelectionDAG &DAG = DCI.DAG;
7904   SDLoc DL(N);
7905 
7906   SDValue Src = N->getOperand(0);
7907   EVT SrcVT = Src.getValueType();
7908 
7909   // TODO: We could try to match extracting the higher bytes, which would be
7910   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7911   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7912   // about in practice.
7913   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
7914     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7915       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7916       DCI.AddToWorklist(Cvt.getNode());
7917       return Cvt;
7918     }
7919   }
7920 
7921   return SDValue();
7922 }
7923 
7924 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7925 
7926 // This is a variant of
7927 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7928 //
7929 // The normal DAG combiner will do this, but only if the add has one use since
7930 // that would increase the number of instructions.
7931 //
7932 // This prevents us from seeing a constant offset that can be folded into a
7933 // memory instruction's addressing mode. If we know the resulting add offset of
7934 // a pointer can be folded into an addressing offset, we can replace the pointer
7935 // operand with the add of new constant offset. This eliminates one of the uses,
7936 // and may allow the remaining use to also be simplified.
7937 //
7938 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7939                                                unsigned AddrSpace,
7940                                                EVT MemVT,
7941                                                DAGCombinerInfo &DCI) const {
7942   SDValue N0 = N->getOperand(0);
7943   SDValue N1 = N->getOperand(1);
7944 
7945   // We only do this to handle cases where it's profitable when there are
7946   // multiple uses of the add, so defer to the standard combine.
7947   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
7948       N0->hasOneUse())
7949     return SDValue();
7950 
7951   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
7952   if (!CN1)
7953     return SDValue();
7954 
7955   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7956   if (!CAdd)
7957     return SDValue();
7958 
7959   // If the resulting offset is too large, we can't fold it into the addressing
7960   // mode offset.
7961   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
7962   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
7963 
7964   AddrMode AM;
7965   AM.HasBaseReg = true;
7966   AM.BaseOffs = Offset.getSExtValue();
7967   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
7968     return SDValue();
7969 
7970   SelectionDAG &DAG = DCI.DAG;
7971   SDLoc SL(N);
7972   EVT VT = N->getValueType(0);
7973 
7974   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
7975   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
7976 
7977   SDNodeFlags Flags;
7978   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
7979                           (N0.getOpcode() == ISD::OR ||
7980                            N0->getFlags().hasNoUnsignedWrap()));
7981 
7982   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
7983 }
7984 
7985 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
7986                                                   DAGCombinerInfo &DCI) const {
7987   SDValue Ptr = N->getBasePtr();
7988   SelectionDAG &DAG = DCI.DAG;
7989   SDLoc SL(N);
7990 
7991   // TODO: We could also do this for multiplies.
7992   if (Ptr.getOpcode() == ISD::SHL) {
7993     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
7994                                           N->getMemoryVT(), DCI);
7995     if (NewPtr) {
7996       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
7997 
7998       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
7999       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8000     }
8001   }
8002 
8003   return SDValue();
8004 }
8005 
8006 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8007   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8008          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8009          (Opc == ISD::XOR && Val == 0);
8010 }
8011 
8012 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8013 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8014 // integer combine opportunities since most 64-bit operations are decomposed
8015 // this way.  TODO: We won't want this for SALU especially if it is an inline
8016 // immediate.
8017 SDValue SITargetLowering::splitBinaryBitConstantOp(
8018   DAGCombinerInfo &DCI,
8019   const SDLoc &SL,
8020   unsigned Opc, SDValue LHS,
8021   const ConstantSDNode *CRHS) const {
8022   uint64_t Val = CRHS->getZExtValue();
8023   uint32_t ValLo = Lo_32(Val);
8024   uint32_t ValHi = Hi_32(Val);
8025   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8026 
8027     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8028          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8029         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8030     // If we need to materialize a 64-bit immediate, it will be split up later
8031     // anyway. Avoid creating the harder to understand 64-bit immediate
8032     // materialization.
8033     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8034   }
8035 
8036   return SDValue();
8037 }
8038 
8039 // Returns true if argument is a boolean value which is not serialized into
8040 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8041 static bool isBoolSGPR(SDValue V) {
8042   if (V.getValueType() != MVT::i1)
8043     return false;
8044   switch (V.getOpcode()) {
8045   default: break;
8046   case ISD::SETCC:
8047   case ISD::AND:
8048   case ISD::OR:
8049   case ISD::XOR:
8050   case AMDGPUISD::FP_CLASS:
8051     return true;
8052   }
8053   return false;
8054 }
8055 
8056 // If a constant has all zeroes or all ones within each byte return it.
8057 // Otherwise return 0.
8058 static uint32_t getConstantPermuteMask(uint32_t C) {
8059   // 0xff for any zero byte in the mask
8060   uint32_t ZeroByteMask = 0;
8061   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8062   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8063   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8064   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8065   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8066   if ((NonZeroByteMask & C) != NonZeroByteMask)
8067     return 0; // Partial bytes selected.
8068   return C;
8069 }
8070 
8071 // Check if a node selects whole bytes from its operand 0 starting at a byte
8072 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8073 // or -1 if not succeeded.
8074 // Note byte select encoding:
8075 // value 0-3 selects corresponding source byte;
8076 // value 0xc selects zero;
8077 // value 0xff selects 0xff.
8078 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8079   assert(V.getValueSizeInBits() == 32);
8080 
8081   if (V.getNumOperands() != 2)
8082     return ~0;
8083 
8084   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8085   if (!N1)
8086     return ~0;
8087 
8088   uint32_t C = N1->getZExtValue();
8089 
8090   switch (V.getOpcode()) {
8091   default:
8092     break;
8093   case ISD::AND:
8094     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8095       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8096     }
8097     break;
8098 
8099   case ISD::OR:
8100     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8101       return (0x03020100 & ~ConstMask) | ConstMask;
8102     }
8103     break;
8104 
8105   case ISD::SHL:
8106     if (C % 8)
8107       return ~0;
8108 
8109     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8110 
8111   case ISD::SRL:
8112     if (C % 8)
8113       return ~0;
8114 
8115     return uint32_t(0x0c0c0c0c03020100ull >> C);
8116   }
8117 
8118   return ~0;
8119 }
8120 
8121 SDValue SITargetLowering::performAndCombine(SDNode *N,
8122                                             DAGCombinerInfo &DCI) const {
8123   if (DCI.isBeforeLegalize())
8124     return SDValue();
8125 
8126   SelectionDAG &DAG = DCI.DAG;
8127   EVT VT = N->getValueType(0);
8128   SDValue LHS = N->getOperand(0);
8129   SDValue RHS = N->getOperand(1);
8130 
8131 
8132   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8133   if (VT == MVT::i64 && CRHS) {
8134     if (SDValue Split
8135         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8136       return Split;
8137   }
8138 
8139   if (CRHS && VT == MVT::i32) {
8140     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8141     // nb = number of trailing zeroes in mask
8142     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8143     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8144     uint64_t Mask = CRHS->getZExtValue();
8145     unsigned Bits = countPopulation(Mask);
8146     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8147         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8148       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8149         unsigned Shift = CShift->getZExtValue();
8150         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8151         unsigned Offset = NB + Shift;
8152         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8153           SDLoc SL(N);
8154           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8155                                     LHS->getOperand(0),
8156                                     DAG.getConstant(Offset, SL, MVT::i32),
8157                                     DAG.getConstant(Bits, SL, MVT::i32));
8158           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8159           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8160                                     DAG.getValueType(NarrowVT));
8161           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8162                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8163           return Shl;
8164         }
8165       }
8166     }
8167 
8168     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8169     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8170         isa<ConstantSDNode>(LHS.getOperand(2))) {
8171       uint32_t Sel = getConstantPermuteMask(Mask);
8172       if (!Sel)
8173         return SDValue();
8174 
8175       // Select 0xc for all zero bytes
8176       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8177       SDLoc DL(N);
8178       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8179                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8180     }
8181   }
8182 
8183   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8184   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8185   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8186     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8187     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8188 
8189     SDValue X = LHS.getOperand(0);
8190     SDValue Y = RHS.getOperand(0);
8191     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8192       return SDValue();
8193 
8194     if (LCC == ISD::SETO) {
8195       if (X != LHS.getOperand(1))
8196         return SDValue();
8197 
8198       if (RCC == ISD::SETUNE) {
8199         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8200         if (!C1 || !C1->isInfinity() || C1->isNegative())
8201           return SDValue();
8202 
8203         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8204                               SIInstrFlags::N_SUBNORMAL |
8205                               SIInstrFlags::N_ZERO |
8206                               SIInstrFlags::P_ZERO |
8207                               SIInstrFlags::P_SUBNORMAL |
8208                               SIInstrFlags::P_NORMAL;
8209 
8210         static_assert(((~(SIInstrFlags::S_NAN |
8211                           SIInstrFlags::Q_NAN |
8212                           SIInstrFlags::N_INFINITY |
8213                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8214                       "mask not equal");
8215 
8216         SDLoc DL(N);
8217         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8218                            X, DAG.getConstant(Mask, DL, MVT::i32));
8219       }
8220     }
8221   }
8222 
8223   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8224     std::swap(LHS, RHS);
8225 
8226   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8227       RHS.hasOneUse()) {
8228     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8229     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8230     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8231     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8232     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8233         (RHS.getOperand(0) == LHS.getOperand(0) &&
8234          LHS.getOperand(0) == LHS.getOperand(1))) {
8235       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8236       unsigned NewMask = LCC == ISD::SETO ?
8237         Mask->getZExtValue() & ~OrdMask :
8238         Mask->getZExtValue() & OrdMask;
8239 
8240       SDLoc DL(N);
8241       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8242                          DAG.getConstant(NewMask, DL, MVT::i32));
8243     }
8244   }
8245 
8246   if (VT == MVT::i32 &&
8247       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8248     // and x, (sext cc from i1) => select cc, x, 0
8249     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8250       std::swap(LHS, RHS);
8251     if (isBoolSGPR(RHS.getOperand(0)))
8252       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8253                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8254   }
8255 
8256   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8257   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8258   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8259       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8260     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8261     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8262     if (LHSMask != ~0u && RHSMask != ~0u) {
8263       // Canonicalize the expression in an attempt to have fewer unique masks
8264       // and therefore fewer registers used to hold the masks.
8265       if (LHSMask > RHSMask) {
8266         std::swap(LHSMask, RHSMask);
8267         std::swap(LHS, RHS);
8268       }
8269 
8270       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8271       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8272       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8273       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8274 
8275       // Check of we need to combine values from two sources within a byte.
8276       if (!(LHSUsedLanes & RHSUsedLanes) &&
8277           // If we select high and lower word keep it for SDWA.
8278           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8279           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8280         // Each byte in each mask is either selector mask 0-3, or has higher
8281         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8282         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8283         // mask which is not 0xff wins. By anding both masks we have a correct
8284         // result except that 0x0c shall be corrected to give 0x0c only.
8285         uint32_t Mask = LHSMask & RHSMask;
8286         for (unsigned I = 0; I < 32; I += 8) {
8287           uint32_t ByteSel = 0xff << I;
8288           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8289             Mask &= (0x0c << I) & 0xffffffff;
8290         }
8291 
8292         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8293         // or 0x0c.
8294         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8295         SDLoc DL(N);
8296 
8297         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8298                            LHS.getOperand(0), RHS.getOperand(0),
8299                            DAG.getConstant(Sel, DL, MVT::i32));
8300       }
8301     }
8302   }
8303 
8304   return SDValue();
8305 }
8306 
8307 SDValue SITargetLowering::performOrCombine(SDNode *N,
8308                                            DAGCombinerInfo &DCI) const {
8309   SelectionDAG &DAG = DCI.DAG;
8310   SDValue LHS = N->getOperand(0);
8311   SDValue RHS = N->getOperand(1);
8312 
8313   EVT VT = N->getValueType(0);
8314   if (VT == MVT::i1) {
8315     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8316     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8317         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8318       SDValue Src = LHS.getOperand(0);
8319       if (Src != RHS.getOperand(0))
8320         return SDValue();
8321 
8322       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8323       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8324       if (!CLHS || !CRHS)
8325         return SDValue();
8326 
8327       // Only 10 bits are used.
8328       static const uint32_t MaxMask = 0x3ff;
8329 
8330       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8331       SDLoc DL(N);
8332       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8333                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8334     }
8335 
8336     return SDValue();
8337   }
8338 
8339   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8340   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8341       LHS.getOpcode() == AMDGPUISD::PERM &&
8342       isa<ConstantSDNode>(LHS.getOperand(2))) {
8343     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8344     if (!Sel)
8345       return SDValue();
8346 
8347     Sel |= LHS.getConstantOperandVal(2);
8348     SDLoc DL(N);
8349     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8350                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8351   }
8352 
8353   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8354   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8355   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8356       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8357     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8358     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8359     if (LHSMask != ~0u && RHSMask != ~0u) {
8360       // Canonicalize the expression in an attempt to have fewer unique masks
8361       // and therefore fewer registers used to hold the masks.
8362       if (LHSMask > RHSMask) {
8363         std::swap(LHSMask, RHSMask);
8364         std::swap(LHS, RHS);
8365       }
8366 
8367       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8368       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8369       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8370       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8371 
8372       // Check of we need to combine values from two sources within a byte.
8373       if (!(LHSUsedLanes & RHSUsedLanes) &&
8374           // If we select high and lower word keep it for SDWA.
8375           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8376           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8377         // Kill zero bytes selected by other mask. Zero value is 0xc.
8378         LHSMask &= ~RHSUsedLanes;
8379         RHSMask &= ~LHSUsedLanes;
8380         // Add 4 to each active LHS lane
8381         LHSMask |= LHSUsedLanes & 0x04040404;
8382         // Combine masks
8383         uint32_t Sel = LHSMask | RHSMask;
8384         SDLoc DL(N);
8385 
8386         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8387                            LHS.getOperand(0), RHS.getOperand(0),
8388                            DAG.getConstant(Sel, DL, MVT::i32));
8389       }
8390     }
8391   }
8392 
8393   if (VT != MVT::i64)
8394     return SDValue();
8395 
8396   // TODO: This could be a generic combine with a predicate for extracting the
8397   // high half of an integer being free.
8398 
8399   // (or i64:x, (zero_extend i32:y)) ->
8400   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8401   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8402       RHS.getOpcode() != ISD::ZERO_EXTEND)
8403     std::swap(LHS, RHS);
8404 
8405   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8406     SDValue ExtSrc = RHS.getOperand(0);
8407     EVT SrcVT = ExtSrc.getValueType();
8408     if (SrcVT == MVT::i32) {
8409       SDLoc SL(N);
8410       SDValue LowLHS, HiBits;
8411       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8412       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8413 
8414       DCI.AddToWorklist(LowOr.getNode());
8415       DCI.AddToWorklist(HiBits.getNode());
8416 
8417       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8418                                 LowOr, HiBits);
8419       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8420     }
8421   }
8422 
8423   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8424   if (CRHS) {
8425     if (SDValue Split
8426           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8427       return Split;
8428   }
8429 
8430   return SDValue();
8431 }
8432 
8433 SDValue SITargetLowering::performXorCombine(SDNode *N,
8434                                             DAGCombinerInfo &DCI) const {
8435   EVT VT = N->getValueType(0);
8436   if (VT != MVT::i64)
8437     return SDValue();
8438 
8439   SDValue LHS = N->getOperand(0);
8440   SDValue RHS = N->getOperand(1);
8441 
8442   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8443   if (CRHS) {
8444     if (SDValue Split
8445           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8446       return Split;
8447   }
8448 
8449   return SDValue();
8450 }
8451 
8452 // Instructions that will be lowered with a final instruction that zeros the
8453 // high result bits.
8454 // XXX - probably only need to list legal operations.
8455 static bool fp16SrcZerosHighBits(unsigned Opc) {
8456   switch (Opc) {
8457   case ISD::FADD:
8458   case ISD::FSUB:
8459   case ISD::FMUL:
8460   case ISD::FDIV:
8461   case ISD::FREM:
8462   case ISD::FMA:
8463   case ISD::FMAD:
8464   case ISD::FCANONICALIZE:
8465   case ISD::FP_ROUND:
8466   case ISD::UINT_TO_FP:
8467   case ISD::SINT_TO_FP:
8468   case ISD::FABS:
8469     // Fabs is lowered to a bit operation, but it's an and which will clear the
8470     // high bits anyway.
8471   case ISD::FSQRT:
8472   case ISD::FSIN:
8473   case ISD::FCOS:
8474   case ISD::FPOWI:
8475   case ISD::FPOW:
8476   case ISD::FLOG:
8477   case ISD::FLOG2:
8478   case ISD::FLOG10:
8479   case ISD::FEXP:
8480   case ISD::FEXP2:
8481   case ISD::FCEIL:
8482   case ISD::FTRUNC:
8483   case ISD::FRINT:
8484   case ISD::FNEARBYINT:
8485   case ISD::FROUND:
8486   case ISD::FFLOOR:
8487   case ISD::FMINNUM:
8488   case ISD::FMAXNUM:
8489   case AMDGPUISD::FRACT:
8490   case AMDGPUISD::CLAMP:
8491   case AMDGPUISD::COS_HW:
8492   case AMDGPUISD::SIN_HW:
8493   case AMDGPUISD::FMIN3:
8494   case AMDGPUISD::FMAX3:
8495   case AMDGPUISD::FMED3:
8496   case AMDGPUISD::FMAD_FTZ:
8497   case AMDGPUISD::RCP:
8498   case AMDGPUISD::RSQ:
8499   case AMDGPUISD::RCP_IFLAG:
8500   case AMDGPUISD::LDEXP:
8501     return true;
8502   default:
8503     // fcopysign, select and others may be lowered to 32-bit bit operations
8504     // which don't zero the high bits.
8505     return false;
8506   }
8507 }
8508 
8509 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8510                                                    DAGCombinerInfo &DCI) const {
8511   if (!Subtarget->has16BitInsts() ||
8512       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8513     return SDValue();
8514 
8515   EVT VT = N->getValueType(0);
8516   if (VT != MVT::i32)
8517     return SDValue();
8518 
8519   SDValue Src = N->getOperand(0);
8520   if (Src.getValueType() != MVT::i16)
8521     return SDValue();
8522 
8523   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8524   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8525   if (Src.getOpcode() == ISD::BITCAST) {
8526     SDValue BCSrc = Src.getOperand(0);
8527     if (BCSrc.getValueType() == MVT::f16 &&
8528         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8529       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8530   }
8531 
8532   return SDValue();
8533 }
8534 
8535 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8536                                                         DAGCombinerInfo &DCI)
8537                                                         const {
8538   SDValue Src = N->getOperand(0);
8539   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8540 
8541   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8542       VTSign->getVT() == MVT::i8) ||
8543       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8544       VTSign->getVT() == MVT::i16)) &&
8545       Src.hasOneUse()) {
8546     auto *M = cast<MemSDNode>(Src);
8547     SDValue Ops[] = {
8548       Src.getOperand(0), // Chain
8549       Src.getOperand(1), // rsrc
8550       Src.getOperand(2), // vindex
8551       Src.getOperand(3), // voffset
8552       Src.getOperand(4), // soffset
8553       Src.getOperand(5), // offset
8554       Src.getOperand(6),
8555       Src.getOperand(7)
8556     };
8557     // replace with BUFFER_LOAD_BYTE/SHORT
8558     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8559                                          Src.getOperand(0).getValueType());
8560     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8561                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8562     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8563                                                           ResList,
8564                                                           Ops, M->getMemoryVT(),
8565                                                           M->getMemOperand());
8566     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8567                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8568   }
8569   return SDValue();
8570 }
8571 
8572 SDValue SITargetLowering::performClassCombine(SDNode *N,
8573                                               DAGCombinerInfo &DCI) const {
8574   SelectionDAG &DAG = DCI.DAG;
8575   SDValue Mask = N->getOperand(1);
8576 
8577   // fp_class x, 0 -> false
8578   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8579     if (CMask->isNullValue())
8580       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8581   }
8582 
8583   if (N->getOperand(0).isUndef())
8584     return DAG.getUNDEF(MVT::i1);
8585 
8586   return SDValue();
8587 }
8588 
8589 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8590                                             DAGCombinerInfo &DCI) const {
8591   EVT VT = N->getValueType(0);
8592   SDValue N0 = N->getOperand(0);
8593 
8594   if (N0.isUndef())
8595     return N0;
8596 
8597   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8598                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8599     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8600                            N->getFlags());
8601   }
8602 
8603   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8604     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8605                            N0.getOperand(0), N->getFlags());
8606   }
8607 
8608   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8609 }
8610 
8611 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8612                                        unsigned MaxDepth) const {
8613   unsigned Opcode = Op.getOpcode();
8614   if (Opcode == ISD::FCANONICALIZE)
8615     return true;
8616 
8617   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8618     auto F = CFP->getValueAPF();
8619     if (F.isNaN() && F.isSignaling())
8620       return false;
8621     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8622   }
8623 
8624   // If source is a result of another standard FP operation it is already in
8625   // canonical form.
8626   if (MaxDepth == 0)
8627     return false;
8628 
8629   switch (Opcode) {
8630   // These will flush denorms if required.
8631   case ISD::FADD:
8632   case ISD::FSUB:
8633   case ISD::FMUL:
8634   case ISD::FCEIL:
8635   case ISD::FFLOOR:
8636   case ISD::FMA:
8637   case ISD::FMAD:
8638   case ISD::FSQRT:
8639   case ISD::FDIV:
8640   case ISD::FREM:
8641   case ISD::FP_ROUND:
8642   case ISD::FP_EXTEND:
8643   case AMDGPUISD::FMUL_LEGACY:
8644   case AMDGPUISD::FMAD_FTZ:
8645   case AMDGPUISD::RCP:
8646   case AMDGPUISD::RSQ:
8647   case AMDGPUISD::RSQ_CLAMP:
8648   case AMDGPUISD::RCP_LEGACY:
8649   case AMDGPUISD::RSQ_LEGACY:
8650   case AMDGPUISD::RCP_IFLAG:
8651   case AMDGPUISD::TRIG_PREOP:
8652   case AMDGPUISD::DIV_SCALE:
8653   case AMDGPUISD::DIV_FMAS:
8654   case AMDGPUISD::DIV_FIXUP:
8655   case AMDGPUISD::FRACT:
8656   case AMDGPUISD::LDEXP:
8657   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8658   case AMDGPUISD::CVT_F32_UBYTE0:
8659   case AMDGPUISD::CVT_F32_UBYTE1:
8660   case AMDGPUISD::CVT_F32_UBYTE2:
8661   case AMDGPUISD::CVT_F32_UBYTE3:
8662     return true;
8663 
8664   // It can/will be lowered or combined as a bit operation.
8665   // Need to check their input recursively to handle.
8666   case ISD::FNEG:
8667   case ISD::FABS:
8668   case ISD::FCOPYSIGN:
8669     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8670 
8671   case ISD::FSIN:
8672   case ISD::FCOS:
8673   case ISD::FSINCOS:
8674     return Op.getValueType().getScalarType() != MVT::f16;
8675 
8676   case ISD::FMINNUM:
8677   case ISD::FMAXNUM:
8678   case ISD::FMINNUM_IEEE:
8679   case ISD::FMAXNUM_IEEE:
8680   case AMDGPUISD::CLAMP:
8681   case AMDGPUISD::FMED3:
8682   case AMDGPUISD::FMAX3:
8683   case AMDGPUISD::FMIN3: {
8684     // FIXME: Shouldn't treat the generic operations different based these.
8685     // However, we aren't really required to flush the result from
8686     // minnum/maxnum..
8687 
8688     // snans will be quieted, so we only need to worry about denormals.
8689     if (Subtarget->supportsMinMaxDenormModes() ||
8690         denormalsEnabledForType(DAG, Op.getValueType()))
8691       return true;
8692 
8693     // Flushing may be required.
8694     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8695     // targets need to check their input recursively.
8696 
8697     // FIXME: Does this apply with clamp? It's implemented with max.
8698     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8699       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8700         return false;
8701     }
8702 
8703     return true;
8704   }
8705   case ISD::SELECT: {
8706     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8707            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8708   }
8709   case ISD::BUILD_VECTOR: {
8710     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8711       SDValue SrcOp = Op.getOperand(i);
8712       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8713         return false;
8714     }
8715 
8716     return true;
8717   }
8718   case ISD::EXTRACT_VECTOR_ELT:
8719   case ISD::EXTRACT_SUBVECTOR: {
8720     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8721   }
8722   case ISD::INSERT_VECTOR_ELT: {
8723     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8724            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8725   }
8726   case ISD::UNDEF:
8727     // Could be anything.
8728     return false;
8729 
8730   case ISD::BITCAST: {
8731     // Hack round the mess we make when legalizing extract_vector_elt
8732     SDValue Src = Op.getOperand(0);
8733     if (Src.getValueType() == MVT::i16 &&
8734         Src.getOpcode() == ISD::TRUNCATE) {
8735       SDValue TruncSrc = Src.getOperand(0);
8736       if (TruncSrc.getValueType() == MVT::i32 &&
8737           TruncSrc.getOpcode() == ISD::BITCAST &&
8738           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8739         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8740       }
8741     }
8742 
8743     return false;
8744   }
8745   case ISD::INTRINSIC_WO_CHAIN: {
8746     unsigned IntrinsicID
8747       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8748     // TODO: Handle more intrinsics
8749     switch (IntrinsicID) {
8750     case Intrinsic::amdgcn_cvt_pkrtz:
8751     case Intrinsic::amdgcn_cubeid:
8752     case Intrinsic::amdgcn_frexp_mant:
8753     case Intrinsic::amdgcn_fdot2:
8754       return true;
8755     default:
8756       break;
8757     }
8758 
8759     LLVM_FALLTHROUGH;
8760   }
8761   default:
8762     return denormalsEnabledForType(DAG, Op.getValueType()) &&
8763            DAG.isKnownNeverSNaN(Op);
8764   }
8765 
8766   llvm_unreachable("invalid operation");
8767 }
8768 
8769 // Constant fold canonicalize.
8770 SDValue SITargetLowering::getCanonicalConstantFP(
8771   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8772   // Flush denormals to 0 if not enabled.
8773   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
8774     return DAG.getConstantFP(0.0, SL, VT);
8775 
8776   if (C.isNaN()) {
8777     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8778     if (C.isSignaling()) {
8779       // Quiet a signaling NaN.
8780       // FIXME: Is this supposed to preserve payload bits?
8781       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8782     }
8783 
8784     // Make sure it is the canonical NaN bitpattern.
8785     //
8786     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8787     // immediate?
8788     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8789       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8790   }
8791 
8792   // Already canonical.
8793   return DAG.getConstantFP(C, SL, VT);
8794 }
8795 
8796 static bool vectorEltWillFoldAway(SDValue Op) {
8797   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8798 }
8799 
8800 SDValue SITargetLowering::performFCanonicalizeCombine(
8801   SDNode *N,
8802   DAGCombinerInfo &DCI) const {
8803   SelectionDAG &DAG = DCI.DAG;
8804   SDValue N0 = N->getOperand(0);
8805   EVT VT = N->getValueType(0);
8806 
8807   // fcanonicalize undef -> qnan
8808   if (N0.isUndef()) {
8809     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8810     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8811   }
8812 
8813   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8814     EVT VT = N->getValueType(0);
8815     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8816   }
8817 
8818   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8819   //                                                   (fcanonicalize k)
8820   //
8821   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8822 
8823   // TODO: This could be better with wider vectors that will be split to v2f16,
8824   // and to consider uses since there aren't that many packed operations.
8825   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8826       isTypeLegal(MVT::v2f16)) {
8827     SDLoc SL(N);
8828     SDValue NewElts[2];
8829     SDValue Lo = N0.getOperand(0);
8830     SDValue Hi = N0.getOperand(1);
8831     EVT EltVT = Lo.getValueType();
8832 
8833     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8834       for (unsigned I = 0; I != 2; ++I) {
8835         SDValue Op = N0.getOperand(I);
8836         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8837           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8838                                               CFP->getValueAPF());
8839         } else if (Op.isUndef()) {
8840           // Handled below based on what the other operand is.
8841           NewElts[I] = Op;
8842         } else {
8843           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8844         }
8845       }
8846 
8847       // If one half is undef, and one is constant, perfer a splat vector rather
8848       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8849       // cheaper to use and may be free with a packed operation.
8850       if (NewElts[0].isUndef()) {
8851         if (isa<ConstantFPSDNode>(NewElts[1]))
8852           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8853             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8854       }
8855 
8856       if (NewElts[1].isUndef()) {
8857         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8858           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8859       }
8860 
8861       return DAG.getBuildVector(VT, SL, NewElts);
8862     }
8863   }
8864 
8865   unsigned SrcOpc = N0.getOpcode();
8866 
8867   // If it's free to do so, push canonicalizes further up the source, which may
8868   // find a canonical source.
8869   //
8870   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8871   // sNaNs.
8872   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8873     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8874     if (CRHS && N0.hasOneUse()) {
8875       SDLoc SL(N);
8876       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8877                                    N0.getOperand(0));
8878       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8879       DCI.AddToWorklist(Canon0.getNode());
8880 
8881       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8882     }
8883   }
8884 
8885   return isCanonicalized(DAG, N0) ? N0 : SDValue();
8886 }
8887 
8888 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
8889   switch (Opc) {
8890   case ISD::FMAXNUM:
8891   case ISD::FMAXNUM_IEEE:
8892     return AMDGPUISD::FMAX3;
8893   case ISD::SMAX:
8894     return AMDGPUISD::SMAX3;
8895   case ISD::UMAX:
8896     return AMDGPUISD::UMAX3;
8897   case ISD::FMINNUM:
8898   case ISD::FMINNUM_IEEE:
8899     return AMDGPUISD::FMIN3;
8900   case ISD::SMIN:
8901     return AMDGPUISD::SMIN3;
8902   case ISD::UMIN:
8903     return AMDGPUISD::UMIN3;
8904   default:
8905     llvm_unreachable("Not a min/max opcode");
8906   }
8907 }
8908 
8909 SDValue SITargetLowering::performIntMed3ImmCombine(
8910   SelectionDAG &DAG, const SDLoc &SL,
8911   SDValue Op0, SDValue Op1, bool Signed) const {
8912   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8913   if (!K1)
8914     return SDValue();
8915 
8916   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8917   if (!K0)
8918     return SDValue();
8919 
8920   if (Signed) {
8921     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8922       return SDValue();
8923   } else {
8924     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8925       return SDValue();
8926   }
8927 
8928   EVT VT = K0->getValueType(0);
8929   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8930   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8931     return DAG.getNode(Med3Opc, SL, VT,
8932                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8933   }
8934 
8935   // If there isn't a 16-bit med3 operation, convert to 32-bit.
8936   MVT NVT = MVT::i32;
8937   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8938 
8939   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8940   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8941   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
8942 
8943   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8944   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
8945 }
8946 
8947 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8948   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8949     return C;
8950 
8951   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8952     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
8953       return C;
8954   }
8955 
8956   return nullptr;
8957 }
8958 
8959 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
8960                                                   const SDLoc &SL,
8961                                                   SDValue Op0,
8962                                                   SDValue Op1) const {
8963   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
8964   if (!K1)
8965     return SDValue();
8966 
8967   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
8968   if (!K0)
8969     return SDValue();
8970 
8971   // Ordered >= (although NaN inputs should have folded away by now).
8972   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
8973   if (Cmp == APFloat::cmpGreaterThan)
8974     return SDValue();
8975 
8976   const MachineFunction &MF = DAG.getMachineFunction();
8977   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8978 
8979   // TODO: Check IEEE bit enabled?
8980   EVT VT = Op0.getValueType();
8981   if (Info->getMode().DX10Clamp) {
8982     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
8983     // hardware fmed3 behavior converting to a min.
8984     // FIXME: Should this be allowing -0.0?
8985     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
8986       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
8987   }
8988 
8989   // med3 for f16 is only available on gfx9+, and not available for v2f16.
8990   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
8991     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
8992     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
8993     // then give the other result, which is different from med3 with a NaN
8994     // input.
8995     SDValue Var = Op0.getOperand(0);
8996     if (!DAG.isKnownNeverSNaN(Var))
8997       return SDValue();
8998 
8999     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9000 
9001     if ((!K0->hasOneUse() ||
9002          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9003         (!K1->hasOneUse() ||
9004          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9005       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9006                          Var, SDValue(K0, 0), SDValue(K1, 0));
9007     }
9008   }
9009 
9010   return SDValue();
9011 }
9012 
9013 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9014                                                DAGCombinerInfo &DCI) const {
9015   SelectionDAG &DAG = DCI.DAG;
9016 
9017   EVT VT = N->getValueType(0);
9018   unsigned Opc = N->getOpcode();
9019   SDValue Op0 = N->getOperand(0);
9020   SDValue Op1 = N->getOperand(1);
9021 
9022   // Only do this if the inner op has one use since this will just increases
9023   // register pressure for no benefit.
9024 
9025   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9026       !VT.isVector() &&
9027       (VT == MVT::i32 || VT == MVT::f32 ||
9028        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9029     // max(max(a, b), c) -> max3(a, b, c)
9030     // min(min(a, b), c) -> min3(a, b, c)
9031     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9032       SDLoc DL(N);
9033       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9034                          DL,
9035                          N->getValueType(0),
9036                          Op0.getOperand(0),
9037                          Op0.getOperand(1),
9038                          Op1);
9039     }
9040 
9041     // Try commuted.
9042     // max(a, max(b, c)) -> max3(a, b, c)
9043     // min(a, min(b, c)) -> min3(a, b, c)
9044     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9045       SDLoc DL(N);
9046       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9047                          DL,
9048                          N->getValueType(0),
9049                          Op0,
9050                          Op1.getOperand(0),
9051                          Op1.getOperand(1));
9052     }
9053   }
9054 
9055   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9056   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9057     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9058       return Med3;
9059   }
9060 
9061   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9062     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9063       return Med3;
9064   }
9065 
9066   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9067   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9068        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9069        (Opc == AMDGPUISD::FMIN_LEGACY &&
9070         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9071       (VT == MVT::f32 || VT == MVT::f64 ||
9072        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9073        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9074       Op0.hasOneUse()) {
9075     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9076       return Res;
9077   }
9078 
9079   return SDValue();
9080 }
9081 
9082 static bool isClampZeroToOne(SDValue A, SDValue B) {
9083   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9084     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9085       // FIXME: Should this be allowing -0.0?
9086       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9087              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9088     }
9089   }
9090 
9091   return false;
9092 }
9093 
9094 // FIXME: Should only worry about snans for version with chain.
9095 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9096                                               DAGCombinerInfo &DCI) const {
9097   EVT VT = N->getValueType(0);
9098   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9099   // NaNs. With a NaN input, the order of the operands may change the result.
9100 
9101   SelectionDAG &DAG = DCI.DAG;
9102   SDLoc SL(N);
9103 
9104   SDValue Src0 = N->getOperand(0);
9105   SDValue Src1 = N->getOperand(1);
9106   SDValue Src2 = N->getOperand(2);
9107 
9108   if (isClampZeroToOne(Src0, Src1)) {
9109     // const_a, const_b, x -> clamp is safe in all cases including signaling
9110     // nans.
9111     // FIXME: Should this be allowing -0.0?
9112     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9113   }
9114 
9115   const MachineFunction &MF = DAG.getMachineFunction();
9116   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9117 
9118   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9119   // handling no dx10-clamp?
9120   if (Info->getMode().DX10Clamp) {
9121     // If NaNs is clamped to 0, we are free to reorder the inputs.
9122 
9123     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9124       std::swap(Src0, Src1);
9125 
9126     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9127       std::swap(Src1, Src2);
9128 
9129     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9130       std::swap(Src0, Src1);
9131 
9132     if (isClampZeroToOne(Src1, Src2))
9133       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9134   }
9135 
9136   return SDValue();
9137 }
9138 
9139 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9140                                                  DAGCombinerInfo &DCI) const {
9141   SDValue Src0 = N->getOperand(0);
9142   SDValue Src1 = N->getOperand(1);
9143   if (Src0.isUndef() && Src1.isUndef())
9144     return DCI.DAG.getUNDEF(N->getValueType(0));
9145   return SDValue();
9146 }
9147 
9148 SDValue SITargetLowering::performExtractVectorEltCombine(
9149   SDNode *N, DAGCombinerInfo &DCI) const {
9150   SDValue Vec = N->getOperand(0);
9151   SelectionDAG &DAG = DCI.DAG;
9152 
9153   EVT VecVT = Vec.getValueType();
9154   EVT EltVT = VecVT.getVectorElementType();
9155 
9156   if ((Vec.getOpcode() == ISD::FNEG ||
9157        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9158     SDLoc SL(N);
9159     EVT EltVT = N->getValueType(0);
9160     SDValue Idx = N->getOperand(1);
9161     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9162                               Vec.getOperand(0), Idx);
9163     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9164   }
9165 
9166   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9167   //    =>
9168   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9169   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9170   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9171   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9172     SDLoc SL(N);
9173     EVT EltVT = N->getValueType(0);
9174     SDValue Idx = N->getOperand(1);
9175     unsigned Opc = Vec.getOpcode();
9176 
9177     switch(Opc) {
9178     default:
9179       break;
9180       // TODO: Support other binary operations.
9181     case ISD::FADD:
9182     case ISD::FSUB:
9183     case ISD::FMUL:
9184     case ISD::ADD:
9185     case ISD::UMIN:
9186     case ISD::UMAX:
9187     case ISD::SMIN:
9188     case ISD::SMAX:
9189     case ISD::FMAXNUM:
9190     case ISD::FMINNUM:
9191     case ISD::FMAXNUM_IEEE:
9192     case ISD::FMINNUM_IEEE: {
9193       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9194                                  Vec.getOperand(0), Idx);
9195       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9196                                  Vec.getOperand(1), Idx);
9197 
9198       DCI.AddToWorklist(Elt0.getNode());
9199       DCI.AddToWorklist(Elt1.getNode());
9200       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9201     }
9202     }
9203   }
9204 
9205   unsigned VecSize = VecVT.getSizeInBits();
9206   unsigned EltSize = EltVT.getSizeInBits();
9207 
9208   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9209   // This elminates non-constant index and subsequent movrel or scratch access.
9210   // Sub-dword vectors of size 2 dword or less have better implementation.
9211   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9212   // instructions.
9213   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9214       !isa<ConstantSDNode>(N->getOperand(1))) {
9215     SDLoc SL(N);
9216     SDValue Idx = N->getOperand(1);
9217     SDValue V;
9218     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9219       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9220       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9221       if (I == 0)
9222         V = Elt;
9223       else
9224         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9225     }
9226     return V;
9227   }
9228 
9229   if (!DCI.isBeforeLegalize())
9230     return SDValue();
9231 
9232   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9233   // elements. This exposes more load reduction opportunities by replacing
9234   // multiple small extract_vector_elements with a single 32-bit extract.
9235   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9236   if (isa<MemSDNode>(Vec) &&
9237       EltSize <= 16 &&
9238       EltVT.isByteSized() &&
9239       VecSize > 32 &&
9240       VecSize % 32 == 0 &&
9241       Idx) {
9242     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9243 
9244     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9245     unsigned EltIdx = BitIndex / 32;
9246     unsigned LeftoverBitIdx = BitIndex % 32;
9247     SDLoc SL(N);
9248 
9249     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9250     DCI.AddToWorklist(Cast.getNode());
9251 
9252     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9253                               DAG.getConstant(EltIdx, SL, MVT::i32));
9254     DCI.AddToWorklist(Elt.getNode());
9255     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9256                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9257     DCI.AddToWorklist(Srl.getNode());
9258 
9259     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9260     DCI.AddToWorklist(Trunc.getNode());
9261     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9262   }
9263 
9264   return SDValue();
9265 }
9266 
9267 SDValue
9268 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9269                                                 DAGCombinerInfo &DCI) const {
9270   SDValue Vec = N->getOperand(0);
9271   SDValue Idx = N->getOperand(2);
9272   EVT VecVT = Vec.getValueType();
9273   EVT EltVT = VecVT.getVectorElementType();
9274   unsigned VecSize = VecVT.getSizeInBits();
9275   unsigned EltSize = EltVT.getSizeInBits();
9276 
9277   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9278   // => BUILD_VECTOR n x select (e, const-idx)
9279   // This elminates non-constant index and subsequent movrel or scratch access.
9280   // Sub-dword vectors of size 2 dword or less have better implementation.
9281   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9282   // instructions.
9283   if (isa<ConstantSDNode>(Idx) ||
9284       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9285     return SDValue();
9286 
9287   SelectionDAG &DAG = DCI.DAG;
9288   SDLoc SL(N);
9289   SDValue Ins = N->getOperand(1);
9290   EVT IdxVT = Idx.getValueType();
9291 
9292   SmallVector<SDValue, 16> Ops;
9293   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9294     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9295     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9296     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9297     Ops.push_back(V);
9298   }
9299 
9300   return DAG.getBuildVector(VecVT, SL, Ops);
9301 }
9302 
9303 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9304                                           const SDNode *N0,
9305                                           const SDNode *N1) const {
9306   EVT VT = N0->getValueType(0);
9307 
9308   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9309   // support denormals ever.
9310   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9311        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9312         getSubtarget()->hasMadF16())) &&
9313        isOperationLegal(ISD::FMAD, VT))
9314     return ISD::FMAD;
9315 
9316   const TargetOptions &Options = DAG.getTarget().Options;
9317   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9318        (N0->getFlags().hasAllowContract() &&
9319         N1->getFlags().hasAllowContract())) &&
9320       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9321     return ISD::FMA;
9322   }
9323 
9324   return 0;
9325 }
9326 
9327 // For a reassociatable opcode perform:
9328 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9329 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9330                                                SelectionDAG &DAG) const {
9331   EVT VT = N->getValueType(0);
9332   if (VT != MVT::i32 && VT != MVT::i64)
9333     return SDValue();
9334 
9335   unsigned Opc = N->getOpcode();
9336   SDValue Op0 = N->getOperand(0);
9337   SDValue Op1 = N->getOperand(1);
9338 
9339   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9340     return SDValue();
9341 
9342   if (Op0->isDivergent())
9343     std::swap(Op0, Op1);
9344 
9345   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9346     return SDValue();
9347 
9348   SDValue Op2 = Op1.getOperand(1);
9349   Op1 = Op1.getOperand(0);
9350   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9351     return SDValue();
9352 
9353   if (Op1->isDivergent())
9354     std::swap(Op1, Op2);
9355 
9356   // If either operand is constant this will conflict with
9357   // DAGCombiner::ReassociateOps().
9358   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9359       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9360     return SDValue();
9361 
9362   SDLoc SL(N);
9363   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9364   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9365 }
9366 
9367 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9368                            EVT VT,
9369                            SDValue N0, SDValue N1, SDValue N2,
9370                            bool Signed) {
9371   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9372   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9373   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9374   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9375 }
9376 
9377 SDValue SITargetLowering::performAddCombine(SDNode *N,
9378                                             DAGCombinerInfo &DCI) const {
9379   SelectionDAG &DAG = DCI.DAG;
9380   EVT VT = N->getValueType(0);
9381   SDLoc SL(N);
9382   SDValue LHS = N->getOperand(0);
9383   SDValue RHS = N->getOperand(1);
9384 
9385   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9386       && Subtarget->hasMad64_32() &&
9387       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9388       VT.getScalarSizeInBits() <= 64) {
9389     if (LHS.getOpcode() != ISD::MUL)
9390       std::swap(LHS, RHS);
9391 
9392     SDValue MulLHS = LHS.getOperand(0);
9393     SDValue MulRHS = LHS.getOperand(1);
9394     SDValue AddRHS = RHS;
9395 
9396     // TODO: Maybe restrict if SGPR inputs.
9397     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9398         numBitsUnsigned(MulRHS, DAG) <= 32) {
9399       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9400       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9401       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9402       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9403     }
9404 
9405     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9406       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9407       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9408       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9409       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9410     }
9411 
9412     return SDValue();
9413   }
9414 
9415   if (SDValue V = reassociateScalarOps(N, DAG)) {
9416     return V;
9417   }
9418 
9419   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9420     return SDValue();
9421 
9422   // add x, zext (setcc) => addcarry x, 0, setcc
9423   // add x, sext (setcc) => subcarry x, 0, setcc
9424   unsigned Opc = LHS.getOpcode();
9425   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9426       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9427     std::swap(RHS, LHS);
9428 
9429   Opc = RHS.getOpcode();
9430   switch (Opc) {
9431   default: break;
9432   case ISD::ZERO_EXTEND:
9433   case ISD::SIGN_EXTEND:
9434   case ISD::ANY_EXTEND: {
9435     auto Cond = RHS.getOperand(0);
9436     // If this won't be a real VOPC output, we would still need to insert an
9437     // extra instruction anyway.
9438     if (!isBoolSGPR(Cond))
9439       break;
9440     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9441     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9442     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9443     return DAG.getNode(Opc, SL, VTList, Args);
9444   }
9445   case ISD::ADDCARRY: {
9446     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9447     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9448     if (!C || C->getZExtValue() != 0) break;
9449     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9450     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9451   }
9452   }
9453   return SDValue();
9454 }
9455 
9456 SDValue SITargetLowering::performSubCombine(SDNode *N,
9457                                             DAGCombinerInfo &DCI) const {
9458   SelectionDAG &DAG = DCI.DAG;
9459   EVT VT = N->getValueType(0);
9460 
9461   if (VT != MVT::i32)
9462     return SDValue();
9463 
9464   SDLoc SL(N);
9465   SDValue LHS = N->getOperand(0);
9466   SDValue RHS = N->getOperand(1);
9467 
9468   // sub x, zext (setcc) => subcarry x, 0, setcc
9469   // sub x, sext (setcc) => addcarry x, 0, setcc
9470   unsigned Opc = RHS.getOpcode();
9471   switch (Opc) {
9472   default: break;
9473   case ISD::ZERO_EXTEND:
9474   case ISD::SIGN_EXTEND:
9475   case ISD::ANY_EXTEND: {
9476     auto Cond = RHS.getOperand(0);
9477     // If this won't be a real VOPC output, we would still need to insert an
9478     // extra instruction anyway.
9479     if (!isBoolSGPR(Cond))
9480       break;
9481     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9482     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9483     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9484     return DAG.getNode(Opc, SL, VTList, Args);
9485   }
9486   }
9487 
9488   if (LHS.getOpcode() == ISD::SUBCARRY) {
9489     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9490     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9491     if (!C || !C->isNullValue())
9492       return SDValue();
9493     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9494     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9495   }
9496   return SDValue();
9497 }
9498 
9499 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9500   DAGCombinerInfo &DCI) const {
9501 
9502   if (N->getValueType(0) != MVT::i32)
9503     return SDValue();
9504 
9505   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9506   if (!C || C->getZExtValue() != 0)
9507     return SDValue();
9508 
9509   SelectionDAG &DAG = DCI.DAG;
9510   SDValue LHS = N->getOperand(0);
9511 
9512   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9513   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9514   unsigned LHSOpc = LHS.getOpcode();
9515   unsigned Opc = N->getOpcode();
9516   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9517       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9518     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9519     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9520   }
9521   return SDValue();
9522 }
9523 
9524 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9525                                              DAGCombinerInfo &DCI) const {
9526   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9527     return SDValue();
9528 
9529   SelectionDAG &DAG = DCI.DAG;
9530   EVT VT = N->getValueType(0);
9531 
9532   SDLoc SL(N);
9533   SDValue LHS = N->getOperand(0);
9534   SDValue RHS = N->getOperand(1);
9535 
9536   // These should really be instruction patterns, but writing patterns with
9537   // source modiifiers is a pain.
9538 
9539   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9540   if (LHS.getOpcode() == ISD::FADD) {
9541     SDValue A = LHS.getOperand(0);
9542     if (A == LHS.getOperand(1)) {
9543       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9544       if (FusedOp != 0) {
9545         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9546         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9547       }
9548     }
9549   }
9550 
9551   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9552   if (RHS.getOpcode() == ISD::FADD) {
9553     SDValue A = RHS.getOperand(0);
9554     if (A == RHS.getOperand(1)) {
9555       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9556       if (FusedOp != 0) {
9557         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9558         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9559       }
9560     }
9561   }
9562 
9563   return SDValue();
9564 }
9565 
9566 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9567                                              DAGCombinerInfo &DCI) const {
9568   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9569     return SDValue();
9570 
9571   SelectionDAG &DAG = DCI.DAG;
9572   SDLoc SL(N);
9573   EVT VT = N->getValueType(0);
9574   assert(!VT.isVector());
9575 
9576   // Try to get the fneg to fold into the source modifier. This undoes generic
9577   // DAG combines and folds them into the mad.
9578   //
9579   // Only do this if we are not trying to support denormals. v_mad_f32 does
9580   // not support denormals ever.
9581   SDValue LHS = N->getOperand(0);
9582   SDValue RHS = N->getOperand(1);
9583   if (LHS.getOpcode() == ISD::FADD) {
9584     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9585     SDValue A = LHS.getOperand(0);
9586     if (A == LHS.getOperand(1)) {
9587       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9588       if (FusedOp != 0){
9589         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9590         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9591 
9592         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9593       }
9594     }
9595   }
9596 
9597   if (RHS.getOpcode() == ISD::FADD) {
9598     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9599 
9600     SDValue A = RHS.getOperand(0);
9601     if (A == RHS.getOperand(1)) {
9602       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9603       if (FusedOp != 0){
9604         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9605         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9606       }
9607     }
9608   }
9609 
9610   return SDValue();
9611 }
9612 
9613 SDValue SITargetLowering::performFMACombine(SDNode *N,
9614                                             DAGCombinerInfo &DCI) const {
9615   SelectionDAG &DAG = DCI.DAG;
9616   EVT VT = N->getValueType(0);
9617   SDLoc SL(N);
9618 
9619   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9620     return SDValue();
9621 
9622   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9623   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9624   SDValue Op1 = N->getOperand(0);
9625   SDValue Op2 = N->getOperand(1);
9626   SDValue FMA = N->getOperand(2);
9627 
9628   if (FMA.getOpcode() != ISD::FMA ||
9629       Op1.getOpcode() != ISD::FP_EXTEND ||
9630       Op2.getOpcode() != ISD::FP_EXTEND)
9631     return SDValue();
9632 
9633   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9634   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9635   // is sufficient to allow generaing fdot2.
9636   const TargetOptions &Options = DAG.getTarget().Options;
9637   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9638       (N->getFlags().hasAllowContract() &&
9639        FMA->getFlags().hasAllowContract())) {
9640     Op1 = Op1.getOperand(0);
9641     Op2 = Op2.getOperand(0);
9642     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9643         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9644       return SDValue();
9645 
9646     SDValue Vec1 = Op1.getOperand(0);
9647     SDValue Idx1 = Op1.getOperand(1);
9648     SDValue Vec2 = Op2.getOperand(0);
9649 
9650     SDValue FMAOp1 = FMA.getOperand(0);
9651     SDValue FMAOp2 = FMA.getOperand(1);
9652     SDValue FMAAcc = FMA.getOperand(2);
9653 
9654     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9655         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9656       return SDValue();
9657 
9658     FMAOp1 = FMAOp1.getOperand(0);
9659     FMAOp2 = FMAOp2.getOperand(0);
9660     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9661         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9662       return SDValue();
9663 
9664     SDValue Vec3 = FMAOp1.getOperand(0);
9665     SDValue Vec4 = FMAOp2.getOperand(0);
9666     SDValue Idx2 = FMAOp1.getOperand(1);
9667 
9668     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9669         // Idx1 and Idx2 cannot be the same.
9670         Idx1 == Idx2)
9671       return SDValue();
9672 
9673     if (Vec1 == Vec2 || Vec3 == Vec4)
9674       return SDValue();
9675 
9676     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9677       return SDValue();
9678 
9679     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9680         (Vec1 == Vec4 && Vec2 == Vec3)) {
9681       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9682                          DAG.getTargetConstant(0, SL, MVT::i1));
9683     }
9684   }
9685   return SDValue();
9686 }
9687 
9688 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9689                                               DAGCombinerInfo &DCI) const {
9690   SelectionDAG &DAG = DCI.DAG;
9691   SDLoc SL(N);
9692 
9693   SDValue LHS = N->getOperand(0);
9694   SDValue RHS = N->getOperand(1);
9695   EVT VT = LHS.getValueType();
9696   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9697 
9698   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9699   if (!CRHS) {
9700     CRHS = dyn_cast<ConstantSDNode>(LHS);
9701     if (CRHS) {
9702       std::swap(LHS, RHS);
9703       CC = getSetCCSwappedOperands(CC);
9704     }
9705   }
9706 
9707   if (CRHS) {
9708     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9709         isBoolSGPR(LHS.getOperand(0))) {
9710       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9711       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9712       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9713       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9714       if ((CRHS->isAllOnesValue() &&
9715            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9716           (CRHS->isNullValue() &&
9717            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9718         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9719                            DAG.getConstant(-1, SL, MVT::i1));
9720       if ((CRHS->isAllOnesValue() &&
9721            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9722           (CRHS->isNullValue() &&
9723            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9724         return LHS.getOperand(0);
9725     }
9726 
9727     uint64_t CRHSVal = CRHS->getZExtValue();
9728     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9729         LHS.getOpcode() == ISD::SELECT &&
9730         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9731         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9732         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9733         isBoolSGPR(LHS.getOperand(0))) {
9734       // Given CT != FT:
9735       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9736       // setcc (select cc, CT, CF), CF, ne => cc
9737       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9738       // setcc (select cc, CT, CF), CT, eq => cc
9739       uint64_t CT = LHS.getConstantOperandVal(1);
9740       uint64_t CF = LHS.getConstantOperandVal(2);
9741 
9742       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9743           (CT == CRHSVal && CC == ISD::SETNE))
9744         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9745                            DAG.getConstant(-1, SL, MVT::i1));
9746       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9747           (CT == CRHSVal && CC == ISD::SETEQ))
9748         return LHS.getOperand(0);
9749     }
9750   }
9751 
9752   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9753                                            VT != MVT::f16))
9754     return SDValue();
9755 
9756   // Match isinf/isfinite pattern
9757   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9758   // (fcmp one (fabs x), inf) -> (fp_class x,
9759   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9760   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9761     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9762     if (!CRHS)
9763       return SDValue();
9764 
9765     const APFloat &APF = CRHS->getValueAPF();
9766     if (APF.isInfinity() && !APF.isNegative()) {
9767       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9768                                  SIInstrFlags::N_INFINITY;
9769       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9770                                     SIInstrFlags::P_ZERO |
9771                                     SIInstrFlags::N_NORMAL |
9772                                     SIInstrFlags::P_NORMAL |
9773                                     SIInstrFlags::N_SUBNORMAL |
9774                                     SIInstrFlags::P_SUBNORMAL;
9775       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9776       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9777                          DAG.getConstant(Mask, SL, MVT::i32));
9778     }
9779   }
9780 
9781   return SDValue();
9782 }
9783 
9784 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9785                                                      DAGCombinerInfo &DCI) const {
9786   SelectionDAG &DAG = DCI.DAG;
9787   SDLoc SL(N);
9788   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9789 
9790   SDValue Src = N->getOperand(0);
9791   SDValue Srl = N->getOperand(0);
9792   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9793     Srl = Srl.getOperand(0);
9794 
9795   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9796   if (Srl.getOpcode() == ISD::SRL) {
9797     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9798     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9799     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9800 
9801     if (const ConstantSDNode *C =
9802         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9803       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9804                                EVT(MVT::i32));
9805 
9806       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9807       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9808         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9809                            MVT::f32, Srl);
9810       }
9811     }
9812   }
9813 
9814   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9815 
9816   KnownBits Known;
9817   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9818                                         !DCI.isBeforeLegalizeOps());
9819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9820   if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
9821     DCI.CommitTargetLoweringOpt(TLO);
9822   }
9823 
9824   return SDValue();
9825 }
9826 
9827 SDValue SITargetLowering::performClampCombine(SDNode *N,
9828                                               DAGCombinerInfo &DCI) const {
9829   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9830   if (!CSrc)
9831     return SDValue();
9832 
9833   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9834   const APFloat &F = CSrc->getValueAPF();
9835   APFloat Zero = APFloat::getZero(F.getSemantics());
9836   APFloat::cmpResult Cmp0 = F.compare(Zero);
9837   if (Cmp0 == APFloat::cmpLessThan ||
9838       (Cmp0 == APFloat::cmpUnordered &&
9839        MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9840     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9841   }
9842 
9843   APFloat One(F.getSemantics(), "1.0");
9844   APFloat::cmpResult Cmp1 = F.compare(One);
9845   if (Cmp1 == APFloat::cmpGreaterThan)
9846     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9847 
9848   return SDValue(CSrc, 0);
9849 }
9850 
9851 
9852 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9853                                             DAGCombinerInfo &DCI) const {
9854   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9855     return SDValue();
9856   switch (N->getOpcode()) {
9857   default:
9858     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9859   case ISD::ADD:
9860     return performAddCombine(N, DCI);
9861   case ISD::SUB:
9862     return performSubCombine(N, DCI);
9863   case ISD::ADDCARRY:
9864   case ISD::SUBCARRY:
9865     return performAddCarrySubCarryCombine(N, DCI);
9866   case ISD::FADD:
9867     return performFAddCombine(N, DCI);
9868   case ISD::FSUB:
9869     return performFSubCombine(N, DCI);
9870   case ISD::SETCC:
9871     return performSetCCCombine(N, DCI);
9872   case ISD::FMAXNUM:
9873   case ISD::FMINNUM:
9874   case ISD::FMAXNUM_IEEE:
9875   case ISD::FMINNUM_IEEE:
9876   case ISD::SMAX:
9877   case ISD::SMIN:
9878   case ISD::UMAX:
9879   case ISD::UMIN:
9880   case AMDGPUISD::FMIN_LEGACY:
9881   case AMDGPUISD::FMAX_LEGACY:
9882     return performMinMaxCombine(N, DCI);
9883   case ISD::FMA:
9884     return performFMACombine(N, DCI);
9885   case ISD::LOAD: {
9886     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9887       return Widended;
9888     LLVM_FALLTHROUGH;
9889   }
9890   case ISD::STORE:
9891   case ISD::ATOMIC_LOAD:
9892   case ISD::ATOMIC_STORE:
9893   case ISD::ATOMIC_CMP_SWAP:
9894   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9895   case ISD::ATOMIC_SWAP:
9896   case ISD::ATOMIC_LOAD_ADD:
9897   case ISD::ATOMIC_LOAD_SUB:
9898   case ISD::ATOMIC_LOAD_AND:
9899   case ISD::ATOMIC_LOAD_OR:
9900   case ISD::ATOMIC_LOAD_XOR:
9901   case ISD::ATOMIC_LOAD_NAND:
9902   case ISD::ATOMIC_LOAD_MIN:
9903   case ISD::ATOMIC_LOAD_MAX:
9904   case ISD::ATOMIC_LOAD_UMIN:
9905   case ISD::ATOMIC_LOAD_UMAX:
9906   case ISD::ATOMIC_LOAD_FADD:
9907   case AMDGPUISD::ATOMIC_INC:
9908   case AMDGPUISD::ATOMIC_DEC:
9909   case AMDGPUISD::ATOMIC_LOAD_FMIN:
9910   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
9911     if (DCI.isBeforeLegalize())
9912       break;
9913     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
9914   case ISD::AND:
9915     return performAndCombine(N, DCI);
9916   case ISD::OR:
9917     return performOrCombine(N, DCI);
9918   case ISD::XOR:
9919     return performXorCombine(N, DCI);
9920   case ISD::ZERO_EXTEND:
9921     return performZeroExtendCombine(N, DCI);
9922   case ISD::SIGN_EXTEND_INREG:
9923     return performSignExtendInRegCombine(N , DCI);
9924   case AMDGPUISD::FP_CLASS:
9925     return performClassCombine(N, DCI);
9926   case ISD::FCANONICALIZE:
9927     return performFCanonicalizeCombine(N, DCI);
9928   case AMDGPUISD::RCP:
9929     return performRcpCombine(N, DCI);
9930   case AMDGPUISD::FRACT:
9931   case AMDGPUISD::RSQ:
9932   case AMDGPUISD::RCP_LEGACY:
9933   case AMDGPUISD::RSQ_LEGACY:
9934   case AMDGPUISD::RCP_IFLAG:
9935   case AMDGPUISD::RSQ_CLAMP:
9936   case AMDGPUISD::LDEXP: {
9937     SDValue Src = N->getOperand(0);
9938     if (Src.isUndef())
9939       return Src;
9940     break;
9941   }
9942   case ISD::SINT_TO_FP:
9943   case ISD::UINT_TO_FP:
9944     return performUCharToFloatCombine(N, DCI);
9945   case AMDGPUISD::CVT_F32_UBYTE0:
9946   case AMDGPUISD::CVT_F32_UBYTE1:
9947   case AMDGPUISD::CVT_F32_UBYTE2:
9948   case AMDGPUISD::CVT_F32_UBYTE3:
9949     return performCvtF32UByteNCombine(N, DCI);
9950   case AMDGPUISD::FMED3:
9951     return performFMed3Combine(N, DCI);
9952   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9953     return performCvtPkRTZCombine(N, DCI);
9954   case AMDGPUISD::CLAMP:
9955     return performClampCombine(N, DCI);
9956   case ISD::SCALAR_TO_VECTOR: {
9957     SelectionDAG &DAG = DCI.DAG;
9958     EVT VT = N->getValueType(0);
9959 
9960     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
9961     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
9962       SDLoc SL(N);
9963       SDValue Src = N->getOperand(0);
9964       EVT EltVT = Src.getValueType();
9965       if (EltVT == MVT::f16)
9966         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
9967 
9968       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
9969       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
9970     }
9971 
9972     break;
9973   }
9974   case ISD::EXTRACT_VECTOR_ELT:
9975     return performExtractVectorEltCombine(N, DCI);
9976   case ISD::INSERT_VECTOR_ELT:
9977     return performInsertVectorEltCombine(N, DCI);
9978   }
9979   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9980 }
9981 
9982 /// Helper function for adjustWritemask
9983 static unsigned SubIdx2Lane(unsigned Idx) {
9984   switch (Idx) {
9985   default: return 0;
9986   case AMDGPU::sub0: return 0;
9987   case AMDGPU::sub1: return 1;
9988   case AMDGPU::sub2: return 2;
9989   case AMDGPU::sub3: return 3;
9990   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
9991   }
9992 }
9993 
9994 /// Adjust the writemask of MIMG instructions
9995 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
9996                                           SelectionDAG &DAG) const {
9997   unsigned Opcode = Node->getMachineOpcode();
9998 
9999   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10000   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10001   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10002     return Node; // not implemented for D16
10003 
10004   SDNode *Users[5] = { nullptr };
10005   unsigned Lane = 0;
10006   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10007   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10008   unsigned NewDmask = 0;
10009   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10010   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10011   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10012                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10013   unsigned TFCLane = 0;
10014   bool HasChain = Node->getNumValues() > 1;
10015 
10016   if (OldDmask == 0) {
10017     // These are folded out, but on the chance it happens don't assert.
10018     return Node;
10019   }
10020 
10021   unsigned OldBitsSet = countPopulation(OldDmask);
10022   // Work out which is the TFE/LWE lane if that is enabled.
10023   if (UsesTFC) {
10024     TFCLane = OldBitsSet;
10025   }
10026 
10027   // Try to figure out the used register components
10028   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10029        I != E; ++I) {
10030 
10031     // Don't look at users of the chain.
10032     if (I.getUse().getResNo() != 0)
10033       continue;
10034 
10035     // Abort if we can't understand the usage
10036     if (!I->isMachineOpcode() ||
10037         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10038       return Node;
10039 
10040     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10041     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10042     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10043     // set, etc.
10044     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10045 
10046     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10047     if (UsesTFC && Lane == TFCLane) {
10048       Users[Lane] = *I;
10049     } else {
10050       // Set which texture component corresponds to the lane.
10051       unsigned Comp;
10052       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10053         Comp = countTrailingZeros(Dmask);
10054         Dmask &= ~(1 << Comp);
10055       }
10056 
10057       // Abort if we have more than one user per component.
10058       if (Users[Lane])
10059         return Node;
10060 
10061       Users[Lane] = *I;
10062       NewDmask |= 1 << Comp;
10063     }
10064   }
10065 
10066   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10067   bool NoChannels = !NewDmask;
10068   if (NoChannels) {
10069     if (!UsesTFC) {
10070       // No uses of the result and not using TFC. Then do nothing.
10071       return Node;
10072     }
10073     // If the original dmask has one channel - then nothing to do
10074     if (OldBitsSet == 1)
10075       return Node;
10076     // Use an arbitrary dmask - required for the instruction to work
10077     NewDmask = 1;
10078   }
10079   // Abort if there's no change
10080   if (NewDmask == OldDmask)
10081     return Node;
10082 
10083   unsigned BitsSet = countPopulation(NewDmask);
10084 
10085   // Check for TFE or LWE - increase the number of channels by one to account
10086   // for the extra return value
10087   // This will need adjustment for D16 if this is also included in
10088   // adjustWriteMask (this function) but at present D16 are excluded.
10089   unsigned NewChannels = BitsSet + UsesTFC;
10090 
10091   int NewOpcode =
10092       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10093   assert(NewOpcode != -1 &&
10094          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10095          "failed to find equivalent MIMG op");
10096 
10097   // Adjust the writemask in the node
10098   SmallVector<SDValue, 12> Ops;
10099   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10100   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10101   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10102 
10103   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10104 
10105   MVT ResultVT = NewChannels == 1 ?
10106     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10107                            NewChannels == 5 ? 8 : NewChannels);
10108   SDVTList NewVTList = HasChain ?
10109     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10110 
10111 
10112   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10113                                               NewVTList, Ops);
10114 
10115   if (HasChain) {
10116     // Update chain.
10117     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10118     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10119   }
10120 
10121   if (NewChannels == 1) {
10122     assert(Node->hasNUsesOfValue(1, 0));
10123     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10124                                       SDLoc(Node), Users[Lane]->getValueType(0),
10125                                       SDValue(NewNode, 0));
10126     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10127     return nullptr;
10128   }
10129 
10130   // Update the users of the node with the new indices
10131   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10132     SDNode *User = Users[i];
10133     if (!User) {
10134       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10135       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10136       if (i || !NoChannels)
10137         continue;
10138     } else {
10139       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10140       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10141     }
10142 
10143     switch (Idx) {
10144     default: break;
10145     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10146     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10147     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10148     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10149     }
10150   }
10151 
10152   DAG.RemoveDeadNode(Node);
10153   return nullptr;
10154 }
10155 
10156 static bool isFrameIndexOp(SDValue Op) {
10157   if (Op.getOpcode() == ISD::AssertZext)
10158     Op = Op.getOperand(0);
10159 
10160   return isa<FrameIndexSDNode>(Op);
10161 }
10162 
10163 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10164 /// with frame index operands.
10165 /// LLVM assumes that inputs are to these instructions are registers.
10166 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10167                                                         SelectionDAG &DAG) const {
10168   if (Node->getOpcode() == ISD::CopyToReg) {
10169     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10170     SDValue SrcVal = Node->getOperand(2);
10171 
10172     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10173     // to try understanding copies to physical registers.
10174     if (SrcVal.getValueType() == MVT::i1 &&
10175         Register::isPhysicalRegister(DestReg->getReg())) {
10176       SDLoc SL(Node);
10177       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10178       SDValue VReg = DAG.getRegister(
10179         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10180 
10181       SDNode *Glued = Node->getGluedNode();
10182       SDValue ToVReg
10183         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10184                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10185       SDValue ToResultReg
10186         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10187                            VReg, ToVReg.getValue(1));
10188       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10189       DAG.RemoveDeadNode(Node);
10190       return ToResultReg.getNode();
10191     }
10192   }
10193 
10194   SmallVector<SDValue, 8> Ops;
10195   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10196     if (!isFrameIndexOp(Node->getOperand(i))) {
10197       Ops.push_back(Node->getOperand(i));
10198       continue;
10199     }
10200 
10201     SDLoc DL(Node);
10202     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10203                                      Node->getOperand(i).getValueType(),
10204                                      Node->getOperand(i)), 0));
10205   }
10206 
10207   return DAG.UpdateNodeOperands(Node, Ops);
10208 }
10209 
10210 /// Fold the instructions after selecting them.
10211 /// Returns null if users were already updated.
10212 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10213                                           SelectionDAG &DAG) const {
10214   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10215   unsigned Opcode = Node->getMachineOpcode();
10216 
10217   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10218       !TII->isGather4(Opcode)) {
10219     return adjustWritemask(Node, DAG);
10220   }
10221 
10222   if (Opcode == AMDGPU::INSERT_SUBREG ||
10223       Opcode == AMDGPU::REG_SEQUENCE) {
10224     legalizeTargetIndependentNode(Node, DAG);
10225     return Node;
10226   }
10227 
10228   switch (Opcode) {
10229   case AMDGPU::V_DIV_SCALE_F32:
10230   case AMDGPU::V_DIV_SCALE_F64: {
10231     // Satisfy the operand register constraint when one of the inputs is
10232     // undefined. Ordinarily each undef value will have its own implicit_def of
10233     // a vreg, so force these to use a single register.
10234     SDValue Src0 = Node->getOperand(0);
10235     SDValue Src1 = Node->getOperand(1);
10236     SDValue Src2 = Node->getOperand(2);
10237 
10238     if ((Src0.isMachineOpcode() &&
10239          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10240         (Src0 == Src1 || Src0 == Src2))
10241       break;
10242 
10243     MVT VT = Src0.getValueType().getSimpleVT();
10244     const TargetRegisterClass *RC =
10245         getRegClassFor(VT, Src0.getNode()->isDivergent());
10246 
10247     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10248     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10249 
10250     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10251                                       UndefReg, Src0, SDValue());
10252 
10253     // src0 must be the same register as src1 or src2, even if the value is
10254     // undefined, so make sure we don't violate this constraint.
10255     if (Src0.isMachineOpcode() &&
10256         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10257       if (Src1.isMachineOpcode() &&
10258           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10259         Src0 = Src1;
10260       else if (Src2.isMachineOpcode() &&
10261                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10262         Src0 = Src2;
10263       else {
10264         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10265         Src0 = UndefReg;
10266         Src1 = UndefReg;
10267       }
10268     } else
10269       break;
10270 
10271     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10272     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10273       Ops.push_back(Node->getOperand(I));
10274 
10275     Ops.push_back(ImpDef.getValue(1));
10276     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10277   }
10278   default:
10279     break;
10280   }
10281 
10282   return Node;
10283 }
10284 
10285 /// Assign the register class depending on the number of
10286 /// bits set in the writemask
10287 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10288                                                      SDNode *Node) const {
10289   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10290 
10291   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10292 
10293   if (TII->isVOP3(MI.getOpcode())) {
10294     // Make sure constant bus requirements are respected.
10295     TII->legalizeOperandsVOP3(MRI, MI);
10296 
10297     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10298     // This saves a chain-copy of registers and better ballance register
10299     // use between vgpr and agpr as agpr tuples tend to be big.
10300     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10301       unsigned Opc = MI.getOpcode();
10302       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10303       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10304                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10305         if (I == -1)
10306           break;
10307         MachineOperand &Op = MI.getOperand(I);
10308         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10309              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10310             !Register::isVirtualRegister(Op.getReg()) ||
10311             !TRI->isAGPR(MRI, Op.getReg()))
10312           continue;
10313         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10314         if (!Src || !Src->isCopy() ||
10315             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10316           continue;
10317         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10318         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10319         // All uses of agpr64 and agpr32 can also accept vgpr except for
10320         // v_accvgpr_read, but we do not produce agpr reads during selection,
10321         // so no use checks are needed.
10322         MRI.setRegClass(Op.getReg(), NewRC);
10323       }
10324     }
10325 
10326     return;
10327   }
10328 
10329   // Replace unused atomics with the no return version.
10330   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10331   if (NoRetAtomicOp != -1) {
10332     if (!Node->hasAnyUseOfValue(0)) {
10333       MI.setDesc(TII->get(NoRetAtomicOp));
10334       MI.RemoveOperand(0);
10335       return;
10336     }
10337 
10338     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10339     // instruction, because the return type of these instructions is a vec2 of
10340     // the memory type, so it can be tied to the input operand.
10341     // This means these instructions always have a use, so we need to add a
10342     // special case to check if the atomic has only one extract_subreg use,
10343     // which itself has no uses.
10344     if ((Node->hasNUsesOfValue(1, 0) &&
10345          Node->use_begin()->isMachineOpcode() &&
10346          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10347          !Node->use_begin()->hasAnyUseOfValue(0))) {
10348       Register Def = MI.getOperand(0).getReg();
10349 
10350       // Change this into a noret atomic.
10351       MI.setDesc(TII->get(NoRetAtomicOp));
10352       MI.RemoveOperand(0);
10353 
10354       // If we only remove the def operand from the atomic instruction, the
10355       // extract_subreg will be left with a use of a vreg without a def.
10356       // So we need to insert an implicit_def to avoid machine verifier
10357       // errors.
10358       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10359               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10360     }
10361     return;
10362   }
10363 }
10364 
10365 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10366                               uint64_t Val) {
10367   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10368   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10369 }
10370 
10371 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10372                                                 const SDLoc &DL,
10373                                                 SDValue Ptr) const {
10374   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10375 
10376   // Build the half of the subregister with the constants before building the
10377   // full 128-bit register. If we are building multiple resource descriptors,
10378   // this will allow CSEing of the 2-component register.
10379   const SDValue Ops0[] = {
10380     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10381     buildSMovImm32(DAG, DL, 0),
10382     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10383     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10384     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10385   };
10386 
10387   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10388                                                 MVT::v2i32, Ops0), 0);
10389 
10390   // Combine the constants and the pointer.
10391   const SDValue Ops1[] = {
10392     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10393     Ptr,
10394     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10395     SubRegHi,
10396     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10397   };
10398 
10399   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10400 }
10401 
10402 /// Return a resource descriptor with the 'Add TID' bit enabled
10403 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10404 ///        of the resource descriptor) to create an offset, which is added to
10405 ///        the resource pointer.
10406 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10407                                            SDValue Ptr, uint32_t RsrcDword1,
10408                                            uint64_t RsrcDword2And3) const {
10409   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10410   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10411   if (RsrcDword1) {
10412     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10413                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10414                     0);
10415   }
10416 
10417   SDValue DataLo = buildSMovImm32(DAG, DL,
10418                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10419   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10420 
10421   const SDValue Ops[] = {
10422     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10423     PtrLo,
10424     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10425     PtrHi,
10426     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10427     DataLo,
10428     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10429     DataHi,
10430     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10431   };
10432 
10433   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10434 }
10435 
10436 //===----------------------------------------------------------------------===//
10437 //                         SI Inline Assembly Support
10438 //===----------------------------------------------------------------------===//
10439 
10440 std::pair<unsigned, const TargetRegisterClass *>
10441 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10442                                                StringRef Constraint,
10443                                                MVT VT) const {
10444   const TargetRegisterClass *RC = nullptr;
10445   if (Constraint.size() == 1) {
10446     switch (Constraint[0]) {
10447     default:
10448       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10449     case 's':
10450     case 'r':
10451       switch (VT.getSizeInBits()) {
10452       default:
10453         return std::make_pair(0U, nullptr);
10454       case 32:
10455       case 16:
10456         RC = &AMDGPU::SReg_32RegClass;
10457         break;
10458       case 64:
10459         RC = &AMDGPU::SGPR_64RegClass;
10460         break;
10461       case 96:
10462         RC = &AMDGPU::SReg_96RegClass;
10463         break;
10464       case 128:
10465         RC = &AMDGPU::SGPR_128RegClass;
10466         break;
10467       case 160:
10468         RC = &AMDGPU::SReg_160RegClass;
10469         break;
10470       case 256:
10471         RC = &AMDGPU::SReg_256RegClass;
10472         break;
10473       case 512:
10474         RC = &AMDGPU::SReg_512RegClass;
10475         break;
10476       }
10477       break;
10478     case 'v':
10479       switch (VT.getSizeInBits()) {
10480       default:
10481         return std::make_pair(0U, nullptr);
10482       case 32:
10483       case 16:
10484         RC = &AMDGPU::VGPR_32RegClass;
10485         break;
10486       case 64:
10487         RC = &AMDGPU::VReg_64RegClass;
10488         break;
10489       case 96:
10490         RC = &AMDGPU::VReg_96RegClass;
10491         break;
10492       case 128:
10493         RC = &AMDGPU::VReg_128RegClass;
10494         break;
10495       case 160:
10496         RC = &AMDGPU::VReg_160RegClass;
10497         break;
10498       case 256:
10499         RC = &AMDGPU::VReg_256RegClass;
10500         break;
10501       case 512:
10502         RC = &AMDGPU::VReg_512RegClass;
10503         break;
10504       }
10505       break;
10506     case 'a':
10507       if (!Subtarget->hasMAIInsts())
10508         break;
10509       switch (VT.getSizeInBits()) {
10510       default:
10511         return std::make_pair(0U, nullptr);
10512       case 32:
10513       case 16:
10514         RC = &AMDGPU::AGPR_32RegClass;
10515         break;
10516       case 64:
10517         RC = &AMDGPU::AReg_64RegClass;
10518         break;
10519       case 128:
10520         RC = &AMDGPU::AReg_128RegClass;
10521         break;
10522       case 512:
10523         RC = &AMDGPU::AReg_512RegClass;
10524         break;
10525       case 1024:
10526         RC = &AMDGPU::AReg_1024RegClass;
10527         // v32 types are not legal but we support them here.
10528         return std::make_pair(0U, RC);
10529       }
10530       break;
10531     }
10532     // We actually support i128, i16 and f16 as inline parameters
10533     // even if they are not reported as legal
10534     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10535                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10536       return std::make_pair(0U, RC);
10537   }
10538 
10539   if (Constraint.size() > 1) {
10540     if (Constraint[1] == 'v') {
10541       RC = &AMDGPU::VGPR_32RegClass;
10542     } else if (Constraint[1] == 's') {
10543       RC = &AMDGPU::SGPR_32RegClass;
10544     } else if (Constraint[1] == 'a') {
10545       RC = &AMDGPU::AGPR_32RegClass;
10546     }
10547 
10548     if (RC) {
10549       uint32_t Idx;
10550       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10551       if (!Failed && Idx < RC->getNumRegs())
10552         return std::make_pair(RC->getRegister(Idx), RC);
10553     }
10554   }
10555 
10556   // FIXME: Returns VS_32 for physical SGPR constraints
10557   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10558 }
10559 
10560 SITargetLowering::ConstraintType
10561 SITargetLowering::getConstraintType(StringRef Constraint) const {
10562   if (Constraint.size() == 1) {
10563     switch (Constraint[0]) {
10564     default: break;
10565     case 's':
10566     case 'v':
10567     case 'a':
10568       return C_RegisterClass;
10569     }
10570   }
10571   return TargetLowering::getConstraintType(Constraint);
10572 }
10573 
10574 // Figure out which registers should be reserved for stack access. Only after
10575 // the function is legalized do we know all of the non-spill stack objects or if
10576 // calls are present.
10577 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10578   MachineRegisterInfo &MRI = MF.getRegInfo();
10579   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10580   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10581   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10582 
10583   if (Info->isEntryFunction()) {
10584     // Callable functions have fixed registers used for stack access.
10585     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10586   }
10587 
10588   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10589                              Info->getStackPtrOffsetReg()));
10590   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10591     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10592 
10593   // We need to worry about replacing the default register with itself in case
10594   // of MIR testcases missing the MFI.
10595   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10596     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10597 
10598   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10599     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10600 
10601   if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
10602     MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
10603                        Info->getScratchWaveOffsetReg());
10604   }
10605 
10606   Info->limitOccupancy(MF);
10607 
10608   if (ST.isWave32() && !MF.empty()) {
10609     // Add VCC_HI def because many instructions marked as imp-use VCC where
10610     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10611     // having a use of undef.
10612 
10613     const SIInstrInfo *TII = ST.getInstrInfo();
10614     DebugLoc DL;
10615 
10616     MachineBasicBlock &MBB = MF.front();
10617     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10618     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10619 
10620     for (auto &MBB : MF) {
10621       for (auto &MI : MBB) {
10622         TII->fixImplicitOperands(MI);
10623       }
10624     }
10625   }
10626 
10627   TargetLoweringBase::finalizeLowering(MF);
10628 }
10629 
10630 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10631                                                      KnownBits &Known,
10632                                                      const APInt &DemandedElts,
10633                                                      const SelectionDAG &DAG,
10634                                                      unsigned Depth) const {
10635   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10636                                                 DAG, Depth);
10637 
10638   // Set the high bits to zero based on the maximum allowed scratch size per
10639   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10640   // calculation won't overflow, so assume the sign bit is never set.
10641   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10642 }
10643 
10644 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10645   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10646   const Align CacheLineAlign = Align(64);
10647 
10648   // Pre-GFX10 target did not benefit from loop alignment
10649   if (!ML || DisableLoopAlignment ||
10650       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10651       getSubtarget()->hasInstFwdPrefetchBug())
10652     return PrefAlign;
10653 
10654   // On GFX10 I$ is 4 x 64 bytes cache lines.
10655   // By default prefetcher keeps one cache line behind and reads two ahead.
10656   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10657   // behind and one ahead.
10658   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10659   // If loop fits 64 bytes it always spans no more than two cache lines and
10660   // does not need an alignment.
10661   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10662   // Else if loop is less or equal 192 bytes we need two lines behind.
10663 
10664   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10665   const MachineBasicBlock *Header = ML->getHeader();
10666   if (Header->getAlignment() != PrefAlign)
10667     return Header->getAlignment(); // Already processed.
10668 
10669   unsigned LoopSize = 0;
10670   for (const MachineBasicBlock *MBB : ML->blocks()) {
10671     // If inner loop block is aligned assume in average half of the alignment
10672     // size to be added as nops.
10673     if (MBB != Header)
10674       LoopSize += MBB->getAlignment().value() / 2;
10675 
10676     for (const MachineInstr &MI : *MBB) {
10677       LoopSize += TII->getInstSizeInBytes(MI);
10678       if (LoopSize > 192)
10679         return PrefAlign;
10680     }
10681   }
10682 
10683   if (LoopSize <= 64)
10684     return PrefAlign;
10685 
10686   if (LoopSize <= 128)
10687     return CacheLineAlign;
10688 
10689   // If any of parent loops is surrounded by prefetch instructions do not
10690   // insert new for inner loop, which would reset parent's settings.
10691   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10692     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10693       auto I = Exit->getFirstNonDebugInstr();
10694       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10695         return CacheLineAlign;
10696     }
10697   }
10698 
10699   MachineBasicBlock *Pre = ML->getLoopPreheader();
10700   MachineBasicBlock *Exit = ML->getExitBlock();
10701 
10702   if (Pre && Exit) {
10703     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10704             TII->get(AMDGPU::S_INST_PREFETCH))
10705       .addImm(1); // prefetch 2 lines behind PC
10706 
10707     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10708             TII->get(AMDGPU::S_INST_PREFETCH))
10709       .addImm(2); // prefetch 1 line behind PC
10710   }
10711 
10712   return CacheLineAlign;
10713 }
10714 
10715 LLVM_ATTRIBUTE_UNUSED
10716 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10717   assert(N->getOpcode() == ISD::CopyFromReg);
10718   do {
10719     // Follow the chain until we find an INLINEASM node.
10720     N = N->getOperand(0).getNode();
10721     if (N->getOpcode() == ISD::INLINEASM ||
10722         N->getOpcode() == ISD::INLINEASM_BR)
10723       return true;
10724   } while (N->getOpcode() == ISD::CopyFromReg);
10725   return false;
10726 }
10727 
10728 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10729   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10730 {
10731   switch (N->getOpcode()) {
10732     case ISD::CopyFromReg:
10733     {
10734       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10735       const MachineFunction * MF = FLI->MF;
10736       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10737       const MachineRegisterInfo &MRI = MF->getRegInfo();
10738       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10739       unsigned Reg = R->getReg();
10740       if (Register::isPhysicalRegister(Reg))
10741         return !TRI.isSGPRReg(MRI, Reg);
10742 
10743       if (MRI.isLiveIn(Reg)) {
10744         // workitem.id.x workitem.id.y workitem.id.z
10745         // Any VGPR formal argument is also considered divergent
10746         if (!TRI.isSGPRReg(MRI, Reg))
10747           return true;
10748         // Formal arguments of non-entry functions
10749         // are conservatively considered divergent
10750         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10751           return true;
10752         return false;
10753       }
10754       const Value *V = FLI->getValueFromVirtualReg(Reg);
10755       if (V)
10756         return KDA->isDivergent(V);
10757       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10758       return !TRI.isSGPRReg(MRI, Reg);
10759     }
10760     break;
10761     case ISD::LOAD: {
10762       const LoadSDNode *L = cast<LoadSDNode>(N);
10763       unsigned AS = L->getAddressSpace();
10764       // A flat load may access private memory.
10765       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10766     } break;
10767     case ISD::CALLSEQ_END:
10768     return true;
10769     break;
10770     case ISD::INTRINSIC_WO_CHAIN:
10771     {
10772 
10773     }
10774       return AMDGPU::isIntrinsicSourceOfDivergence(
10775       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10776     case ISD::INTRINSIC_W_CHAIN:
10777       return AMDGPU::isIntrinsicSourceOfDivergence(
10778       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10779   }
10780   return false;
10781 }
10782 
10783 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
10784                                                EVT VT) const {
10785   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10786   case MVT::f32:
10787     return hasFP32Denormals(DAG.getMachineFunction());
10788   case MVT::f64:
10789   case MVT::f16:
10790     return hasFP64FP16Denormals(DAG.getMachineFunction());
10791   default:
10792     return false;
10793   }
10794 }
10795 
10796 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10797                                                     const SelectionDAG &DAG,
10798                                                     bool SNaN,
10799                                                     unsigned Depth) const {
10800   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10801     const MachineFunction &MF = DAG.getMachineFunction();
10802     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10803 
10804     if (Info->getMode().DX10Clamp)
10805       return true; // Clamped to 0.
10806     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10807   }
10808 
10809   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10810                                                             SNaN, Depth);
10811 }
10812 
10813 TargetLowering::AtomicExpansionKind
10814 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10815   switch (RMW->getOperation()) {
10816   case AtomicRMWInst::FAdd: {
10817     Type *Ty = RMW->getType();
10818 
10819     // We don't have a way to support 16-bit atomics now, so just leave them
10820     // as-is.
10821     if (Ty->isHalfTy())
10822       return AtomicExpansionKind::None;
10823 
10824     if (!Ty->isFloatTy())
10825       return AtomicExpansionKind::CmpXChg;
10826 
10827     // TODO: Do have these for flat. Older targets also had them for buffers.
10828     unsigned AS = RMW->getPointerAddressSpace();
10829 
10830     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
10831       return RMW->use_empty() ? AtomicExpansionKind::None :
10832                                 AtomicExpansionKind::CmpXChg;
10833     }
10834 
10835     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10836       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10837   }
10838   default:
10839     break;
10840   }
10841 
10842   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10843 }
10844 
10845 const TargetRegisterClass *
10846 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
10847   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
10848   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10849   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
10850     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
10851                                                : &AMDGPU::SReg_32RegClass;
10852   if (!TRI->isSGPRClass(RC) && !isDivergent)
10853     return TRI->getEquivalentSGPRClass(RC);
10854   else if (TRI->isSGPRClass(RC) && isDivergent)
10855     return TRI->getEquivalentVGPRClass(RC);
10856 
10857   return RC;
10858 }
10859 
10860 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
10861                       unsigned WaveSize) {
10862   // FIXME: We asssume we never cast the mask results of a control flow
10863   // intrinsic.
10864   // Early exit if the type won't be consistent as a compile time hack.
10865   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
10866   if (!IT || IT->getBitWidth() != WaveSize)
10867     return false;
10868 
10869   if (!isa<Instruction>(V))
10870     return false;
10871   if (!Visited.insert(V).second)
10872     return false;
10873   bool Result = false;
10874   for (auto U : V->users()) {
10875     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
10876       if (V == U->getOperand(1)) {
10877         switch (Intrinsic->getIntrinsicID()) {
10878         default:
10879           Result = false;
10880           break;
10881         case Intrinsic::amdgcn_if_break:
10882         case Intrinsic::amdgcn_if:
10883         case Intrinsic::amdgcn_else:
10884           Result = true;
10885           break;
10886         }
10887       }
10888       if (V == U->getOperand(0)) {
10889         switch (Intrinsic->getIntrinsicID()) {
10890         default:
10891           Result = false;
10892           break;
10893         case Intrinsic::amdgcn_end_cf:
10894         case Intrinsic::amdgcn_loop:
10895           Result = true;
10896           break;
10897         }
10898       }
10899     } else {
10900       Result = hasCFUser(U, Visited, WaveSize);
10901     }
10902     if (Result)
10903       break;
10904   }
10905   return Result;
10906 }
10907 
10908 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
10909                                                const Value *V) const {
10910   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
10911     switch (Intrinsic->getIntrinsicID()) {
10912     default:
10913       return false;
10914     case Intrinsic::amdgcn_if_break:
10915       return true;
10916     }
10917   }
10918   if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) {
10919     if (const IntrinsicInst *Intrinsic =
10920             dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) {
10921       switch (Intrinsic->getIntrinsicID()) {
10922       default:
10923         return false;
10924       case Intrinsic::amdgcn_if:
10925       case Intrinsic::amdgcn_else: {
10926         ArrayRef<unsigned> Indices = ExtValue->getIndices();
10927         if (Indices.size() == 1 && Indices[0] == 1) {
10928           return true;
10929         }
10930       }
10931       }
10932     }
10933   }
10934   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
10935     if (isa<InlineAsm>(CI->getCalledValue())) {
10936       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
10937       ImmutableCallSite CS(CI);
10938       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
10939           MF.getDataLayout(), Subtarget->getRegisterInfo(), CS);
10940       for (auto &TC : TargetConstraints) {
10941         if (TC.Type == InlineAsm::isOutput) {
10942           ComputeConstraintToUse(TC, SDValue());
10943           unsigned AssignedReg;
10944           const TargetRegisterClass *RC;
10945           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
10946               SIRI, TC.ConstraintCode, TC.ConstraintVT);
10947           if (RC) {
10948             MachineRegisterInfo &MRI = MF.getRegInfo();
10949             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
10950               return true;
10951             else if (SIRI->isSGPRClass(RC))
10952               return true;
10953           }
10954         }
10955       }
10956     }
10957   }
10958   SmallPtrSet<const Value *, 16> Visited;
10959   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
10960 }
10961