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 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "Utils/AMDGPUBaseInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/DAGCombine.h"
37 #include "llvm/CodeGen/FunctionLoweringInfo.h"
38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/SelectionDAG.h"
51 #include "llvm/CodeGen/SelectionDAGNodes.h"
52 #include "llvm/CodeGen/TargetCallingConv.h"
53 #include "llvm/CodeGen/TargetRegisterInfo.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/DiagnosticInfo.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/GlobalValue.h"
62 #include "llvm/IR/InstrTypes.h"
63 #include "llvm/IR/Instruction.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/Type.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/KnownBits.h"
73 #include "llvm/Support/MachineValueType.h"
74 #include "llvm/Support/MathExtras.h"
75 #include "llvm/Target/TargetOptions.h"
76 #include <cassert>
77 #include <cmath>
78 #include <cstdint>
79 #include <iterator>
80 #include <tuple>
81 #include <utility>
82 #include <vector>
83 
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "si-lower"
87 
88 STATISTIC(NumTailCalls, "Number of tail calls");
89 
90 static cl::opt<bool> DisableLoopAlignment(
91   "amdgpu-disable-loop-alignment",
92   cl::desc("Do not align and prefetch loops"),
93   cl::init(false));
94 
95 static cl::opt<bool> VGPRReserveforSGPRSpill(
96     "amdgpu-reserve-vgpr-for-sgpr-spill",
97     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
98 
99 static cl::opt<bool> UseDivergentRegisterIndexing(
100   "amdgpu-use-divergent-register-indexing",
101   cl::Hidden,
102   cl::desc("Use indirect register addressing for divergent indexes"),
103   cl::init(false));
104 
105 static bool hasFP32Denormals(const MachineFunction &MF) {
106   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
107   return Info->getMode().allFP32Denormals();
108 }
109 
110 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
111   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
112   return Info->getMode().allFP64FP16Denormals();
113 }
114 
115 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
116   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
117   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
118     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
119       return AMDGPU::SGPR0 + Reg;
120     }
121   }
122   llvm_unreachable("Cannot allocate sgpr");
123 }
124 
125 SITargetLowering::SITargetLowering(const TargetMachine &TM,
126                                    const GCNSubtarget &STI)
127     : AMDGPUTargetLowering(TM, STI),
128       Subtarget(&STI) {
129   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
130   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
131 
132   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
133   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
134 
135   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
136   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
137   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
138 
139   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
140   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
141 
142   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
143   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
144 
145   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
146   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
147 
148   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
149   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
150 
151   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
152   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
153 
154   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
155   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
156 
157   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
158   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
159 
160   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
161   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
162 
163   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
164   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
165 
166   if (Subtarget->has16BitInsts()) {
167     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
168     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
169 
170     // Unless there are also VOP3P operations, not operations are really legal.
171     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
172     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
173     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
174     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
175   }
176 
177   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
178   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
179 
180   computeRegisterProperties(Subtarget->getRegisterInfo());
181 
182   // The boolean content concept here is too inflexible. Compares only ever
183   // really produce a 1-bit result. Any copy/extend from these will turn into a
184   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
185   // it's what most targets use.
186   setBooleanContents(ZeroOrOneBooleanContent);
187   setBooleanVectorContents(ZeroOrOneBooleanContent);
188 
189   // We need to custom lower vector stores from local memory
190   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
196   setOperationAction(ISD::LOAD, MVT::i1, Custom);
197   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
198 
199   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
204   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
205   setOperationAction(ISD::STORE, MVT::i1, Custom);
206   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
207 
208   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
209   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
210   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
211   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
212   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
213   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
214   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
215   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
216   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
217   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
218   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
219   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
220   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
221   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
222   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
223   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
224 
225   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
227   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
228   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
229   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
230 
231   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
232   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
233 
234   setOperationAction(ISD::SELECT, MVT::i1, Promote);
235   setOperationAction(ISD::SELECT, MVT::i64, Custom);
236   setOperationAction(ISD::SELECT, MVT::f64, Promote);
237   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
238 
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
242   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
243   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
244 
245   setOperationAction(ISD::SETCC, MVT::i1, Promote);
246   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
247   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
248   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
249 
250   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
251   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
252   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
253   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
254   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
255   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
256   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
257   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
258 
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
267 
268   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
269   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
270   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
271   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
272   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
273   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
274 
275   setOperationAction(ISD::UADDO, MVT::i32, Legal);
276   setOperationAction(ISD::USUBO, MVT::i32, Legal);
277 
278   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
279   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
280 
281   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
282   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
283   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
284 
285 #if 0
286   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
287   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
288 #endif
289 
290   // We only support LOAD/STORE and vector manipulation ops for vectors
291   // with > 4 elements.
292   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
293                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
294                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
295                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
296     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
297       switch (Op) {
298       case ISD::LOAD:
299       case ISD::STORE:
300       case ISD::BUILD_VECTOR:
301       case ISD::BITCAST:
302       case ISD::EXTRACT_VECTOR_ELT:
303       case ISD::INSERT_VECTOR_ELT:
304       case ISD::INSERT_SUBVECTOR:
305       case ISD::EXTRACT_SUBVECTOR:
306       case ISD::SCALAR_TO_VECTOR:
307         break;
308       case ISD::CONCAT_VECTORS:
309         setOperationAction(Op, VT, Custom);
310         break;
311       default:
312         setOperationAction(Op, VT, Expand);
313         break;
314       }
315     }
316   }
317 
318   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
319 
320   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
321   // is expanded to avoid having two separate loops in case the index is a VGPR.
322 
323   // Most operations are naturally 32-bit vector operations. We only support
324   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
325   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
326     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
327     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
328 
329     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
330     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
331 
332     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
333     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
334 
335     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
336     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
337   }
338 
339   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
340     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
341     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
344     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
345 
346     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
347     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
348 
349     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
350     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
351   }
352 
353   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
354     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
355     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
358     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
359 
360     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
361     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
362 
363     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
364     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
365   }
366 
367   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
368     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
369     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
372     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
373 
374     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
375     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
376 
377     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
378     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
379   }
380 
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
383   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
384   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
385 
386   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
387   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
388 
389   // Avoid stack access for these.
390   // TODO: Generalize to more vector types.
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
395 
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
400   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
401 
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
403   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
404   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
405 
406   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
407   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
408   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
409   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
410 
411   // Deal with vec3 vector operations when widened to vec4.
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
416 
417   // Deal with vec5 vector operations when widened to vec8.
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
420   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
421   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
422 
423   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
424   // and output demarshalling
425   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
426   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
427 
428   // We can't return success/failure, only the old value,
429   // let LLVM add the comparison
430   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
431   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
432 
433   if (Subtarget->hasFlatAddressSpace()) {
434     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
435     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
436   }
437 
438   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
439 
440   // FIXME: This should be narrowed to i32, but that only happens if i64 is
441   // illegal.
442   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
443   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
444   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
445 
446   // On SI this is s_memtime and s_memrealtime on VI.
447   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
448   setOperationAction(ISD::TRAP, MVT::Other, Custom);
449   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
450 
451   if (Subtarget->has16BitInsts()) {
452     setOperationAction(ISD::FPOW, MVT::f16, Promote);
453     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
454     setOperationAction(ISD::FLOG, MVT::f16, Custom);
455     setOperationAction(ISD::FEXP, MVT::f16, Custom);
456     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
457   }
458 
459   if (Subtarget->hasMadMacF32Insts())
460     setOperationAction(ISD::FMAD, MVT::f32, Legal);
461 
462   if (!Subtarget->hasBFI()) {
463     // fcopysign can be done in a single instruction with BFI.
464     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
465     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466   }
467 
468   if (!Subtarget->hasBCNT(32))
469     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
470 
471   if (!Subtarget->hasBCNT(64))
472     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
473 
474   if (Subtarget->hasFFBH())
475     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
476 
477   if (Subtarget->hasFFBL())
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
479 
480   // We only really have 32-bit BFE instructions (and 16-bit on VI).
481   //
482   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483   // effort to match them now. We want this to be false for i64 cases when the
484   // extraction isn't restricted to the upper or lower half. Ideally we would
485   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486   // span the midpoint are probably relatively rare, so don't worry about them
487   // for now.
488   if (Subtarget->hasBFE())
489     setHasExtractBitsInsn(true);
490 
491   // Clamp modifier on add/sub
492   if (Subtarget->hasIntClamp()) {
493     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495   }
496 
497   if (Subtarget->hasAddNoCarry()) {
498     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502   }
503 
504   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508 
509 
510   // These are really only legal for ieee_mode functions. We should be avoiding
511   // them for functions that don't have ieee_mode enabled, so just say they are
512   // legal.
513   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517 
518 
519   if (Subtarget->haveRoundOpsF64()) {
520     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522     setOperationAction(ISD::FRINT, MVT::f64, Legal);
523   } else {
524     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526     setOperationAction(ISD::FRINT, MVT::f64, Custom);
527     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528   }
529 
530   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531 
532   setOperationAction(ISD::FSIN, MVT::f32, Custom);
533   setOperationAction(ISD::FCOS, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f64, Custom);
536 
537   if (Subtarget->has16BitInsts()) {
538     setOperationAction(ISD::Constant, MVT::i16, Legal);
539 
540     setOperationAction(ISD::SMIN, MVT::i16, Legal);
541     setOperationAction(ISD::SMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::UMIN, MVT::i16, Legal);
544     setOperationAction(ISD::UMAX, MVT::i16, Legal);
545 
546     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548 
549     setOperationAction(ISD::ROTR, MVT::i16, Expand);
550     setOperationAction(ISD::ROTL, MVT::i16, Expand);
551 
552     setOperationAction(ISD::SDIV, MVT::i16, Promote);
553     setOperationAction(ISD::UDIV, MVT::i16, Promote);
554     setOperationAction(ISD::SREM, MVT::i16, Promote);
555     setOperationAction(ISD::UREM, MVT::i16, Promote);
556     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558 
559     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560 
561     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566 
567     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568 
569     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::LOAD, MVT::i16, Custom);
572 
573     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574 
575     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579 
580     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
581     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
582 
583     // F16 - Constant Actions.
584     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585 
586     // F16 - Load/Store Actions.
587     setOperationAction(ISD::LOAD, MVT::f16, Promote);
588     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589     setOperationAction(ISD::STORE, MVT::f16, Promote);
590     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591 
592     // F16 - VOP1 Actions.
593     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594     setOperationAction(ISD::FCOS, MVT::f16, Custom);
595     setOperationAction(ISD::FSIN, MVT::f16, Custom);
596 
597     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599 
600     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::FROUND, MVT::f16, Custom);
605 
606     // F16 - VOP2 Actions.
607     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609 
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
618       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
619         switch (Op) {
620         case ISD::LOAD:
621         case ISD::STORE:
622         case ISD::BUILD_VECTOR:
623         case ISD::BITCAST:
624         case ISD::EXTRACT_VECTOR_ELT:
625         case ISD::INSERT_VECTOR_ELT:
626         case ISD::INSERT_SUBVECTOR:
627         case ISD::EXTRACT_SUBVECTOR:
628         case ISD::SCALAR_TO_VECTOR:
629           break;
630         case ISD::CONCAT_VECTORS:
631           setOperationAction(Op, VT, Custom);
632           break;
633         default:
634           setOperationAction(Op, VT, Expand);
635           break;
636         }
637       }
638     }
639 
640     // v_perm_b32 can handle either of these.
641     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
644 
645     // XXX - Do these do anything? Vector constants turn into build_vector.
646     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
647     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
648 
649     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
650     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
653     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
654     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
655     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
656 
657     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
658     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
659     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
660     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
661 
662     setOperationAction(ISD::AND, MVT::v2i16, Promote);
663     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
664     setOperationAction(ISD::OR, MVT::v2i16, Promote);
665     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
666     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
667     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
668 
669     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
670     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
671     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
672     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
673 
674     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
675     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
676     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
677     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
678 
679     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
682     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
683 
684     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
686     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
687 
688     if (!Subtarget->hasVOP3PInsts()) {
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
690       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
691     }
692 
693     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
694     // This isn't really legal, but this avoids the legalizer unrolling it (and
695     // allows matching fneg (fabs x) patterns)
696     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
697 
698     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
700     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
701     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
702 
703     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
704     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
705 
706     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
707     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
708   }
709 
710   if (Subtarget->hasVOP3PInsts()) {
711     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
712     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
713     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
716     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
717     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
719     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
720     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
721 
722     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
725     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
726 
727     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
730 
731     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
732     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
733 
734     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
735 
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
737     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
738 
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
740     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
741 
742     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
744     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
745     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
746     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
747     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
748 
749     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
750     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
752     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
753 
754     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
757     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
758 
759     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
761     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
762 
763     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
764     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
765 
766     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
768     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
769 
770     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
772     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
773   }
774 
775   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
776   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
777 
778   if (Subtarget->has16BitInsts()) {
779     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
780     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
781     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
782     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
783   } else {
784     // Legalization hack.
785     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
786     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
787 
788     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
789     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
790   }
791 
792   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
793     setOperationAction(ISD::SELECT, VT, Custom);
794   }
795 
796   setOperationAction(ISD::SMULO, MVT::i64, Custom);
797   setOperationAction(ISD::UMULO, MVT::i64, Custom);
798 
799   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
801   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
802   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
803   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
804   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
805   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
806 
807   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
808   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
809   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
810   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
811   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
812   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
813   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
814   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
815   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
816   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
817   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
818 
819   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
820   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
821   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
822   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
823   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
824   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
825   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
826   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
827   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
828   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
829 
830   setTargetDAGCombine(ISD::ADD);
831   setTargetDAGCombine(ISD::ADDCARRY);
832   setTargetDAGCombine(ISD::SUB);
833   setTargetDAGCombine(ISD::SUBCARRY);
834   setTargetDAGCombine(ISD::FADD);
835   setTargetDAGCombine(ISD::FSUB);
836   setTargetDAGCombine(ISD::FMINNUM);
837   setTargetDAGCombine(ISD::FMAXNUM);
838   setTargetDAGCombine(ISD::FMINNUM_IEEE);
839   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
840   setTargetDAGCombine(ISD::FMA);
841   setTargetDAGCombine(ISD::SMIN);
842   setTargetDAGCombine(ISD::SMAX);
843   setTargetDAGCombine(ISD::UMIN);
844   setTargetDAGCombine(ISD::UMAX);
845   setTargetDAGCombine(ISD::SETCC);
846   setTargetDAGCombine(ISD::AND);
847   setTargetDAGCombine(ISD::OR);
848   setTargetDAGCombine(ISD::XOR);
849   setTargetDAGCombine(ISD::SINT_TO_FP);
850   setTargetDAGCombine(ISD::UINT_TO_FP);
851   setTargetDAGCombine(ISD::FCANONICALIZE);
852   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
853   setTargetDAGCombine(ISD::ZERO_EXTEND);
854   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
855   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
856   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
857 
858   // All memory operations. Some folding on the pointer operand is done to help
859   // matching the constant offsets in the addressing modes.
860   setTargetDAGCombine(ISD::LOAD);
861   setTargetDAGCombine(ISD::STORE);
862   setTargetDAGCombine(ISD::ATOMIC_LOAD);
863   setTargetDAGCombine(ISD::ATOMIC_STORE);
864   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
865   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
866   setTargetDAGCombine(ISD::ATOMIC_SWAP);
867   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
868   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
869   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
870   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
871   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
872   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
873   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
874   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
875   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
876   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
877   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
878   setTargetDAGCombine(ISD::INTRINSIC_VOID);
879   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
880 
881   // FIXME: In other contexts we pretend this is a per-function property.
882   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
883 
884   setSchedulingPreference(Sched::RegPressure);
885 }
886 
887 const GCNSubtarget *SITargetLowering::getSubtarget() const {
888   return Subtarget;
889 }
890 
891 //===----------------------------------------------------------------------===//
892 // TargetLowering queries
893 //===----------------------------------------------------------------------===//
894 
895 // v_mad_mix* support a conversion from f16 to f32.
896 //
897 // There is only one special case when denormals are enabled we don't currently,
898 // where this is OK to use.
899 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
900                                        EVT DestVT, EVT SrcVT) const {
901   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
902           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
903     DestVT.getScalarType() == MVT::f32 &&
904     SrcVT.getScalarType() == MVT::f16 &&
905     // TODO: This probably only requires no input flushing?
906     !hasFP32Denormals(DAG.getMachineFunction());
907 }
908 
909 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
910   // SI has some legal vector types, but no legal vector operations. Say no
911   // shuffles are legal in order to prefer scalarizing some vector operations.
912   return false;
913 }
914 
915 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
916                                                     CallingConv::ID CC,
917                                                     EVT VT) const {
918   if (CC == CallingConv::AMDGPU_KERNEL)
919     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
920 
921   if (VT.isVector()) {
922     EVT ScalarVT = VT.getScalarType();
923     unsigned Size = ScalarVT.getSizeInBits();
924     if (Size == 16) {
925       if (Subtarget->has16BitInsts())
926         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
927       return VT.isInteger() ? MVT::i32 : MVT::f32;
928     }
929 
930     if (Size < 16)
931       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
932     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
933   }
934 
935   if (VT.getSizeInBits() > 32)
936     return MVT::i32;
937 
938   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
939 }
940 
941 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
942                                                          CallingConv::ID CC,
943                                                          EVT VT) const {
944   if (CC == CallingConv::AMDGPU_KERNEL)
945     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
946 
947   if (VT.isVector()) {
948     unsigned NumElts = VT.getVectorNumElements();
949     EVT ScalarVT = VT.getScalarType();
950     unsigned Size = ScalarVT.getSizeInBits();
951 
952     // FIXME: Should probably promote 8-bit vectors to i16.
953     if (Size == 16 && Subtarget->has16BitInsts())
954       return (NumElts + 1) / 2;
955 
956     if (Size <= 32)
957       return NumElts;
958 
959     if (Size > 32)
960       return NumElts * ((Size + 31) / 32);
961   } else if (VT.getSizeInBits() > 32)
962     return (VT.getSizeInBits() + 31) / 32;
963 
964   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
965 }
966 
967 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
968   LLVMContext &Context, CallingConv::ID CC,
969   EVT VT, EVT &IntermediateVT,
970   unsigned &NumIntermediates, MVT &RegisterVT) const {
971   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
972     unsigned NumElts = VT.getVectorNumElements();
973     EVT ScalarVT = VT.getScalarType();
974     unsigned Size = ScalarVT.getSizeInBits();
975     // FIXME: We should fix the ABI to be the same on targets without 16-bit
976     // support, but unless we can properly handle 3-vectors, it will be still be
977     // inconsistent.
978     if (Size == 16 && Subtarget->has16BitInsts()) {
979       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
980       IntermediateVT = RegisterVT;
981       NumIntermediates = (NumElts + 1) / 2;
982       return NumIntermediates;
983     }
984 
985     if (Size == 32) {
986       RegisterVT = ScalarVT.getSimpleVT();
987       IntermediateVT = RegisterVT;
988       NumIntermediates = NumElts;
989       return NumIntermediates;
990     }
991 
992     if (Size < 16 && Subtarget->has16BitInsts()) {
993       // FIXME: Should probably form v2i16 pieces
994       RegisterVT = MVT::i16;
995       IntermediateVT = ScalarVT;
996       NumIntermediates = NumElts;
997       return NumIntermediates;
998     }
999 
1000 
1001     if (Size != 16 && Size <= 32) {
1002       RegisterVT = MVT::i32;
1003       IntermediateVT = ScalarVT;
1004       NumIntermediates = NumElts;
1005       return NumIntermediates;
1006     }
1007 
1008     if (Size > 32) {
1009       RegisterVT = MVT::i32;
1010       IntermediateVT = RegisterVT;
1011       NumIntermediates = NumElts * ((Size + 31) / 32);
1012       return NumIntermediates;
1013     }
1014   }
1015 
1016   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1017     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1018 }
1019 
1020 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1021   assert(DMaskLanes != 0);
1022 
1023   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1024     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1025     return EVT::getVectorVT(Ty->getContext(),
1026                             EVT::getEVT(VT->getElementType()),
1027                             NumElts);
1028   }
1029 
1030   return EVT::getEVT(Ty);
1031 }
1032 
1033 // Peek through TFE struct returns to only use the data size.
1034 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1035   auto *ST = dyn_cast<StructType>(Ty);
1036   if (!ST)
1037     return memVTFromImageData(Ty, DMaskLanes);
1038 
1039   // Some intrinsics return an aggregate type - special case to work out the
1040   // correct memVT.
1041   //
1042   // Only limited forms of aggregate type currently expected.
1043   if (ST->getNumContainedTypes() != 2 ||
1044       !ST->getContainedType(1)->isIntegerTy(32))
1045     return EVT();
1046   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1047 }
1048 
1049 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1050                                           const CallInst &CI,
1051                                           MachineFunction &MF,
1052                                           unsigned IntrID) const {
1053   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1054           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1055     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1056                                                   (Intrinsic::ID)IntrID);
1057     if (Attr.hasFnAttribute(Attribute::ReadNone))
1058       return false;
1059 
1060     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1061 
1062     if (RsrcIntr->IsImage) {
1063       Info.ptrVal = MFI->getImagePSV(
1064         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1065         CI.getArgOperand(RsrcIntr->RsrcArg));
1066       Info.align.reset();
1067     } else {
1068       Info.ptrVal = MFI->getBufferPSV(
1069         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1070         CI.getArgOperand(RsrcIntr->RsrcArg));
1071     }
1072 
1073     Info.flags = MachineMemOperand::MODereferenceable;
1074     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1075       unsigned DMaskLanes = 4;
1076 
1077       if (RsrcIntr->IsImage) {
1078         const AMDGPU::ImageDimIntrinsicInfo *Intr
1079           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1080         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1081           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1082 
1083         if (!BaseOpcode->Gather4) {
1084           // If this isn't a gather, we may have excess loaded elements in the
1085           // IR type. Check the dmask for the real number of elements loaded.
1086           unsigned DMask
1087             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1088           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1089         }
1090 
1091         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1092       } else
1093         Info.memVT = EVT::getEVT(CI.getType());
1094 
1095       // FIXME: What does alignment mean for an image?
1096       Info.opc = ISD::INTRINSIC_W_CHAIN;
1097       Info.flags |= MachineMemOperand::MOLoad;
1098     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1099       Info.opc = ISD::INTRINSIC_VOID;
1100 
1101       Type *DataTy = CI.getArgOperand(0)->getType();
1102       if (RsrcIntr->IsImage) {
1103         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1104         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1105         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1106       } else
1107         Info.memVT = EVT::getEVT(DataTy);
1108 
1109       Info.flags |= MachineMemOperand::MOStore;
1110     } else {
1111       // Atomic
1112       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1113                                             ISD::INTRINSIC_W_CHAIN;
1114       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1115       Info.flags = MachineMemOperand::MOLoad |
1116                    MachineMemOperand::MOStore |
1117                    MachineMemOperand::MODereferenceable;
1118 
1119       // XXX - Should this be volatile without known ordering?
1120       Info.flags |= MachineMemOperand::MOVolatile;
1121     }
1122     return true;
1123   }
1124 
1125   switch (IntrID) {
1126   case Intrinsic::amdgcn_atomic_inc:
1127   case Intrinsic::amdgcn_atomic_dec:
1128   case Intrinsic::amdgcn_ds_ordered_add:
1129   case Intrinsic::amdgcn_ds_ordered_swap:
1130   case Intrinsic::amdgcn_ds_fadd:
1131   case Intrinsic::amdgcn_ds_fmin:
1132   case Intrinsic::amdgcn_ds_fmax: {
1133     Info.opc = ISD::INTRINSIC_W_CHAIN;
1134     Info.memVT = MVT::getVT(CI.getType());
1135     Info.ptrVal = CI.getOperand(0);
1136     Info.align.reset();
1137     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1138 
1139     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1140     if (!Vol->isZero())
1141       Info.flags |= MachineMemOperand::MOVolatile;
1142 
1143     return true;
1144   }
1145   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1146     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1147 
1148     Info.opc = ISD::INTRINSIC_W_CHAIN;
1149     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1150     Info.ptrVal = MFI->getBufferPSV(
1151       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1152       CI.getArgOperand(1));
1153     Info.align.reset();
1154     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1155 
1156     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1157     if (!Vol || !Vol->isZero())
1158       Info.flags |= MachineMemOperand::MOVolatile;
1159 
1160     return true;
1161   }
1162   case Intrinsic::amdgcn_ds_append:
1163   case Intrinsic::amdgcn_ds_consume: {
1164     Info.opc = ISD::INTRINSIC_W_CHAIN;
1165     Info.memVT = MVT::getVT(CI.getType());
1166     Info.ptrVal = CI.getOperand(0);
1167     Info.align.reset();
1168     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1169 
1170     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1171     if (!Vol->isZero())
1172       Info.flags |= MachineMemOperand::MOVolatile;
1173 
1174     return true;
1175   }
1176   case Intrinsic::amdgcn_global_atomic_csub: {
1177     Info.opc = ISD::INTRINSIC_W_CHAIN;
1178     Info.memVT = MVT::getVT(CI.getType());
1179     Info.ptrVal = CI.getOperand(0);
1180     Info.align.reset();
1181     Info.flags = MachineMemOperand::MOLoad |
1182                  MachineMemOperand::MOStore |
1183                  MachineMemOperand::MOVolatile;
1184     return true;
1185   }
1186   case Intrinsic::amdgcn_global_atomic_fadd: {
1187     Info.opc = ISD::INTRINSIC_W_CHAIN;
1188     Info.memVT = MVT::getVT(CI.getType());
1189     Info.ptrVal = CI.getOperand(0);
1190     Info.align.reset();
1191     Info.flags = MachineMemOperand::MOLoad |
1192                  MachineMemOperand::MOStore |
1193                  MachineMemOperand::MODereferenceable |
1194                  MachineMemOperand::MOVolatile;
1195     return true;
1196   }
1197   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1198     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1199     Info.opc = ISD::INTRINSIC_W_CHAIN;
1200     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1201     Info.ptrVal = MFI->getImagePSV(
1202         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5));
1203     Info.align.reset();
1204     Info.flags = MachineMemOperand::MOLoad |
1205                  MachineMemOperand::MODereferenceable;
1206     return true;
1207   }
1208   case Intrinsic::amdgcn_ds_gws_init:
1209   case Intrinsic::amdgcn_ds_gws_barrier:
1210   case Intrinsic::amdgcn_ds_gws_sema_v:
1211   case Intrinsic::amdgcn_ds_gws_sema_br:
1212   case Intrinsic::amdgcn_ds_gws_sema_p:
1213   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1214     Info.opc = ISD::INTRINSIC_VOID;
1215 
1216     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1217     Info.ptrVal =
1218         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1219 
1220     // This is an abstract access, but we need to specify a type and size.
1221     Info.memVT = MVT::i32;
1222     Info.size = 4;
1223     Info.align = Align(4);
1224 
1225     Info.flags = MachineMemOperand::MOStore;
1226     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1227       Info.flags = MachineMemOperand::MOLoad;
1228     return true;
1229   }
1230   default:
1231     return false;
1232   }
1233 }
1234 
1235 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1236                                             SmallVectorImpl<Value*> &Ops,
1237                                             Type *&AccessTy) const {
1238   switch (II->getIntrinsicID()) {
1239   case Intrinsic::amdgcn_atomic_inc:
1240   case Intrinsic::amdgcn_atomic_dec:
1241   case Intrinsic::amdgcn_ds_ordered_add:
1242   case Intrinsic::amdgcn_ds_ordered_swap:
1243   case Intrinsic::amdgcn_ds_append:
1244   case Intrinsic::amdgcn_ds_consume:
1245   case Intrinsic::amdgcn_ds_fadd:
1246   case Intrinsic::amdgcn_ds_fmin:
1247   case Intrinsic::amdgcn_ds_fmax:
1248   case Intrinsic::amdgcn_global_atomic_fadd:
1249   case Intrinsic::amdgcn_global_atomic_csub: {
1250     Value *Ptr = II->getArgOperand(0);
1251     AccessTy = II->getType();
1252     Ops.push_back(Ptr);
1253     return true;
1254   }
1255   default:
1256     return false;
1257   }
1258 }
1259 
1260 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1261   if (!Subtarget->hasFlatInstOffsets()) {
1262     // Flat instructions do not have offsets, and only have the register
1263     // address.
1264     return AM.BaseOffs == 0 && AM.Scale == 0;
1265   }
1266 
1267   return AM.Scale == 0 &&
1268          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1269                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1270                                   /*Signed=*/false));
1271 }
1272 
1273 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1274   if (Subtarget->hasFlatGlobalInsts())
1275     return AM.Scale == 0 &&
1276            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1277                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1278                                     /*Signed=*/true));
1279 
1280   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1281       // Assume the we will use FLAT for all global memory accesses
1282       // on VI.
1283       // FIXME: This assumption is currently wrong.  On VI we still use
1284       // MUBUF instructions for the r + i addressing mode.  As currently
1285       // implemented, the MUBUF instructions only work on buffer < 4GB.
1286       // It may be possible to support > 4GB buffers with MUBUF instructions,
1287       // by setting the stride value in the resource descriptor which would
1288       // increase the size limit to (stride * 4GB).  However, this is risky,
1289       // because it has never been validated.
1290     return isLegalFlatAddressingMode(AM);
1291   }
1292 
1293   return isLegalMUBUFAddressingMode(AM);
1294 }
1295 
1296 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1297   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1298   // additionally can do r + r + i with addr64. 32-bit has more addressing
1299   // mode options. Depending on the resource constant, it can also do
1300   // (i64 r0) + (i32 r1) * (i14 i).
1301   //
1302   // Private arrays end up using a scratch buffer most of the time, so also
1303   // assume those use MUBUF instructions. Scratch loads / stores are currently
1304   // implemented as mubuf instructions with offen bit set, so slightly
1305   // different than the normal addr64.
1306   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1307     return false;
1308 
1309   // FIXME: Since we can split immediate into soffset and immediate offset,
1310   // would it make sense to allow any immediate?
1311 
1312   switch (AM.Scale) {
1313   case 0: // r + i or just i, depending on HasBaseReg.
1314     return true;
1315   case 1:
1316     return true; // We have r + r or r + i.
1317   case 2:
1318     if (AM.HasBaseReg) {
1319       // Reject 2 * r + r.
1320       return false;
1321     }
1322 
1323     // Allow 2 * r as r + r
1324     // Or  2 * r + i is allowed as r + r + i.
1325     return true;
1326   default: // Don't allow n * r
1327     return false;
1328   }
1329 }
1330 
1331 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1332                                              const AddrMode &AM, Type *Ty,
1333                                              unsigned AS, Instruction *I) const {
1334   // No global is ever allowed as a base.
1335   if (AM.BaseGV)
1336     return false;
1337 
1338   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1339     return isLegalGlobalAddressingMode(AM);
1340 
1341   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1342       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1343       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1344     // If the offset isn't a multiple of 4, it probably isn't going to be
1345     // correctly aligned.
1346     // FIXME: Can we get the real alignment here?
1347     if (AM.BaseOffs % 4 != 0)
1348       return isLegalMUBUFAddressingMode(AM);
1349 
1350     // There are no SMRD extloads, so if we have to do a small type access we
1351     // will use a MUBUF load.
1352     // FIXME?: We also need to do this if unaligned, but we don't know the
1353     // alignment here.
1354     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1355       return isLegalGlobalAddressingMode(AM);
1356 
1357     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1358       // SMRD instructions have an 8-bit, dword offset on SI.
1359       if (!isUInt<8>(AM.BaseOffs / 4))
1360         return false;
1361     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1362       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1363       // in 8-bits, it can use a smaller encoding.
1364       if (!isUInt<32>(AM.BaseOffs / 4))
1365         return false;
1366     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1367       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1368       if (!isUInt<20>(AM.BaseOffs))
1369         return false;
1370     } else
1371       llvm_unreachable("unhandled generation");
1372 
1373     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1374       return true;
1375 
1376     if (AM.Scale == 1 && AM.HasBaseReg)
1377       return true;
1378 
1379     return false;
1380 
1381   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1382     return isLegalMUBUFAddressingMode(AM);
1383   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1384              AS == AMDGPUAS::REGION_ADDRESS) {
1385     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1386     // field.
1387     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1388     // an 8-bit dword offset but we don't know the alignment here.
1389     if (!isUInt<16>(AM.BaseOffs))
1390       return false;
1391 
1392     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1393       return true;
1394 
1395     if (AM.Scale == 1 && AM.HasBaseReg)
1396       return true;
1397 
1398     return false;
1399   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1400              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1401     // For an unknown address space, this usually means that this is for some
1402     // reason being used for pure arithmetic, and not based on some addressing
1403     // computation. We don't have instructions that compute pointers with any
1404     // addressing modes, so treat them as having no offset like flat
1405     // instructions.
1406     return isLegalFlatAddressingMode(AM);
1407   }
1408 
1409   // Assume a user alias of global for unknown address spaces.
1410   return isLegalGlobalAddressingMode(AM);
1411 }
1412 
1413 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1414                                         const SelectionDAG &DAG) const {
1415   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1416     return (MemVT.getSizeInBits() <= 4 * 32);
1417   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1418     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1419     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1420   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1421     return (MemVT.getSizeInBits() <= 2 * 32);
1422   }
1423   return true;
1424 }
1425 
1426 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1427     unsigned Size, unsigned AddrSpace, Align Alignment,
1428     MachineMemOperand::Flags Flags, bool *IsFast) const {
1429   if (IsFast)
1430     *IsFast = false;
1431 
1432   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1433       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1434     // Check if alignment requirements for ds_read/write instructions are
1435     // disabled.
1436     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1437         !Subtarget->hasLDSMisalignedBug()) {
1438       if (IsFast)
1439         *IsFast = Alignment != Align(2);
1440       return true;
1441     }
1442 
1443     if (Size == 64) {
1444       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1445       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1446       // with adjacent offsets.
1447       bool AlignedBy4 = Alignment >= Align(4);
1448       if (IsFast)
1449         *IsFast = AlignedBy4;
1450 
1451       return AlignedBy4;
1452     }
1453     if (Size == 96) {
1454       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1455       bool Aligned = Alignment >= Align(16);
1456       if (IsFast)
1457         *IsFast = Aligned;
1458 
1459       return Aligned;
1460     }
1461     if (Size == 128) {
1462       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1463       // can do a 8 byte aligned, 16 byte access in a single operation using
1464       // ds_read2/write2_b64.
1465       bool Aligned = Alignment >= Align(8);
1466       if (IsFast)
1467         *IsFast = Aligned;
1468 
1469       return Aligned;
1470     }
1471   }
1472 
1473   // FIXME: We have to be conservative here and assume that flat operations
1474   // will access scratch.  If we had access to the IR function, then we
1475   // could determine if any private memory was used in the function.
1476   if (!Subtarget->hasUnalignedScratchAccess() &&
1477       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1478        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1479     bool AlignedBy4 = Alignment >= Align(4);
1480     if (IsFast)
1481       *IsFast = AlignedBy4;
1482 
1483     return AlignedBy4;
1484   }
1485 
1486   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1487       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1488         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1489     // If we have an uniform constant load, it still requires using a slow
1490     // buffer instruction if unaligned.
1491     if (IsFast) {
1492       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1493       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1494       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1495                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1496         Alignment >= Align(4) : Alignment != Align(2);
1497     }
1498 
1499     return true;
1500   }
1501 
1502   // Smaller than dword value must be aligned.
1503   if (Size < 32)
1504     return false;
1505 
1506   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1507   // byte-address are ignored, thus forcing Dword alignment.
1508   // This applies to private, global, and constant memory.
1509   if (IsFast)
1510     *IsFast = true;
1511 
1512   return Size >= 32 && Alignment >= Align(4);
1513 }
1514 
1515 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1516     EVT VT, unsigned AddrSpace, unsigned Alignment,
1517     MachineMemOperand::Flags Flags, bool *IsFast) const {
1518   if (IsFast)
1519     *IsFast = false;
1520 
1521   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1522   // which isn't a simple VT.
1523   // Until MVT is extended to handle this, simply check for the size and
1524   // rely on the condition below: allow accesses if the size is a multiple of 4.
1525   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1526                            VT.getStoreSize() > 16)) {
1527     return false;
1528   }
1529 
1530   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1531                                             Align(Alignment), Flags, IsFast);
1532 }
1533 
1534 EVT SITargetLowering::getOptimalMemOpType(
1535     const MemOp &Op, const AttributeList &FuncAttributes) const {
1536   // FIXME: Should account for address space here.
1537 
1538   // The default fallback uses the private pointer size as a guess for a type to
1539   // use. Make sure we switch these to 64-bit accesses.
1540 
1541   if (Op.size() >= 16 &&
1542       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1543     return MVT::v4i32;
1544 
1545   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1546     return MVT::v2i32;
1547 
1548   // Use the default.
1549   return MVT::Other;
1550 }
1551 
1552 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1553   const MemSDNode *MemNode = cast<MemSDNode>(N);
1554   const Value *Ptr = MemNode->getMemOperand()->getValue();
1555   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1556   return I && I->getMetadata("amdgpu.noclobber");
1557 }
1558 
1559 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1560                                            unsigned DestAS) const {
1561   // Flat -> private/local is a simple truncate.
1562   // Flat -> global is no-op
1563   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1564     return true;
1565 
1566   const GCNTargetMachine &TM =
1567       static_cast<const GCNTargetMachine &>(getTargetMachine());
1568   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1569 }
1570 
1571 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1572   const MemSDNode *MemNode = cast<MemSDNode>(N);
1573 
1574   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1575 }
1576 
1577 TargetLoweringBase::LegalizeTypeAction
1578 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1579   int NumElts = VT.getVectorNumElements();
1580   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1581     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1582   return TargetLoweringBase::getPreferredVectorAction(VT);
1583 }
1584 
1585 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1586                                                          Type *Ty) const {
1587   // FIXME: Could be smarter if called for vector constants.
1588   return true;
1589 }
1590 
1591 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1592   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1593     switch (Op) {
1594     case ISD::LOAD:
1595     case ISD::STORE:
1596 
1597     // These operations are done with 32-bit instructions anyway.
1598     case ISD::AND:
1599     case ISD::OR:
1600     case ISD::XOR:
1601     case ISD::SELECT:
1602       // TODO: Extensions?
1603       return true;
1604     default:
1605       return false;
1606     }
1607   }
1608 
1609   // SimplifySetCC uses this function to determine whether or not it should
1610   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1611   if (VT == MVT::i1 && Op == ISD::SETCC)
1612     return false;
1613 
1614   return TargetLowering::isTypeDesirableForOp(Op, VT);
1615 }
1616 
1617 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1618                                                    const SDLoc &SL,
1619                                                    SDValue Chain,
1620                                                    uint64_t Offset) const {
1621   const DataLayout &DL = DAG.getDataLayout();
1622   MachineFunction &MF = DAG.getMachineFunction();
1623   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1624 
1625   const ArgDescriptor *InputPtrReg;
1626   const TargetRegisterClass *RC;
1627   LLT ArgTy;
1628 
1629   std::tie(InputPtrReg, RC, ArgTy) =
1630       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1631 
1632   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1633   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1634   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1635     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1636 
1637   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1638 }
1639 
1640 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1641                                             const SDLoc &SL) const {
1642   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1643                                                FIRST_IMPLICIT);
1644   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1645 }
1646 
1647 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1648                                          const SDLoc &SL, SDValue Val,
1649                                          bool Signed,
1650                                          const ISD::InputArg *Arg) const {
1651   // First, if it is a widened vector, narrow it.
1652   if (VT.isVector() &&
1653       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1654     EVT NarrowedVT =
1655         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1656                          VT.getVectorNumElements());
1657     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1658                       DAG.getConstant(0, SL, MVT::i32));
1659   }
1660 
1661   // Then convert the vector elements or scalar value.
1662   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1663       VT.bitsLT(MemVT)) {
1664     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1665     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1666   }
1667 
1668   if (MemVT.isFloatingPoint())
1669     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1670   else if (Signed)
1671     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1672   else
1673     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1674 
1675   return Val;
1676 }
1677 
1678 SDValue SITargetLowering::lowerKernargMemParameter(
1679     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1680     uint64_t Offset, Align Alignment, bool Signed,
1681     const ISD::InputArg *Arg) const {
1682   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1683 
1684   // Try to avoid using an extload by loading earlier than the argument address,
1685   // and extracting the relevant bits. The load should hopefully be merged with
1686   // the previous argument.
1687   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1688     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1689     int64_t AlignDownOffset = alignDown(Offset, 4);
1690     int64_t OffsetDiff = Offset - AlignDownOffset;
1691 
1692     EVT IntVT = MemVT.changeTypeToInteger();
1693 
1694     // TODO: If we passed in the base kernel offset we could have a better
1695     // alignment than 4, but we don't really need it.
1696     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1697     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1698                                MachineMemOperand::MODereferenceable |
1699                                    MachineMemOperand::MOInvariant);
1700 
1701     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1702     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1703 
1704     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1705     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1706     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1707 
1708 
1709     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1710   }
1711 
1712   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1713   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1714                              MachineMemOperand::MODereferenceable |
1715                                  MachineMemOperand::MOInvariant);
1716 
1717   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1718   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1719 }
1720 
1721 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1722                                               const SDLoc &SL, SDValue Chain,
1723                                               const ISD::InputArg &Arg) const {
1724   MachineFunction &MF = DAG.getMachineFunction();
1725   MachineFrameInfo &MFI = MF.getFrameInfo();
1726 
1727   if (Arg.Flags.isByVal()) {
1728     unsigned Size = Arg.Flags.getByValSize();
1729     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1730     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1731   }
1732 
1733   unsigned ArgOffset = VA.getLocMemOffset();
1734   unsigned ArgSize = VA.getValVT().getStoreSize();
1735 
1736   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1737 
1738   // Create load nodes to retrieve arguments from the stack.
1739   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1740   SDValue ArgValue;
1741 
1742   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1743   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1744   MVT MemVT = VA.getValVT();
1745 
1746   switch (VA.getLocInfo()) {
1747   default:
1748     break;
1749   case CCValAssign::BCvt:
1750     MemVT = VA.getLocVT();
1751     break;
1752   case CCValAssign::SExt:
1753     ExtType = ISD::SEXTLOAD;
1754     break;
1755   case CCValAssign::ZExt:
1756     ExtType = ISD::ZEXTLOAD;
1757     break;
1758   case CCValAssign::AExt:
1759     ExtType = ISD::EXTLOAD;
1760     break;
1761   }
1762 
1763   ArgValue = DAG.getExtLoad(
1764     ExtType, SL, VA.getLocVT(), Chain, FIN,
1765     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1766     MemVT);
1767   return ArgValue;
1768 }
1769 
1770 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1771   const SIMachineFunctionInfo &MFI,
1772   EVT VT,
1773   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1774   const ArgDescriptor *Reg;
1775   const TargetRegisterClass *RC;
1776   LLT Ty;
1777 
1778   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1779   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1780 }
1781 
1782 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1783                                CallingConv::ID CallConv,
1784                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1785                                FunctionType *FType,
1786                                SIMachineFunctionInfo *Info) {
1787   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1788     const ISD::InputArg *Arg = &Ins[I];
1789 
1790     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1791            "vector type argument should have been split");
1792 
1793     // First check if it's a PS input addr.
1794     if (CallConv == CallingConv::AMDGPU_PS &&
1795         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1796       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1797 
1798       // Inconveniently only the first part of the split is marked as isSplit,
1799       // so skip to the end. We only want to increment PSInputNum once for the
1800       // entire split argument.
1801       if (Arg->Flags.isSplit()) {
1802         while (!Arg->Flags.isSplitEnd()) {
1803           assert((!Arg->VT.isVector() ||
1804                   Arg->VT.getScalarSizeInBits() == 16) &&
1805                  "unexpected vector split in ps argument type");
1806           if (!SkipArg)
1807             Splits.push_back(*Arg);
1808           Arg = &Ins[++I];
1809         }
1810       }
1811 
1812       if (SkipArg) {
1813         // We can safely skip PS inputs.
1814         Skipped.set(Arg->getOrigArgIndex());
1815         ++PSInputNum;
1816         continue;
1817       }
1818 
1819       Info->markPSInputAllocated(PSInputNum);
1820       if (Arg->Used)
1821         Info->markPSInputEnabled(PSInputNum);
1822 
1823       ++PSInputNum;
1824     }
1825 
1826     Splits.push_back(*Arg);
1827   }
1828 }
1829 
1830 // Allocate special inputs passed in VGPRs.
1831 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1832                                                       MachineFunction &MF,
1833                                                       const SIRegisterInfo &TRI,
1834                                                       SIMachineFunctionInfo &Info) const {
1835   const LLT S32 = LLT::scalar(32);
1836   MachineRegisterInfo &MRI = MF.getRegInfo();
1837 
1838   if (Info.hasWorkItemIDX()) {
1839     Register Reg = AMDGPU::VGPR0;
1840     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1841 
1842     CCInfo.AllocateReg(Reg);
1843     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1844   }
1845 
1846   if (Info.hasWorkItemIDY()) {
1847     Register Reg = AMDGPU::VGPR1;
1848     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1849 
1850     CCInfo.AllocateReg(Reg);
1851     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1852   }
1853 
1854   if (Info.hasWorkItemIDZ()) {
1855     Register Reg = AMDGPU::VGPR2;
1856     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1857 
1858     CCInfo.AllocateReg(Reg);
1859     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1860   }
1861 }
1862 
1863 // Try to allocate a VGPR at the end of the argument list, or if no argument
1864 // VGPRs are left allocating a stack slot.
1865 // If \p Mask is is given it indicates bitfield position in the register.
1866 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1867 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1868                                          ArgDescriptor Arg = ArgDescriptor()) {
1869   if (Arg.isSet())
1870     return ArgDescriptor::createArg(Arg, Mask);
1871 
1872   ArrayRef<MCPhysReg> ArgVGPRs
1873     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1874   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1875   if (RegIdx == ArgVGPRs.size()) {
1876     // Spill to stack required.
1877     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1878 
1879     return ArgDescriptor::createStack(Offset, Mask);
1880   }
1881 
1882   unsigned Reg = ArgVGPRs[RegIdx];
1883   Reg = CCInfo.AllocateReg(Reg);
1884   assert(Reg != AMDGPU::NoRegister);
1885 
1886   MachineFunction &MF = CCInfo.getMachineFunction();
1887   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1888   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1889   return ArgDescriptor::createRegister(Reg, Mask);
1890 }
1891 
1892 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1893                                              const TargetRegisterClass *RC,
1894                                              unsigned NumArgRegs) {
1895   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1896   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1897   if (RegIdx == ArgSGPRs.size())
1898     report_fatal_error("ran out of SGPRs for arguments");
1899 
1900   unsigned Reg = ArgSGPRs[RegIdx];
1901   Reg = CCInfo.AllocateReg(Reg);
1902   assert(Reg != AMDGPU::NoRegister);
1903 
1904   MachineFunction &MF = CCInfo.getMachineFunction();
1905   MF.addLiveIn(Reg, RC);
1906   return ArgDescriptor::createRegister(Reg);
1907 }
1908 
1909 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1910   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1911 }
1912 
1913 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1914   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1915 }
1916 
1917 /// Allocate implicit function VGPR arguments at the end of allocated user
1918 /// arguments.
1919 void SITargetLowering::allocateSpecialInputVGPRs(
1920   CCState &CCInfo, MachineFunction &MF,
1921   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1922   const unsigned Mask = 0x3ff;
1923   ArgDescriptor Arg;
1924 
1925   if (Info.hasWorkItemIDX()) {
1926     Arg = allocateVGPR32Input(CCInfo, Mask);
1927     Info.setWorkItemIDX(Arg);
1928   }
1929 
1930   if (Info.hasWorkItemIDY()) {
1931     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1932     Info.setWorkItemIDY(Arg);
1933   }
1934 
1935   if (Info.hasWorkItemIDZ())
1936     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1937 }
1938 
1939 /// Allocate implicit function VGPR arguments in fixed registers.
1940 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1941   CCState &CCInfo, MachineFunction &MF,
1942   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1943   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1944   if (!Reg)
1945     report_fatal_error("failed to allocated VGPR for implicit arguments");
1946 
1947   const unsigned Mask = 0x3ff;
1948   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1949   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1950   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1951 }
1952 
1953 void SITargetLowering::allocateSpecialInputSGPRs(
1954   CCState &CCInfo,
1955   MachineFunction &MF,
1956   const SIRegisterInfo &TRI,
1957   SIMachineFunctionInfo &Info) const {
1958   auto &ArgInfo = Info.getArgInfo();
1959 
1960   // TODO: Unify handling with private memory pointers.
1961 
1962   if (Info.hasDispatchPtr())
1963     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1964 
1965   if (Info.hasQueuePtr())
1966     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1967 
1968   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1969   // constant offset from the kernarg segment.
1970   if (Info.hasImplicitArgPtr())
1971     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1972 
1973   if (Info.hasDispatchID())
1974     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1975 
1976   // flat_scratch_init is not applicable for non-kernel functions.
1977 
1978   if (Info.hasWorkGroupIDX())
1979     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1980 
1981   if (Info.hasWorkGroupIDY())
1982     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1983 
1984   if (Info.hasWorkGroupIDZ())
1985     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1986 }
1987 
1988 // Allocate special inputs passed in user SGPRs.
1989 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1990                                             MachineFunction &MF,
1991                                             const SIRegisterInfo &TRI,
1992                                             SIMachineFunctionInfo &Info) const {
1993   if (Info.hasImplicitBufferPtr()) {
1994     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1995     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1996     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1997   }
1998 
1999   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2000   if (Info.hasPrivateSegmentBuffer()) {
2001     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2002     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2003     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2004   }
2005 
2006   if (Info.hasDispatchPtr()) {
2007     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2008     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2009     CCInfo.AllocateReg(DispatchPtrReg);
2010   }
2011 
2012   if (Info.hasQueuePtr()) {
2013     Register QueuePtrReg = Info.addQueuePtr(TRI);
2014     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2015     CCInfo.AllocateReg(QueuePtrReg);
2016   }
2017 
2018   if (Info.hasKernargSegmentPtr()) {
2019     MachineRegisterInfo &MRI = MF.getRegInfo();
2020     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2021     CCInfo.AllocateReg(InputPtrReg);
2022 
2023     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2024     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2025   }
2026 
2027   if (Info.hasDispatchID()) {
2028     Register DispatchIDReg = Info.addDispatchID(TRI);
2029     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2030     CCInfo.AllocateReg(DispatchIDReg);
2031   }
2032 
2033   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2034     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2035     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2036     CCInfo.AllocateReg(FlatScratchInitReg);
2037   }
2038 
2039   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2040   // these from the dispatch pointer.
2041 }
2042 
2043 // Allocate special input registers that are initialized per-wave.
2044 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2045                                            MachineFunction &MF,
2046                                            SIMachineFunctionInfo &Info,
2047                                            CallingConv::ID CallConv,
2048                                            bool IsShader) const {
2049   if (Info.hasWorkGroupIDX()) {
2050     Register Reg = Info.addWorkGroupIDX();
2051     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2052     CCInfo.AllocateReg(Reg);
2053   }
2054 
2055   if (Info.hasWorkGroupIDY()) {
2056     Register Reg = Info.addWorkGroupIDY();
2057     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2058     CCInfo.AllocateReg(Reg);
2059   }
2060 
2061   if (Info.hasWorkGroupIDZ()) {
2062     Register Reg = Info.addWorkGroupIDZ();
2063     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2064     CCInfo.AllocateReg(Reg);
2065   }
2066 
2067   if (Info.hasWorkGroupInfo()) {
2068     Register Reg = Info.addWorkGroupInfo();
2069     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2070     CCInfo.AllocateReg(Reg);
2071   }
2072 
2073   if (Info.hasPrivateSegmentWaveByteOffset()) {
2074     // Scratch wave offset passed in system SGPR.
2075     unsigned PrivateSegmentWaveByteOffsetReg;
2076 
2077     if (IsShader) {
2078       PrivateSegmentWaveByteOffsetReg =
2079         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2080 
2081       // This is true if the scratch wave byte offset doesn't have a fixed
2082       // location.
2083       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2084         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2085         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2086       }
2087     } else
2088       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2089 
2090     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2091     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2092   }
2093 }
2094 
2095 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2096                                      MachineFunction &MF,
2097                                      const SIRegisterInfo &TRI,
2098                                      SIMachineFunctionInfo &Info) {
2099   // Now that we've figured out where the scratch register inputs are, see if
2100   // should reserve the arguments and use them directly.
2101   MachineFrameInfo &MFI = MF.getFrameInfo();
2102   bool HasStackObjects = MFI.hasStackObjects();
2103   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2104 
2105   // Record that we know we have non-spill stack objects so we don't need to
2106   // check all stack objects later.
2107   if (HasStackObjects)
2108     Info.setHasNonSpillStackObjects(true);
2109 
2110   // Everything live out of a block is spilled with fast regalloc, so it's
2111   // almost certain that spilling will be required.
2112   if (TM.getOptLevel() == CodeGenOpt::None)
2113     HasStackObjects = true;
2114 
2115   // For now assume stack access is needed in any callee functions, so we need
2116   // the scratch registers to pass in.
2117   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2118 
2119   if (!ST.enableFlatScratch()) {
2120     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2121       // If we have stack objects, we unquestionably need the private buffer
2122       // resource. For the Code Object V2 ABI, this will be the first 4 user
2123       // SGPR inputs. We can reserve those and use them directly.
2124 
2125       Register PrivateSegmentBufferReg =
2126           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2127       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2128     } else {
2129       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2130       // We tentatively reserve the last registers (skipping the last registers
2131       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2132       // we'll replace these with the ones immediately after those which were
2133       // really allocated. In the prologue copies will be inserted from the
2134       // argument to these reserved registers.
2135 
2136       // Without HSA, relocations are used for the scratch pointer and the
2137       // buffer resource setup is always inserted in the prologue. Scratch wave
2138       // offset is still in an input SGPR.
2139       Info.setScratchRSrcReg(ReservedBufferReg);
2140     }
2141   }
2142 
2143   MachineRegisterInfo &MRI = MF.getRegInfo();
2144 
2145   // For entry functions we have to set up the stack pointer if we use it,
2146   // whereas non-entry functions get this "for free". This means there is no
2147   // intrinsic advantage to using S32 over S34 in cases where we do not have
2148   // calls but do need a frame pointer (i.e. if we are requested to have one
2149   // because frame pointer elimination is disabled). To keep things simple we
2150   // only ever use S32 as the call ABI stack pointer, and so using it does not
2151   // imply we need a separate frame pointer.
2152   //
2153   // Try to use s32 as the SP, but move it if it would interfere with input
2154   // arguments. This won't work with calls though.
2155   //
2156   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2157   // registers.
2158   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2159     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2160   } else {
2161     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2162 
2163     if (MFI.hasCalls())
2164       report_fatal_error("call in graphics shader with too many input SGPRs");
2165 
2166     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2167       if (!MRI.isLiveIn(Reg)) {
2168         Info.setStackPtrOffsetReg(Reg);
2169         break;
2170       }
2171     }
2172 
2173     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2174       report_fatal_error("failed to find register for SP");
2175   }
2176 
2177   // hasFP should be accurate for entry functions even before the frame is
2178   // finalized, because it does not rely on the known stack size, only
2179   // properties like whether variable sized objects are present.
2180   if (ST.getFrameLowering()->hasFP(MF)) {
2181     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2182   }
2183 }
2184 
2185 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2186   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2187   return !Info->isEntryFunction();
2188 }
2189 
2190 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2191 
2192 }
2193 
2194 void SITargetLowering::insertCopiesSplitCSR(
2195   MachineBasicBlock *Entry,
2196   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2197   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2198 
2199   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2200   if (!IStart)
2201     return;
2202 
2203   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2204   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2205   MachineBasicBlock::iterator MBBI = Entry->begin();
2206   for (const MCPhysReg *I = IStart; *I; ++I) {
2207     const TargetRegisterClass *RC = nullptr;
2208     if (AMDGPU::SReg_64RegClass.contains(*I))
2209       RC = &AMDGPU::SGPR_64RegClass;
2210     else if (AMDGPU::SReg_32RegClass.contains(*I))
2211       RC = &AMDGPU::SGPR_32RegClass;
2212     else
2213       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2214 
2215     Register NewVR = MRI->createVirtualRegister(RC);
2216     // Create copy from CSR to a virtual register.
2217     Entry->addLiveIn(*I);
2218     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2219       .addReg(*I);
2220 
2221     // Insert the copy-back instructions right before the terminator.
2222     for (auto *Exit : Exits)
2223       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2224               TII->get(TargetOpcode::COPY), *I)
2225         .addReg(NewVR);
2226   }
2227 }
2228 
2229 SDValue SITargetLowering::LowerFormalArguments(
2230     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2231     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2232     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2233   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2234 
2235   MachineFunction &MF = DAG.getMachineFunction();
2236   const Function &Fn = MF.getFunction();
2237   FunctionType *FType = MF.getFunction().getFunctionType();
2238   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2239 
2240   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2241     DiagnosticInfoUnsupported NoGraphicsHSA(
2242         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2243     DAG.getContext()->diagnose(NoGraphicsHSA);
2244     return DAG.getEntryNode();
2245   }
2246 
2247   SmallVector<ISD::InputArg, 16> Splits;
2248   SmallVector<CCValAssign, 16> ArgLocs;
2249   BitVector Skipped(Ins.size());
2250   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2251                  *DAG.getContext());
2252 
2253   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2254   bool IsKernel = AMDGPU::isKernel(CallConv);
2255   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2256 
2257   if (IsGraphics) {
2258     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2259            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2260            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2261            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2262            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2263            !Info->hasWorkItemIDZ());
2264   }
2265 
2266   if (CallConv == CallingConv::AMDGPU_PS) {
2267     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2268 
2269     // At least one interpolation mode must be enabled or else the GPU will
2270     // hang.
2271     //
2272     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2273     // set PSInputAddr, the user wants to enable some bits after the compilation
2274     // based on run-time states. Since we can't know what the final PSInputEna
2275     // will look like, so we shouldn't do anything here and the user should take
2276     // responsibility for the correct programming.
2277     //
2278     // Otherwise, the following restrictions apply:
2279     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2280     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2281     //   enabled too.
2282     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2283         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2284       CCInfo.AllocateReg(AMDGPU::VGPR0);
2285       CCInfo.AllocateReg(AMDGPU::VGPR1);
2286       Info->markPSInputAllocated(0);
2287       Info->markPSInputEnabled(0);
2288     }
2289     if (Subtarget->isAmdPalOS()) {
2290       // For isAmdPalOS, the user does not enable some bits after compilation
2291       // based on run-time states; the register values being generated here are
2292       // the final ones set in hardware. Therefore we need to apply the
2293       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2294       // a bit is set in PSInputAddr but not PSInputEnable is where the
2295       // frontend set up an input arg for a particular interpolation mode, but
2296       // nothing uses that input arg. Really we should have an earlier pass
2297       // that removes such an arg.)
2298       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2299       if ((PsInputBits & 0x7F) == 0 ||
2300           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2301         Info->markPSInputEnabled(
2302             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2303     }
2304   } else if (IsKernel) {
2305     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2306   } else {
2307     Splits.append(Ins.begin(), Ins.end());
2308   }
2309 
2310   if (IsEntryFunc) {
2311     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2312     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2313   } else {
2314     // For the fixed ABI, pass workitem IDs in the last argument register.
2315     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2316       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2317   }
2318 
2319   if (IsKernel) {
2320     analyzeFormalArgumentsCompute(CCInfo, Ins);
2321   } else {
2322     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2323     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2324   }
2325 
2326   SmallVector<SDValue, 16> Chains;
2327 
2328   // FIXME: This is the minimum kernel argument alignment. We should improve
2329   // this to the maximum alignment of the arguments.
2330   //
2331   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2332   // kern arg offset.
2333   const Align KernelArgBaseAlign = Align(16);
2334 
2335   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2336     const ISD::InputArg &Arg = Ins[i];
2337     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2338       InVals.push_back(DAG.getUNDEF(Arg.VT));
2339       continue;
2340     }
2341 
2342     CCValAssign &VA = ArgLocs[ArgIdx++];
2343     MVT VT = VA.getLocVT();
2344 
2345     if (IsEntryFunc && VA.isMemLoc()) {
2346       VT = Ins[i].VT;
2347       EVT MemVT = VA.getLocVT();
2348 
2349       const uint64_t Offset = VA.getLocMemOffset();
2350       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2351 
2352       if (Arg.Flags.isByRef()) {
2353         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2354 
2355         const GCNTargetMachine &TM =
2356             static_cast<const GCNTargetMachine &>(getTargetMachine());
2357         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2358                                     Arg.Flags.getPointerAddrSpace())) {
2359           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2360                                      Arg.Flags.getPointerAddrSpace());
2361         }
2362 
2363         InVals.push_back(Ptr);
2364         continue;
2365       }
2366 
2367       SDValue Arg = lowerKernargMemParameter(
2368         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2369       Chains.push_back(Arg.getValue(1));
2370 
2371       auto *ParamTy =
2372         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2373       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2374           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2375                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2376         // On SI local pointers are just offsets into LDS, so they are always
2377         // less than 16-bits.  On CI and newer they could potentially be
2378         // real pointers, so we can't guarantee their size.
2379         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2380                           DAG.getValueType(MVT::i16));
2381       }
2382 
2383       InVals.push_back(Arg);
2384       continue;
2385     } else if (!IsEntryFunc && VA.isMemLoc()) {
2386       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2387       InVals.push_back(Val);
2388       if (!Arg.Flags.isByVal())
2389         Chains.push_back(Val.getValue(1));
2390       continue;
2391     }
2392 
2393     assert(VA.isRegLoc() && "Parameter must be in a register!");
2394 
2395     Register Reg = VA.getLocReg();
2396     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2397     EVT ValVT = VA.getValVT();
2398 
2399     Reg = MF.addLiveIn(Reg, RC);
2400     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2401 
2402     if (Arg.Flags.isSRet()) {
2403       // The return object should be reasonably addressable.
2404 
2405       // FIXME: This helps when the return is a real sret. If it is a
2406       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2407       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2408       unsigned NumBits
2409         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2410       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2411         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2412     }
2413 
2414     // If this is an 8 or 16-bit value, it is really passed promoted
2415     // to 32 bits. Insert an assert[sz]ext to capture this, then
2416     // truncate to the right size.
2417     switch (VA.getLocInfo()) {
2418     case CCValAssign::Full:
2419       break;
2420     case CCValAssign::BCvt:
2421       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2422       break;
2423     case CCValAssign::SExt:
2424       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2425                         DAG.getValueType(ValVT));
2426       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2427       break;
2428     case CCValAssign::ZExt:
2429       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2430                         DAG.getValueType(ValVT));
2431       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2432       break;
2433     case CCValAssign::AExt:
2434       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2435       break;
2436     default:
2437       llvm_unreachable("Unknown loc info!");
2438     }
2439 
2440     InVals.push_back(Val);
2441   }
2442 
2443   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2444     // Special inputs come after user arguments.
2445     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2446   }
2447 
2448   // Start adding system SGPRs.
2449   if (IsEntryFunc) {
2450     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2451   } else {
2452     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2453     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2454   }
2455 
2456   auto &ArgUsageInfo =
2457     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2458   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2459 
2460   unsigned StackArgSize = CCInfo.getNextStackOffset();
2461   Info->setBytesInStackArgArea(StackArgSize);
2462 
2463   return Chains.empty() ? Chain :
2464     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2465 }
2466 
2467 // TODO: If return values can't fit in registers, we should return as many as
2468 // possible in registers before passing on stack.
2469 bool SITargetLowering::CanLowerReturn(
2470   CallingConv::ID CallConv,
2471   MachineFunction &MF, bool IsVarArg,
2472   const SmallVectorImpl<ISD::OutputArg> &Outs,
2473   LLVMContext &Context) const {
2474   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2475   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2476   // for shaders. Vector types should be explicitly handled by CC.
2477   if (AMDGPU::isEntryFunctionCC(CallConv))
2478     return true;
2479 
2480   SmallVector<CCValAssign, 16> RVLocs;
2481   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2482   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2483 }
2484 
2485 SDValue
2486 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2487                               bool isVarArg,
2488                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2489                               const SmallVectorImpl<SDValue> &OutVals,
2490                               const SDLoc &DL, SelectionDAG &DAG) const {
2491   MachineFunction &MF = DAG.getMachineFunction();
2492   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2493 
2494   if (AMDGPU::isKernel(CallConv)) {
2495     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2496                                              OutVals, DL, DAG);
2497   }
2498 
2499   bool IsShader = AMDGPU::isShader(CallConv);
2500 
2501   Info->setIfReturnsVoid(Outs.empty());
2502   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2503 
2504   // CCValAssign - represent the assignment of the return value to a location.
2505   SmallVector<CCValAssign, 48> RVLocs;
2506   SmallVector<ISD::OutputArg, 48> Splits;
2507 
2508   // CCState - Info about the registers and stack slots.
2509   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2510                  *DAG.getContext());
2511 
2512   // Analyze outgoing return values.
2513   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2514 
2515   SDValue Flag;
2516   SmallVector<SDValue, 48> RetOps;
2517   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2518 
2519   // Add return address for callable functions.
2520   if (!Info->isEntryFunction()) {
2521     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2522     SDValue ReturnAddrReg = CreateLiveInRegister(
2523       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2524 
2525     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2526         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2527         MVT::i64);
2528     Chain =
2529         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2530     Flag = Chain.getValue(1);
2531     RetOps.push_back(ReturnAddrVirtualReg);
2532   }
2533 
2534   // Copy the result values into the output registers.
2535   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2536        ++I, ++RealRVLocIdx) {
2537     CCValAssign &VA = RVLocs[I];
2538     assert(VA.isRegLoc() && "Can only return in registers!");
2539     // TODO: Partially return in registers if return values don't fit.
2540     SDValue Arg = OutVals[RealRVLocIdx];
2541 
2542     // Copied from other backends.
2543     switch (VA.getLocInfo()) {
2544     case CCValAssign::Full:
2545       break;
2546     case CCValAssign::BCvt:
2547       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2548       break;
2549     case CCValAssign::SExt:
2550       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2551       break;
2552     case CCValAssign::ZExt:
2553       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2554       break;
2555     case CCValAssign::AExt:
2556       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2557       break;
2558     default:
2559       llvm_unreachable("Unknown loc info!");
2560     }
2561 
2562     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2563     Flag = Chain.getValue(1);
2564     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2565   }
2566 
2567   // FIXME: Does sret work properly?
2568   if (!Info->isEntryFunction()) {
2569     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2570     const MCPhysReg *I =
2571       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2572     if (I) {
2573       for (; *I; ++I) {
2574         if (AMDGPU::SReg_64RegClass.contains(*I))
2575           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2576         else if (AMDGPU::SReg_32RegClass.contains(*I))
2577           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2578         else
2579           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2580       }
2581     }
2582   }
2583 
2584   // Update chain and glue.
2585   RetOps[0] = Chain;
2586   if (Flag.getNode())
2587     RetOps.push_back(Flag);
2588 
2589   unsigned Opc = AMDGPUISD::ENDPGM;
2590   if (!IsWaveEnd)
2591     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2592   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2593 }
2594 
2595 SDValue SITargetLowering::LowerCallResult(
2596     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2597     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2598     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2599     SDValue ThisVal) const {
2600   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2601 
2602   // Assign locations to each value returned by this call.
2603   SmallVector<CCValAssign, 16> RVLocs;
2604   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2605                  *DAG.getContext());
2606   CCInfo.AnalyzeCallResult(Ins, RetCC);
2607 
2608   // Copy all of the result registers out of their specified physreg.
2609   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2610     CCValAssign VA = RVLocs[i];
2611     SDValue Val;
2612 
2613     if (VA.isRegLoc()) {
2614       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2615       Chain = Val.getValue(1);
2616       InFlag = Val.getValue(2);
2617     } else if (VA.isMemLoc()) {
2618       report_fatal_error("TODO: return values in memory");
2619     } else
2620       llvm_unreachable("unknown argument location type");
2621 
2622     switch (VA.getLocInfo()) {
2623     case CCValAssign::Full:
2624       break;
2625     case CCValAssign::BCvt:
2626       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2627       break;
2628     case CCValAssign::ZExt:
2629       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2630                         DAG.getValueType(VA.getValVT()));
2631       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2632       break;
2633     case CCValAssign::SExt:
2634       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2635                         DAG.getValueType(VA.getValVT()));
2636       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2637       break;
2638     case CCValAssign::AExt:
2639       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2640       break;
2641     default:
2642       llvm_unreachable("Unknown loc info!");
2643     }
2644 
2645     InVals.push_back(Val);
2646   }
2647 
2648   return Chain;
2649 }
2650 
2651 // Add code to pass special inputs required depending on used features separate
2652 // from the explicit user arguments present in the IR.
2653 void SITargetLowering::passSpecialInputs(
2654     CallLoweringInfo &CLI,
2655     CCState &CCInfo,
2656     const SIMachineFunctionInfo &Info,
2657     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2658     SmallVectorImpl<SDValue> &MemOpChains,
2659     SDValue Chain) const {
2660   // If we don't have a call site, this was a call inserted by
2661   // legalization. These can never use special inputs.
2662   if (!CLI.CB)
2663     return;
2664 
2665   SelectionDAG &DAG = CLI.DAG;
2666   const SDLoc &DL = CLI.DL;
2667 
2668   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2669   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2670 
2671   const AMDGPUFunctionArgInfo *CalleeArgInfo
2672     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2673   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2674     auto &ArgUsageInfo =
2675       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2676     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2677   }
2678 
2679   // TODO: Unify with private memory register handling. This is complicated by
2680   // the fact that at least in kernels, the input argument is not necessarily
2681   // in the same location as the input.
2682   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2683     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2684     AMDGPUFunctionArgInfo::QUEUE_PTR,
2685     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2686     AMDGPUFunctionArgInfo::DISPATCH_ID,
2687     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2688     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2689     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2690   };
2691 
2692   for (auto InputID : InputRegs) {
2693     const ArgDescriptor *OutgoingArg;
2694     const TargetRegisterClass *ArgRC;
2695     LLT ArgTy;
2696 
2697     std::tie(OutgoingArg, ArgRC, ArgTy) =
2698         CalleeArgInfo->getPreloadedValue(InputID);
2699     if (!OutgoingArg)
2700       continue;
2701 
2702     const ArgDescriptor *IncomingArg;
2703     const TargetRegisterClass *IncomingArgRC;
2704     LLT Ty;
2705     std::tie(IncomingArg, IncomingArgRC, Ty) =
2706         CallerArgInfo.getPreloadedValue(InputID);
2707     assert(IncomingArgRC == ArgRC);
2708 
2709     // All special arguments are ints for now.
2710     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2711     SDValue InputReg;
2712 
2713     if (IncomingArg) {
2714       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2715     } else {
2716       // The implicit arg ptr is special because it doesn't have a corresponding
2717       // input for kernels, and is computed from the kernarg segment pointer.
2718       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2719       InputReg = getImplicitArgPtr(DAG, DL);
2720     }
2721 
2722     if (OutgoingArg->isRegister()) {
2723       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2724       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2725         report_fatal_error("failed to allocate implicit input argument");
2726     } else {
2727       unsigned SpecialArgOffset =
2728           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2729       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2730                                               SpecialArgOffset);
2731       MemOpChains.push_back(ArgStore);
2732     }
2733   }
2734 
2735   // Pack workitem IDs into a single register or pass it as is if already
2736   // packed.
2737   const ArgDescriptor *OutgoingArg;
2738   const TargetRegisterClass *ArgRC;
2739   LLT Ty;
2740 
2741   std::tie(OutgoingArg, ArgRC, Ty) =
2742       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2743   if (!OutgoingArg)
2744     std::tie(OutgoingArg, ArgRC, Ty) =
2745         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2746   if (!OutgoingArg)
2747     std::tie(OutgoingArg, ArgRC, Ty) =
2748         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2749   if (!OutgoingArg)
2750     return;
2751 
2752   const ArgDescriptor *IncomingArgX = std::get<0>(
2753       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2754   const ArgDescriptor *IncomingArgY = std::get<0>(
2755       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2756   const ArgDescriptor *IncomingArgZ = std::get<0>(
2757       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2758 
2759   SDValue InputReg;
2760   SDLoc SL;
2761 
2762   // If incoming ids are not packed we need to pack them.
2763   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2764     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2765 
2766   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2767     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2768     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2769                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2770     InputReg = InputReg.getNode() ?
2771                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2772   }
2773 
2774   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2775     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2776     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2777                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2778     InputReg = InputReg.getNode() ?
2779                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2780   }
2781 
2782   if (!InputReg.getNode()) {
2783     // Workitem ids are already packed, any of present incoming arguments
2784     // will carry all required fields.
2785     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2786       IncomingArgX ? *IncomingArgX :
2787       IncomingArgY ? *IncomingArgY :
2788                      *IncomingArgZ, ~0u);
2789     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2790   }
2791 
2792   if (OutgoingArg->isRegister()) {
2793     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2794     CCInfo.AllocateReg(OutgoingArg->getRegister());
2795   } else {
2796     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2797     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2798                                             SpecialArgOffset);
2799     MemOpChains.push_back(ArgStore);
2800   }
2801 }
2802 
2803 static bool canGuaranteeTCO(CallingConv::ID CC) {
2804   return CC == CallingConv::Fast;
2805 }
2806 
2807 /// Return true if we might ever do TCO for calls with this calling convention.
2808 static bool mayTailCallThisCC(CallingConv::ID CC) {
2809   switch (CC) {
2810   case CallingConv::C:
2811     return true;
2812   default:
2813     return canGuaranteeTCO(CC);
2814   }
2815 }
2816 
2817 bool SITargetLowering::isEligibleForTailCallOptimization(
2818     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2819     const SmallVectorImpl<ISD::OutputArg> &Outs,
2820     const SmallVectorImpl<SDValue> &OutVals,
2821     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2822   if (!mayTailCallThisCC(CalleeCC))
2823     return false;
2824 
2825   MachineFunction &MF = DAG.getMachineFunction();
2826   const Function &CallerF = MF.getFunction();
2827   CallingConv::ID CallerCC = CallerF.getCallingConv();
2828   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2829   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2830 
2831   // Kernels aren't callable, and don't have a live in return address so it
2832   // doesn't make sense to do a tail call with entry functions.
2833   if (!CallerPreserved)
2834     return false;
2835 
2836   bool CCMatch = CallerCC == CalleeCC;
2837 
2838   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2839     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2840       return true;
2841     return false;
2842   }
2843 
2844   // TODO: Can we handle var args?
2845   if (IsVarArg)
2846     return false;
2847 
2848   for (const Argument &Arg : CallerF.args()) {
2849     if (Arg.hasByValAttr())
2850       return false;
2851   }
2852 
2853   LLVMContext &Ctx = *DAG.getContext();
2854 
2855   // Check that the call results are passed in the same way.
2856   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2857                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2858                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2859     return false;
2860 
2861   // The callee has to preserve all registers the caller needs to preserve.
2862   if (!CCMatch) {
2863     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2864     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2865       return false;
2866   }
2867 
2868   // Nothing more to check if the callee is taking no arguments.
2869   if (Outs.empty())
2870     return true;
2871 
2872   SmallVector<CCValAssign, 16> ArgLocs;
2873   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2874 
2875   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2876 
2877   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2878   // If the stack arguments for this call do not fit into our own save area then
2879   // the call cannot be made tail.
2880   // TODO: Is this really necessary?
2881   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2882     return false;
2883 
2884   const MachineRegisterInfo &MRI = MF.getRegInfo();
2885   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2886 }
2887 
2888 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2889   if (!CI->isTailCall())
2890     return false;
2891 
2892   const Function *ParentFn = CI->getParent()->getParent();
2893   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2894     return false;
2895   return true;
2896 }
2897 
2898 // The wave scratch offset register is used as the global base pointer.
2899 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2900                                     SmallVectorImpl<SDValue> &InVals) const {
2901   SelectionDAG &DAG = CLI.DAG;
2902   const SDLoc &DL = CLI.DL;
2903   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2904   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2905   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2906   SDValue Chain = CLI.Chain;
2907   SDValue Callee = CLI.Callee;
2908   bool &IsTailCall = CLI.IsTailCall;
2909   CallingConv::ID CallConv = CLI.CallConv;
2910   bool IsVarArg = CLI.IsVarArg;
2911   bool IsSibCall = false;
2912   bool IsThisReturn = false;
2913   MachineFunction &MF = DAG.getMachineFunction();
2914 
2915   if (Callee.isUndef() || isNullConstant(Callee)) {
2916     if (!CLI.IsTailCall) {
2917       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2918         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2919     }
2920 
2921     return Chain;
2922   }
2923 
2924   if (IsVarArg) {
2925     return lowerUnhandledCall(CLI, InVals,
2926                               "unsupported call to variadic function ");
2927   }
2928 
2929   if (!CLI.CB)
2930     report_fatal_error("unsupported libcall legalization");
2931 
2932   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2933       !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) {
2934     return lowerUnhandledCall(CLI, InVals,
2935                               "unsupported indirect call to function ");
2936   }
2937 
2938   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2939     return lowerUnhandledCall(CLI, InVals,
2940                               "unsupported required tail call to function ");
2941   }
2942 
2943   if (AMDGPU::isShader(CallConv)) {
2944     // Note the issue is with the CC of the called function, not of the call
2945     // itself.
2946     return lowerUnhandledCall(CLI, InVals,
2947                               "unsupported call to a shader function ");
2948   }
2949 
2950   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2951       CallConv != CallingConv::AMDGPU_Gfx) {
2952     // Only allow calls with specific calling conventions.
2953     return lowerUnhandledCall(CLI, InVals,
2954                               "unsupported calling convention for call from "
2955                               "graphics shader of function ");
2956   }
2957 
2958   if (IsTailCall) {
2959     IsTailCall = isEligibleForTailCallOptimization(
2960       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2961     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2962       report_fatal_error("failed to perform tail call elimination on a call "
2963                          "site marked musttail");
2964     }
2965 
2966     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2967 
2968     // A sibling call is one where we're under the usual C ABI and not planning
2969     // to change that but can still do a tail call:
2970     if (!TailCallOpt && IsTailCall)
2971       IsSibCall = true;
2972 
2973     if (IsTailCall)
2974       ++NumTailCalls;
2975   }
2976 
2977   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2978   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2979   SmallVector<SDValue, 8> MemOpChains;
2980 
2981   // Analyze operands of the call, assigning locations to each operand.
2982   SmallVector<CCValAssign, 16> ArgLocs;
2983   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2984   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2985 
2986   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
2987       CallConv != CallingConv::AMDGPU_Gfx) {
2988     // With a fixed ABI, allocate fixed registers before user arguments.
2989     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2990   }
2991 
2992   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2993 
2994   // Get a count of how many bytes are to be pushed on the stack.
2995   unsigned NumBytes = CCInfo.getNextStackOffset();
2996 
2997   if (IsSibCall) {
2998     // Since we're not changing the ABI to make this a tail call, the memory
2999     // operands are already available in the caller's incoming argument space.
3000     NumBytes = 0;
3001   }
3002 
3003   // FPDiff is the byte offset of the call's argument area from the callee's.
3004   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3005   // by this amount for a tail call. In a sibling call it must be 0 because the
3006   // caller will deallocate the entire stack and the callee still expects its
3007   // arguments to begin at SP+0. Completely unused for non-tail calls.
3008   int32_t FPDiff = 0;
3009   MachineFrameInfo &MFI = MF.getFrameInfo();
3010 
3011   // Adjust the stack pointer for the new arguments...
3012   // These operations are automatically eliminated by the prolog/epilog pass
3013   if (!IsSibCall) {
3014     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3015 
3016     if (!Subtarget->enableFlatScratch()) {
3017       SmallVector<SDValue, 4> CopyFromChains;
3018 
3019       // In the HSA case, this should be an identity copy.
3020       SDValue ScratchRSrcReg
3021         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3022       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3023       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3024       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3025     }
3026   }
3027 
3028   MVT PtrVT = MVT::i32;
3029 
3030   // Walk the register/memloc assignments, inserting copies/loads.
3031   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3032     CCValAssign &VA = ArgLocs[i];
3033     SDValue Arg = OutVals[i];
3034 
3035     // Promote the value if needed.
3036     switch (VA.getLocInfo()) {
3037     case CCValAssign::Full:
3038       break;
3039     case CCValAssign::BCvt:
3040       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3041       break;
3042     case CCValAssign::ZExt:
3043       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3044       break;
3045     case CCValAssign::SExt:
3046       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3047       break;
3048     case CCValAssign::AExt:
3049       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3050       break;
3051     case CCValAssign::FPExt:
3052       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3053       break;
3054     default:
3055       llvm_unreachable("Unknown loc info!");
3056     }
3057 
3058     if (VA.isRegLoc()) {
3059       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3060     } else {
3061       assert(VA.isMemLoc());
3062 
3063       SDValue DstAddr;
3064       MachinePointerInfo DstInfo;
3065 
3066       unsigned LocMemOffset = VA.getLocMemOffset();
3067       int32_t Offset = LocMemOffset;
3068 
3069       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3070       MaybeAlign Alignment;
3071 
3072       if (IsTailCall) {
3073         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3074         unsigned OpSize = Flags.isByVal() ?
3075           Flags.getByValSize() : VA.getValVT().getStoreSize();
3076 
3077         // FIXME: We can have better than the minimum byval required alignment.
3078         Alignment =
3079             Flags.isByVal()
3080                 ? Flags.getNonZeroByValAlign()
3081                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3082 
3083         Offset = Offset + FPDiff;
3084         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3085 
3086         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3087         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3088 
3089         // Make sure any stack arguments overlapping with where we're storing
3090         // are loaded before this eventual operation. Otherwise they'll be
3091         // clobbered.
3092 
3093         // FIXME: Why is this really necessary? This seems to just result in a
3094         // lot of code to copy the stack and write them back to the same
3095         // locations, which are supposed to be immutable?
3096         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3097       } else {
3098         DstAddr = PtrOff;
3099         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3100         Alignment =
3101             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3102       }
3103 
3104       if (Outs[i].Flags.isByVal()) {
3105         SDValue SizeNode =
3106             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3107         SDValue Cpy =
3108             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3109                           Outs[i].Flags.getNonZeroByValAlign(),
3110                           /*isVol = */ false, /*AlwaysInline = */ true,
3111                           /*isTailCall = */ false, DstInfo,
3112                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3113 
3114         MemOpChains.push_back(Cpy);
3115       } else {
3116         SDValue Store =
3117             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3118         MemOpChains.push_back(Store);
3119       }
3120     }
3121   }
3122 
3123   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3124       CallConv != CallingConv::AMDGPU_Gfx) {
3125     // Copy special input registers after user input arguments.
3126     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3127   }
3128 
3129   if (!MemOpChains.empty())
3130     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3131 
3132   // Build a sequence of copy-to-reg nodes chained together with token chain
3133   // and flag operands which copy the outgoing args into the appropriate regs.
3134   SDValue InFlag;
3135   for (auto &RegToPass : RegsToPass) {
3136     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3137                              RegToPass.second, InFlag);
3138     InFlag = Chain.getValue(1);
3139   }
3140 
3141 
3142   SDValue PhysReturnAddrReg;
3143   if (IsTailCall) {
3144     // Since the return is being combined with the call, we need to pass on the
3145     // return address.
3146 
3147     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3148     SDValue ReturnAddrReg = CreateLiveInRegister(
3149       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3150 
3151     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3152                                         MVT::i64);
3153     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3154     InFlag = Chain.getValue(1);
3155   }
3156 
3157   // We don't usually want to end the call-sequence here because we would tidy
3158   // the frame up *after* the call, however in the ABI-changing tail-call case
3159   // we've carefully laid out the parameters so that when sp is reset they'll be
3160   // in the correct location.
3161   if (IsTailCall && !IsSibCall) {
3162     Chain = DAG.getCALLSEQ_END(Chain,
3163                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3164                                DAG.getTargetConstant(0, DL, MVT::i32),
3165                                InFlag, DL);
3166     InFlag = Chain.getValue(1);
3167   }
3168 
3169   std::vector<SDValue> Ops;
3170   Ops.push_back(Chain);
3171   Ops.push_back(Callee);
3172   // Add a redundant copy of the callee global which will not be legalized, as
3173   // we need direct access to the callee later.
3174   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3175     const GlobalValue *GV = GSD->getGlobal();
3176     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3177   } else {
3178     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3179   }
3180 
3181   if (IsTailCall) {
3182     // Each tail call may have to adjust the stack by a different amount, so
3183     // this information must travel along with the operation for eventual
3184     // consumption by emitEpilogue.
3185     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3186 
3187     Ops.push_back(PhysReturnAddrReg);
3188   }
3189 
3190   // Add argument registers to the end of the list so that they are known live
3191   // into the call.
3192   for (auto &RegToPass : RegsToPass) {
3193     Ops.push_back(DAG.getRegister(RegToPass.first,
3194                                   RegToPass.second.getValueType()));
3195   }
3196 
3197   // Add a register mask operand representing the call-preserved registers.
3198 
3199   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3200   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3201   assert(Mask && "Missing call preserved mask for calling convention");
3202   Ops.push_back(DAG.getRegisterMask(Mask));
3203 
3204   if (InFlag.getNode())
3205     Ops.push_back(InFlag);
3206 
3207   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3208 
3209   // If we're doing a tall call, use a TC_RETURN here rather than an
3210   // actual call instruction.
3211   if (IsTailCall) {
3212     MFI.setHasTailCall();
3213     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3214   }
3215 
3216   // Returns a chain and a flag for retval copy to use.
3217   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3218   Chain = Call.getValue(0);
3219   InFlag = Call.getValue(1);
3220 
3221   uint64_t CalleePopBytes = NumBytes;
3222   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3223                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3224                              InFlag, DL);
3225   if (!Ins.empty())
3226     InFlag = Chain.getValue(1);
3227 
3228   // Handle result values, copying them out of physregs into vregs that we
3229   // return.
3230   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3231                          InVals, IsThisReturn,
3232                          IsThisReturn ? OutVals[0] : SDValue());
3233 }
3234 
3235 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3236 // except for applying the wave size scale to the increment amount.
3237 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3238     SDValue Op, SelectionDAG &DAG) const {
3239   const MachineFunction &MF = DAG.getMachineFunction();
3240   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3241 
3242   SDLoc dl(Op);
3243   EVT VT = Op.getValueType();
3244   SDValue Tmp1 = Op;
3245   SDValue Tmp2 = Op.getValue(1);
3246   SDValue Tmp3 = Op.getOperand(2);
3247   SDValue Chain = Tmp1.getOperand(0);
3248 
3249   Register SPReg = Info->getStackPtrOffsetReg();
3250 
3251   // Chain the dynamic stack allocation so that it doesn't modify the stack
3252   // pointer when other instructions are using the stack.
3253   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3254 
3255   SDValue Size  = Tmp2.getOperand(1);
3256   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3257   Chain = SP.getValue(1);
3258   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3259   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3260   const TargetFrameLowering *TFL = ST.getFrameLowering();
3261   unsigned Opc =
3262     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3263     ISD::ADD : ISD::SUB;
3264 
3265   SDValue ScaledSize = DAG.getNode(
3266       ISD::SHL, dl, VT, Size,
3267       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3268 
3269   Align StackAlign = TFL->getStackAlign();
3270   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3271   if (Alignment && *Alignment > StackAlign) {
3272     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3273                        DAG.getConstant(-(uint64_t)Alignment->value()
3274                                            << ST.getWavefrontSizeLog2(),
3275                                        dl, VT));
3276   }
3277 
3278   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3279   Tmp2 = DAG.getCALLSEQ_END(
3280       Chain, DAG.getIntPtrConstant(0, dl, true),
3281       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3282 
3283   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3284 }
3285 
3286 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3287                                                   SelectionDAG &DAG) const {
3288   // We only handle constant sizes here to allow non-entry block, static sized
3289   // allocas. A truly dynamic value is more difficult to support because we
3290   // don't know if the size value is uniform or not. If the size isn't uniform,
3291   // we would need to do a wave reduction to get the maximum size to know how
3292   // much to increment the uniform stack pointer.
3293   SDValue Size = Op.getOperand(1);
3294   if (isa<ConstantSDNode>(Size))
3295       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3296 
3297   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3298 }
3299 
3300 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3301                                              const MachineFunction &MF) const {
3302   Register Reg = StringSwitch<Register>(RegName)
3303     .Case("m0", AMDGPU::M0)
3304     .Case("exec", AMDGPU::EXEC)
3305     .Case("exec_lo", AMDGPU::EXEC_LO)
3306     .Case("exec_hi", AMDGPU::EXEC_HI)
3307     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3308     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3309     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3310     .Default(Register());
3311 
3312   if (Reg == AMDGPU::NoRegister) {
3313     report_fatal_error(Twine("invalid register name \""
3314                              + StringRef(RegName)  + "\"."));
3315 
3316   }
3317 
3318   if (!Subtarget->hasFlatScrRegister() &&
3319        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3320     report_fatal_error(Twine("invalid register \""
3321                              + StringRef(RegName)  + "\" for subtarget."));
3322   }
3323 
3324   switch (Reg) {
3325   case AMDGPU::M0:
3326   case AMDGPU::EXEC_LO:
3327   case AMDGPU::EXEC_HI:
3328   case AMDGPU::FLAT_SCR_LO:
3329   case AMDGPU::FLAT_SCR_HI:
3330     if (VT.getSizeInBits() == 32)
3331       return Reg;
3332     break;
3333   case AMDGPU::EXEC:
3334   case AMDGPU::FLAT_SCR:
3335     if (VT.getSizeInBits() == 64)
3336       return Reg;
3337     break;
3338   default:
3339     llvm_unreachable("missing register type checking");
3340   }
3341 
3342   report_fatal_error(Twine("invalid type for register \""
3343                            + StringRef(RegName) + "\"."));
3344 }
3345 
3346 // If kill is not the last instruction, split the block so kill is always a
3347 // proper terminator.
3348 MachineBasicBlock *
3349 SITargetLowering::splitKillBlock(MachineInstr &MI,
3350                                  MachineBasicBlock *BB) const {
3351   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3352   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3353   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3354   return SplitBB;
3355 }
3356 
3357 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3358 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3359 // be the first instruction in the remainder block.
3360 //
3361 /// \returns { LoopBody, Remainder }
3362 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3363 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3364   MachineFunction *MF = MBB.getParent();
3365   MachineBasicBlock::iterator I(&MI);
3366 
3367   // To insert the loop we need to split the block. Move everything after this
3368   // point to a new block, and insert a new empty block between the two.
3369   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3370   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3371   MachineFunction::iterator MBBI(MBB);
3372   ++MBBI;
3373 
3374   MF->insert(MBBI, LoopBB);
3375   MF->insert(MBBI, RemainderBB);
3376 
3377   LoopBB->addSuccessor(LoopBB);
3378   LoopBB->addSuccessor(RemainderBB);
3379 
3380   // Move the rest of the block into a new block.
3381   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3382 
3383   if (InstInLoop) {
3384     auto Next = std::next(I);
3385 
3386     // Move instruction to loop body.
3387     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3388 
3389     // Move the rest of the block.
3390     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3391   } else {
3392     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3393   }
3394 
3395   MBB.addSuccessor(LoopBB);
3396 
3397   return std::make_pair(LoopBB, RemainderBB);
3398 }
3399 
3400 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3401 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3402   MachineBasicBlock *MBB = MI.getParent();
3403   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3404   auto I = MI.getIterator();
3405   auto E = std::next(I);
3406 
3407   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3408     .addImm(0);
3409 
3410   MIBundleBuilder Bundler(*MBB, I, E);
3411   finalizeBundle(*MBB, Bundler.begin());
3412 }
3413 
3414 MachineBasicBlock *
3415 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3416                                          MachineBasicBlock *BB) const {
3417   const DebugLoc &DL = MI.getDebugLoc();
3418 
3419   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3420 
3421   MachineBasicBlock *LoopBB;
3422   MachineBasicBlock *RemainderBB;
3423   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3424 
3425   // Apparently kill flags are only valid if the def is in the same block?
3426   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3427     Src->setIsKill(false);
3428 
3429   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3430 
3431   MachineBasicBlock::iterator I = LoopBB->end();
3432 
3433   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3434     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3435 
3436   // Clear TRAP_STS.MEM_VIOL
3437   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3438     .addImm(0)
3439     .addImm(EncodedReg);
3440 
3441   bundleInstWithWaitcnt(MI);
3442 
3443   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3444 
3445   // Load and check TRAP_STS.MEM_VIOL
3446   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3447     .addImm(EncodedReg);
3448 
3449   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3450   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3451     .addReg(Reg, RegState::Kill)
3452     .addImm(0);
3453   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3454     .addMBB(LoopBB);
3455 
3456   return RemainderBB;
3457 }
3458 
3459 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3460 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3461 // will only do one iteration. In the worst case, this will loop 64 times.
3462 //
3463 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3464 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3465   const SIInstrInfo *TII,
3466   MachineRegisterInfo &MRI,
3467   MachineBasicBlock &OrigBB,
3468   MachineBasicBlock &LoopBB,
3469   const DebugLoc &DL,
3470   const MachineOperand &IdxReg,
3471   unsigned InitReg,
3472   unsigned ResultReg,
3473   unsigned PhiReg,
3474   unsigned InitSaveExecReg,
3475   int Offset,
3476   bool UseGPRIdxMode,
3477   bool IsIndirectSrc) {
3478   MachineFunction *MF = OrigBB.getParent();
3479   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3480   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3481   MachineBasicBlock::iterator I = LoopBB.begin();
3482 
3483   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3484   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3485   Register NewExec = MRI.createVirtualRegister(BoolRC);
3486   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3487   Register CondReg = MRI.createVirtualRegister(BoolRC);
3488 
3489   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3490     .addReg(InitReg)
3491     .addMBB(&OrigBB)
3492     .addReg(ResultReg)
3493     .addMBB(&LoopBB);
3494 
3495   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3496     .addReg(InitSaveExecReg)
3497     .addMBB(&OrigBB)
3498     .addReg(NewExec)
3499     .addMBB(&LoopBB);
3500 
3501   // Read the next variant <- also loop target.
3502   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3503     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3504 
3505   // Compare the just read M0 value to all possible Idx values.
3506   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3507     .addReg(CurrentIdxReg)
3508     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3509 
3510   // Update EXEC, save the original EXEC value to VCC.
3511   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3512                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3513           NewExec)
3514     .addReg(CondReg, RegState::Kill);
3515 
3516   MRI.setSimpleHint(NewExec, CondReg);
3517 
3518   if (UseGPRIdxMode) {
3519     unsigned IdxReg;
3520     if (Offset == 0) {
3521       IdxReg = CurrentIdxReg;
3522     } else {
3523       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3524       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3525         .addReg(CurrentIdxReg, RegState::Kill)
3526         .addImm(Offset);
3527     }
3528     unsigned IdxMode = IsIndirectSrc ?
3529       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3530     MachineInstr *SetOn =
3531       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3532       .addReg(IdxReg, RegState::Kill)
3533       .addImm(IdxMode);
3534     SetOn->getOperand(3).setIsUndef();
3535   } else {
3536     // Move index from VCC into M0
3537     if (Offset == 0) {
3538       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3539         .addReg(CurrentIdxReg, RegState::Kill);
3540     } else {
3541       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3542         .addReg(CurrentIdxReg, RegState::Kill)
3543         .addImm(Offset);
3544     }
3545   }
3546 
3547   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3548   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3549   MachineInstr *InsertPt =
3550     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3551                                                   : AMDGPU::S_XOR_B64_term), Exec)
3552       .addReg(Exec)
3553       .addReg(NewExec);
3554 
3555   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3556   // s_cbranch_scc0?
3557 
3558   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3559   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3560     .addMBB(&LoopBB);
3561 
3562   return InsertPt->getIterator();
3563 }
3564 
3565 // This has slightly sub-optimal regalloc when the source vector is killed by
3566 // the read. The register allocator does not understand that the kill is
3567 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3568 // subregister from it, using 1 more VGPR than necessary. This was saved when
3569 // this was expanded after register allocation.
3570 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3571                                                   MachineBasicBlock &MBB,
3572                                                   MachineInstr &MI,
3573                                                   unsigned InitResultReg,
3574                                                   unsigned PhiReg,
3575                                                   int Offset,
3576                                                   bool UseGPRIdxMode,
3577                                                   bool IsIndirectSrc) {
3578   MachineFunction *MF = MBB.getParent();
3579   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3580   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3581   MachineRegisterInfo &MRI = MF->getRegInfo();
3582   const DebugLoc &DL = MI.getDebugLoc();
3583   MachineBasicBlock::iterator I(&MI);
3584 
3585   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3586   Register DstReg = MI.getOperand(0).getReg();
3587   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3588   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3589   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3590   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3591 
3592   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3593 
3594   // Save the EXEC mask
3595   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3596     .addReg(Exec);
3597 
3598   MachineBasicBlock *LoopBB;
3599   MachineBasicBlock *RemainderBB;
3600   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3601 
3602   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3603 
3604   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3605                                       InitResultReg, DstReg, PhiReg, TmpExec,
3606                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3607   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3608   MachineFunction::iterator MBBI(LoopBB);
3609   ++MBBI;
3610   MF->insert(MBBI, LandingPad);
3611   LoopBB->removeSuccessor(RemainderBB);
3612   LandingPad->addSuccessor(RemainderBB);
3613   LoopBB->addSuccessor(LandingPad);
3614   MachineBasicBlock::iterator First = LandingPad->begin();
3615   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3616     .addReg(SaveExec);
3617 
3618   return InsPt;
3619 }
3620 
3621 // Returns subreg index, offset
3622 static std::pair<unsigned, int>
3623 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3624                             const TargetRegisterClass *SuperRC,
3625                             unsigned VecReg,
3626                             int Offset) {
3627   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3628 
3629   // Skip out of bounds offsets, or else we would end up using an undefined
3630   // register.
3631   if (Offset >= NumElts || Offset < 0)
3632     return std::make_pair(AMDGPU::sub0, Offset);
3633 
3634   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3635 }
3636 
3637 // Return true if the index is an SGPR and was set.
3638 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3639                                  MachineRegisterInfo &MRI,
3640                                  MachineInstr &MI,
3641                                  int Offset,
3642                                  bool UseGPRIdxMode,
3643                                  bool IsIndirectSrc) {
3644   MachineBasicBlock *MBB = MI.getParent();
3645   const DebugLoc &DL = MI.getDebugLoc();
3646   MachineBasicBlock::iterator I(&MI);
3647 
3648   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3649   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3650 
3651   assert(Idx->getReg() != AMDGPU::NoRegister);
3652 
3653   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3654     return false;
3655 
3656   if (UseGPRIdxMode) {
3657     unsigned IdxMode = IsIndirectSrc ?
3658       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3659     if (Offset == 0) {
3660       MachineInstr *SetOn =
3661           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3662               .add(*Idx)
3663               .addImm(IdxMode);
3664 
3665       SetOn->getOperand(3).setIsUndef();
3666     } else {
3667       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3668       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3669           .add(*Idx)
3670           .addImm(Offset);
3671       MachineInstr *SetOn =
3672         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3673         .addReg(Tmp, RegState::Kill)
3674         .addImm(IdxMode);
3675 
3676       SetOn->getOperand(3).setIsUndef();
3677     }
3678 
3679     return true;
3680   }
3681 
3682   if (Offset == 0) {
3683     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3684       .add(*Idx);
3685   } else {
3686     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3687       .add(*Idx)
3688       .addImm(Offset);
3689   }
3690 
3691   return true;
3692 }
3693 
3694 // Control flow needs to be inserted if indexing with a VGPR.
3695 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3696                                           MachineBasicBlock &MBB,
3697                                           const GCNSubtarget &ST) {
3698   const SIInstrInfo *TII = ST.getInstrInfo();
3699   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3700   MachineFunction *MF = MBB.getParent();
3701   MachineRegisterInfo &MRI = MF->getRegInfo();
3702 
3703   Register Dst = MI.getOperand(0).getReg();
3704   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3705   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3706 
3707   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3708 
3709   unsigned SubReg;
3710   std::tie(SubReg, Offset)
3711     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3712 
3713   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3714 
3715   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3716     MachineBasicBlock::iterator I(&MI);
3717     const DebugLoc &DL = MI.getDebugLoc();
3718 
3719     if (UseGPRIdxMode) {
3720       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3721       // to avoid interfering with other uses, so probably requires a new
3722       // optimization pass.
3723       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3724         .addReg(SrcReg, 0, SubReg)
3725         .addReg(SrcReg, RegState::Implicit)
3726         .addReg(AMDGPU::M0, RegState::Implicit);
3727       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3728     } else {
3729       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3730         .addReg(SrcReg, 0, SubReg)
3731         .addReg(SrcReg, RegState::Implicit);
3732     }
3733 
3734     MI.eraseFromParent();
3735 
3736     return &MBB;
3737   }
3738 
3739   const DebugLoc &DL = MI.getDebugLoc();
3740   MachineBasicBlock::iterator I(&MI);
3741 
3742   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3743   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3744 
3745   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3746 
3747   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3748                               Offset, UseGPRIdxMode, true);
3749   MachineBasicBlock *LoopBB = InsPt->getParent();
3750 
3751   if (UseGPRIdxMode) {
3752     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3753       .addReg(SrcReg, 0, SubReg)
3754       .addReg(SrcReg, RegState::Implicit)
3755       .addReg(AMDGPU::M0, RegState::Implicit);
3756     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3757   } else {
3758     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3759       .addReg(SrcReg, 0, SubReg)
3760       .addReg(SrcReg, RegState::Implicit);
3761   }
3762 
3763   MI.eraseFromParent();
3764 
3765   return LoopBB;
3766 }
3767 
3768 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3769                                           MachineBasicBlock &MBB,
3770                                           const GCNSubtarget &ST) {
3771   const SIInstrInfo *TII = ST.getInstrInfo();
3772   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3773   MachineFunction *MF = MBB.getParent();
3774   MachineRegisterInfo &MRI = MF->getRegInfo();
3775 
3776   Register Dst = MI.getOperand(0).getReg();
3777   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3778   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3779   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3780   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3781   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3782 
3783   // This can be an immediate, but will be folded later.
3784   assert(Val->getReg());
3785 
3786   unsigned SubReg;
3787   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3788                                                          SrcVec->getReg(),
3789                                                          Offset);
3790   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3791 
3792   if (Idx->getReg() == AMDGPU::NoRegister) {
3793     MachineBasicBlock::iterator I(&MI);
3794     const DebugLoc &DL = MI.getDebugLoc();
3795 
3796     assert(Offset == 0);
3797 
3798     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3799         .add(*SrcVec)
3800         .add(*Val)
3801         .addImm(SubReg);
3802 
3803     MI.eraseFromParent();
3804     return &MBB;
3805   }
3806 
3807   const MCInstrDesc &MovRelDesc
3808     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3809 
3810   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3811     MachineBasicBlock::iterator I(&MI);
3812     const DebugLoc &DL = MI.getDebugLoc();
3813     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3814       .addReg(SrcVec->getReg())
3815       .add(*Val)
3816       .addImm(SubReg);
3817     if (UseGPRIdxMode)
3818       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3819 
3820     MI.eraseFromParent();
3821     return &MBB;
3822   }
3823 
3824   if (Val->isReg())
3825     MRI.clearKillFlags(Val->getReg());
3826 
3827   const DebugLoc &DL = MI.getDebugLoc();
3828 
3829   Register PhiReg = MRI.createVirtualRegister(VecRC);
3830 
3831   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3832                               Offset, UseGPRIdxMode, false);
3833   MachineBasicBlock *LoopBB = InsPt->getParent();
3834 
3835   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3836     .addReg(PhiReg)
3837     .add(*Val)
3838     .addImm(AMDGPU::sub0);
3839   if (UseGPRIdxMode)
3840     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3841 
3842   MI.eraseFromParent();
3843   return LoopBB;
3844 }
3845 
3846 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3847   MachineInstr &MI, MachineBasicBlock *BB) const {
3848 
3849   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3850   MachineFunction *MF = BB->getParent();
3851   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3852 
3853   switch (MI.getOpcode()) {
3854   case AMDGPU::S_UADDO_PSEUDO:
3855   case AMDGPU::S_USUBO_PSEUDO: {
3856     const DebugLoc &DL = MI.getDebugLoc();
3857     MachineOperand &Dest0 = MI.getOperand(0);
3858     MachineOperand &Dest1 = MI.getOperand(1);
3859     MachineOperand &Src0 = MI.getOperand(2);
3860     MachineOperand &Src1 = MI.getOperand(3);
3861 
3862     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3863                        ? AMDGPU::S_ADD_I32
3864                        : AMDGPU::S_SUB_I32;
3865     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3866 
3867     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3868         .addImm(1)
3869         .addImm(0);
3870 
3871     MI.eraseFromParent();
3872     return BB;
3873   }
3874   case AMDGPU::S_ADD_U64_PSEUDO:
3875   case AMDGPU::S_SUB_U64_PSEUDO: {
3876     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3877     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3878     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3879     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3880     const DebugLoc &DL = MI.getDebugLoc();
3881 
3882     MachineOperand &Dest = MI.getOperand(0);
3883     MachineOperand &Src0 = MI.getOperand(1);
3884     MachineOperand &Src1 = MI.getOperand(2);
3885 
3886     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3887     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3888 
3889     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3890         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3891     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3892         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3893 
3894     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3895         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3896     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3897         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3898 
3899     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3900 
3901     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3902     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3903     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3904     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3905     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3906         .addReg(DestSub0)
3907         .addImm(AMDGPU::sub0)
3908         .addReg(DestSub1)
3909         .addImm(AMDGPU::sub1);
3910     MI.eraseFromParent();
3911     return BB;
3912   }
3913   case AMDGPU::V_ADD_U64_PSEUDO:
3914   case AMDGPU::V_SUB_U64_PSEUDO: {
3915     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3916     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3917     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3918     const DebugLoc &DL = MI.getDebugLoc();
3919 
3920     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3921 
3922     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3923 
3924     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3925     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3926 
3927     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3928     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3929 
3930     MachineOperand &Dest = MI.getOperand(0);
3931     MachineOperand &Src0 = MI.getOperand(1);
3932     MachineOperand &Src1 = MI.getOperand(2);
3933 
3934     const TargetRegisterClass *Src0RC = Src0.isReg()
3935                                             ? MRI.getRegClass(Src0.getReg())
3936                                             : &AMDGPU::VReg_64RegClass;
3937     const TargetRegisterClass *Src1RC = Src1.isReg()
3938                                             ? MRI.getRegClass(Src1.getReg())
3939                                             : &AMDGPU::VReg_64RegClass;
3940 
3941     const TargetRegisterClass *Src0SubRC =
3942         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3943     const TargetRegisterClass *Src1SubRC =
3944         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3945 
3946     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3947         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3948     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3949         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3950 
3951     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3952         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3953     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3954         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3955 
3956     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3957     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3958                                .addReg(CarryReg, RegState::Define)
3959                                .add(SrcReg0Sub0)
3960                                .add(SrcReg1Sub0)
3961                                .addImm(0); // clamp bit
3962 
3963     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3964     MachineInstr *HiHalf =
3965         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3966             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3967             .add(SrcReg0Sub1)
3968             .add(SrcReg1Sub1)
3969             .addReg(CarryReg, RegState::Kill)
3970             .addImm(0); // clamp bit
3971 
3972     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3973         .addReg(DestSub0)
3974         .addImm(AMDGPU::sub0)
3975         .addReg(DestSub1)
3976         .addImm(AMDGPU::sub1);
3977     TII->legalizeOperands(*LoHalf);
3978     TII->legalizeOperands(*HiHalf);
3979     MI.eraseFromParent();
3980     return BB;
3981   }
3982   case AMDGPU::S_ADD_CO_PSEUDO:
3983   case AMDGPU::S_SUB_CO_PSEUDO: {
3984     // This pseudo has a chance to be selected
3985     // only from uniform add/subcarry node. All the VGPR operands
3986     // therefore assumed to be splat vectors.
3987     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3988     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3989     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3990     MachineBasicBlock::iterator MII = MI;
3991     const DebugLoc &DL = MI.getDebugLoc();
3992     MachineOperand &Dest = MI.getOperand(0);
3993     MachineOperand &CarryDest = MI.getOperand(1);
3994     MachineOperand &Src0 = MI.getOperand(2);
3995     MachineOperand &Src1 = MI.getOperand(3);
3996     MachineOperand &Src2 = MI.getOperand(4);
3997     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3998                        ? AMDGPU::S_ADDC_U32
3999                        : AMDGPU::S_SUBB_U32;
4000     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4001       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4002       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4003           .addReg(Src0.getReg());
4004       Src0.setReg(RegOp0);
4005     }
4006     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4007       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4008       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4009           .addReg(Src1.getReg());
4010       Src1.setReg(RegOp1);
4011     }
4012     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4013     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4014       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4015           .addReg(Src2.getReg());
4016       Src2.setReg(RegOp2);
4017     }
4018 
4019     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4020     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4021       if (ST.hasScalarCompareEq64()) {
4022         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4023             .addReg(Src2.getReg())
4024             .addImm(0);
4025       } else {
4026         const TargetRegisterClass *SubRC =
4027             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4028         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4029             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4030         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4031             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4032         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4033 
4034         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4035             .add(Src2Sub0)
4036             .add(Src2Sub1);
4037 
4038         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4039             .addReg(Src2_32, RegState::Kill)
4040             .addImm(0);
4041       }
4042     } else {
4043       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4044           .addReg(Src2.getReg())
4045           .addImm(0);
4046     }
4047 
4048     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4049 
4050     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4051       .addReg(AMDGPU::SCC);
4052     MI.eraseFromParent();
4053     return BB;
4054   }
4055   case AMDGPU::SI_INIT_M0: {
4056     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4057             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4058         .add(MI.getOperand(0));
4059     MI.eraseFromParent();
4060     return BB;
4061   }
4062   case AMDGPU::SI_INIT_EXEC:
4063     // This should be before all vector instructions.
4064     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
4065             AMDGPU::EXEC)
4066         .addImm(MI.getOperand(0).getImm());
4067     MI.eraseFromParent();
4068     return BB;
4069 
4070   case AMDGPU::SI_INIT_EXEC_LO:
4071     // This should be before all vector instructions.
4072     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
4073             AMDGPU::EXEC_LO)
4074         .addImm(MI.getOperand(0).getImm());
4075     MI.eraseFromParent();
4076     return BB;
4077 
4078   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
4079     // Extract the thread count from an SGPR input and set EXEC accordingly.
4080     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
4081     //
4082     // S_BFE_U32 count, input, {shift, 7}
4083     // S_BFM_B64 exec, count, 0
4084     // S_CMP_EQ_U32 count, 64
4085     // S_CMOV_B64 exec, -1
4086     MachineInstr *FirstMI = &*BB->begin();
4087     MachineRegisterInfo &MRI = MF->getRegInfo();
4088     Register InputReg = MI.getOperand(0).getReg();
4089     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4090     bool Found = false;
4091 
4092     // Move the COPY of the input reg to the beginning, so that we can use it.
4093     for (auto I = BB->begin(); I != &MI; I++) {
4094       if (I->getOpcode() != TargetOpcode::COPY ||
4095           I->getOperand(0).getReg() != InputReg)
4096         continue;
4097 
4098       if (I == FirstMI) {
4099         FirstMI = &*++BB->begin();
4100       } else {
4101         I->removeFromParent();
4102         BB->insert(FirstMI, &*I);
4103       }
4104       Found = true;
4105       break;
4106     }
4107     assert(Found);
4108     (void)Found;
4109 
4110     // This should be before all vector instructions.
4111     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4112     bool isWave32 = getSubtarget()->isWave32();
4113     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4114     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4115         .addReg(InputReg)
4116         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4117     BuildMI(*BB, FirstMI, DebugLoc(),
4118             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4119             Exec)
4120         .addReg(CountReg)
4121         .addImm(0);
4122     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4123         .addReg(CountReg, RegState::Kill)
4124         .addImm(getSubtarget()->getWavefrontSize());
4125     BuildMI(*BB, FirstMI, DebugLoc(),
4126             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4127             Exec)
4128         .addImm(-1);
4129     MI.eraseFromParent();
4130     return BB;
4131   }
4132 
4133   case AMDGPU::GET_GROUPSTATICSIZE: {
4134     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4135            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4136     DebugLoc DL = MI.getDebugLoc();
4137     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4138         .add(MI.getOperand(0))
4139         .addImm(MFI->getLDSSize());
4140     MI.eraseFromParent();
4141     return BB;
4142   }
4143   case AMDGPU::SI_INDIRECT_SRC_V1:
4144   case AMDGPU::SI_INDIRECT_SRC_V2:
4145   case AMDGPU::SI_INDIRECT_SRC_V4:
4146   case AMDGPU::SI_INDIRECT_SRC_V8:
4147   case AMDGPU::SI_INDIRECT_SRC_V16:
4148   case AMDGPU::SI_INDIRECT_SRC_V32:
4149     return emitIndirectSrc(MI, *BB, *getSubtarget());
4150   case AMDGPU::SI_INDIRECT_DST_V1:
4151   case AMDGPU::SI_INDIRECT_DST_V2:
4152   case AMDGPU::SI_INDIRECT_DST_V4:
4153   case AMDGPU::SI_INDIRECT_DST_V8:
4154   case AMDGPU::SI_INDIRECT_DST_V16:
4155   case AMDGPU::SI_INDIRECT_DST_V32:
4156     return emitIndirectDst(MI, *BB, *getSubtarget());
4157   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4158   case AMDGPU::SI_KILL_I1_PSEUDO:
4159     return splitKillBlock(MI, BB);
4160   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4161     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4162     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4163     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4164 
4165     Register Dst = MI.getOperand(0).getReg();
4166     Register Src0 = MI.getOperand(1).getReg();
4167     Register Src1 = MI.getOperand(2).getReg();
4168     const DebugLoc &DL = MI.getDebugLoc();
4169     Register SrcCond = MI.getOperand(3).getReg();
4170 
4171     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4172     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4173     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4174     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4175 
4176     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4177       .addReg(SrcCond);
4178     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4179       .addImm(0)
4180       .addReg(Src0, 0, AMDGPU::sub0)
4181       .addImm(0)
4182       .addReg(Src1, 0, AMDGPU::sub0)
4183       .addReg(SrcCondCopy);
4184     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4185       .addImm(0)
4186       .addReg(Src0, 0, AMDGPU::sub1)
4187       .addImm(0)
4188       .addReg(Src1, 0, AMDGPU::sub1)
4189       .addReg(SrcCondCopy);
4190 
4191     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4192       .addReg(DstLo)
4193       .addImm(AMDGPU::sub0)
4194       .addReg(DstHi)
4195       .addImm(AMDGPU::sub1);
4196     MI.eraseFromParent();
4197     return BB;
4198   }
4199   case AMDGPU::SI_BR_UNDEF: {
4200     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4201     const DebugLoc &DL = MI.getDebugLoc();
4202     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4203                            .add(MI.getOperand(0));
4204     Br->getOperand(1).setIsUndef(true); // read undef SCC
4205     MI.eraseFromParent();
4206     return BB;
4207   }
4208   case AMDGPU::ADJCALLSTACKUP:
4209   case AMDGPU::ADJCALLSTACKDOWN: {
4210     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4211     MachineInstrBuilder MIB(*MF, &MI);
4212     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4213        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4214     return BB;
4215   }
4216   case AMDGPU::SI_CALL_ISEL: {
4217     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4218     const DebugLoc &DL = MI.getDebugLoc();
4219 
4220     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4221 
4222     MachineInstrBuilder MIB;
4223     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4224 
4225     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4226       MIB.add(MI.getOperand(I));
4227 
4228     MIB.cloneMemRefs(MI);
4229     MI.eraseFromParent();
4230     return BB;
4231   }
4232   case AMDGPU::V_ADD_CO_U32_e32:
4233   case AMDGPU::V_SUB_CO_U32_e32:
4234   case AMDGPU::V_SUBREV_CO_U32_e32: {
4235     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4236     const DebugLoc &DL = MI.getDebugLoc();
4237     unsigned Opc = MI.getOpcode();
4238 
4239     bool NeedClampOperand = false;
4240     if (TII->pseudoToMCOpcode(Opc) == -1) {
4241       Opc = AMDGPU::getVOPe64(Opc);
4242       NeedClampOperand = true;
4243     }
4244 
4245     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4246     if (TII->isVOP3(*I)) {
4247       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4248       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4249       I.addReg(TRI->getVCC(), RegState::Define);
4250     }
4251     I.add(MI.getOperand(1))
4252      .add(MI.getOperand(2));
4253     if (NeedClampOperand)
4254       I.addImm(0); // clamp bit for e64 encoding
4255 
4256     TII->legalizeOperands(*I);
4257 
4258     MI.eraseFromParent();
4259     return BB;
4260   }
4261   case AMDGPU::DS_GWS_INIT:
4262   case AMDGPU::DS_GWS_SEMA_V:
4263   case AMDGPU::DS_GWS_SEMA_BR:
4264   case AMDGPU::DS_GWS_SEMA_P:
4265   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4266   case AMDGPU::DS_GWS_BARRIER:
4267     // A s_waitcnt 0 is required to be the instruction immediately following.
4268     if (getSubtarget()->hasGWSAutoReplay()) {
4269       bundleInstWithWaitcnt(MI);
4270       return BB;
4271     }
4272 
4273     return emitGWSMemViolTestLoop(MI, BB);
4274   case AMDGPU::S_SETREG_B32: {
4275     // Try to optimize cases that only set the denormal mode or rounding mode.
4276     //
4277     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4278     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4279     // instead.
4280     //
4281     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4282     // allow you to have a no side effect instruction in the output of a
4283     // sideeffecting pattern.
4284     unsigned ID, Offset, Width;
4285     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4286     if (ID != AMDGPU::Hwreg::ID_MODE)
4287       return BB;
4288 
4289     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4290     const unsigned SetMask = WidthMask << Offset;
4291 
4292     if (getSubtarget()->hasDenormModeInst()) {
4293       unsigned SetDenormOp = 0;
4294       unsigned SetRoundOp = 0;
4295 
4296       // The dedicated instructions can only set the whole denorm or round mode
4297       // at once, not a subset of bits in either.
4298       if (SetMask ==
4299           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4300         // If this fully sets both the round and denorm mode, emit the two
4301         // dedicated instructions for these.
4302         SetRoundOp = AMDGPU::S_ROUND_MODE;
4303         SetDenormOp = AMDGPU::S_DENORM_MODE;
4304       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4305         SetRoundOp = AMDGPU::S_ROUND_MODE;
4306       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4307         SetDenormOp = AMDGPU::S_DENORM_MODE;
4308       }
4309 
4310       if (SetRoundOp || SetDenormOp) {
4311         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4312         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4313         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4314           unsigned ImmVal = Def->getOperand(1).getImm();
4315           if (SetRoundOp) {
4316             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4317                 .addImm(ImmVal & 0xf);
4318 
4319             // If we also have the denorm mode, get just the denorm mode bits.
4320             ImmVal >>= 4;
4321           }
4322 
4323           if (SetDenormOp) {
4324             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4325                 .addImm(ImmVal & 0xf);
4326           }
4327 
4328           MI.eraseFromParent();
4329           return BB;
4330         }
4331       }
4332     }
4333 
4334     // If only FP bits are touched, used the no side effects pseudo.
4335     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4336                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4337       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4338 
4339     return BB;
4340   }
4341   default:
4342     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4343   }
4344 }
4345 
4346 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4347   return isTypeLegal(VT.getScalarType());
4348 }
4349 
4350 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4351   // This currently forces unfolding various combinations of fsub into fma with
4352   // free fneg'd operands. As long as we have fast FMA (controlled by
4353   // isFMAFasterThanFMulAndFAdd), we should perform these.
4354 
4355   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4356   // most of these combines appear to be cycle neutral but save on instruction
4357   // count / code size.
4358   return true;
4359 }
4360 
4361 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4362                                          EVT VT) const {
4363   if (!VT.isVector()) {
4364     return MVT::i1;
4365   }
4366   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4367 }
4368 
4369 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4370   // TODO: Should i16 be used always if legal? For now it would force VALU
4371   // shifts.
4372   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4373 }
4374 
4375 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4376   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4377              ? Ty.changeElementSize(16)
4378              : Ty.changeElementSize(32);
4379 }
4380 
4381 // Answering this is somewhat tricky and depends on the specific device which
4382 // have different rates for fma or all f64 operations.
4383 //
4384 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4385 // regardless of which device (although the number of cycles differs between
4386 // devices), so it is always profitable for f64.
4387 //
4388 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4389 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4390 // which we can always do even without fused FP ops since it returns the same
4391 // result as the separate operations and since it is always full
4392 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4393 // however does not support denormals, so we do report fma as faster if we have
4394 // a fast fma device and require denormals.
4395 //
4396 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4397                                                   EVT VT) const {
4398   VT = VT.getScalarType();
4399 
4400   switch (VT.getSimpleVT().SimpleTy) {
4401   case MVT::f32: {
4402     // If mad is not available this depends only on if f32 fma is full rate.
4403     if (!Subtarget->hasMadMacF32Insts())
4404       return Subtarget->hasFastFMAF32();
4405 
4406     // Otherwise f32 mad is always full rate and returns the same result as
4407     // the separate operations so should be preferred over fma.
4408     // However does not support denomals.
4409     if (hasFP32Denormals(MF))
4410       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4411 
4412     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4413     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4414   }
4415   case MVT::f64:
4416     return true;
4417   case MVT::f16:
4418     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4419   default:
4420     break;
4421   }
4422 
4423   return false;
4424 }
4425 
4426 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4427                                    const SDNode *N) const {
4428   // TODO: Check future ftz flag
4429   // v_mad_f32/v_mac_f32 do not support denormals.
4430   EVT VT = N->getValueType(0);
4431   if (VT == MVT::f32)
4432     return Subtarget->hasMadMacF32Insts() &&
4433            !hasFP32Denormals(DAG.getMachineFunction());
4434   if (VT == MVT::f16) {
4435     return Subtarget->hasMadF16() &&
4436            !hasFP64FP16Denormals(DAG.getMachineFunction());
4437   }
4438 
4439   return false;
4440 }
4441 
4442 //===----------------------------------------------------------------------===//
4443 // Custom DAG Lowering Operations
4444 //===----------------------------------------------------------------------===//
4445 
4446 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4447 // wider vector type is legal.
4448 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4449                                              SelectionDAG &DAG) const {
4450   unsigned Opc = Op.getOpcode();
4451   EVT VT = Op.getValueType();
4452   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4453 
4454   SDValue Lo, Hi;
4455   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4456 
4457   SDLoc SL(Op);
4458   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4459                              Op->getFlags());
4460   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4461                              Op->getFlags());
4462 
4463   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4464 }
4465 
4466 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4467 // wider vector type is legal.
4468 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4469                                               SelectionDAG &DAG) const {
4470   unsigned Opc = Op.getOpcode();
4471   EVT VT = Op.getValueType();
4472   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4473 
4474   SDValue Lo0, Hi0;
4475   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4476   SDValue Lo1, Hi1;
4477   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4478 
4479   SDLoc SL(Op);
4480 
4481   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4482                              Op->getFlags());
4483   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4484                              Op->getFlags());
4485 
4486   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4487 }
4488 
4489 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4490                                               SelectionDAG &DAG) const {
4491   unsigned Opc = Op.getOpcode();
4492   EVT VT = Op.getValueType();
4493   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4494 
4495   SDValue Lo0, Hi0;
4496   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4497   SDValue Lo1, Hi1;
4498   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4499   SDValue Lo2, Hi2;
4500   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4501 
4502   SDLoc SL(Op);
4503 
4504   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4505                              Op->getFlags());
4506   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4507                              Op->getFlags());
4508 
4509   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4510 }
4511 
4512 
4513 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4514   switch (Op.getOpcode()) {
4515   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4516   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4517   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4518   case ISD::LOAD: {
4519     SDValue Result = LowerLOAD(Op, DAG);
4520     assert((!Result.getNode() ||
4521             Result.getNode()->getNumValues() == 2) &&
4522            "Load should return a value and a chain");
4523     return Result;
4524   }
4525 
4526   case ISD::FSIN:
4527   case ISD::FCOS:
4528     return LowerTrig(Op, DAG);
4529   case ISD::SELECT: return LowerSELECT(Op, DAG);
4530   case ISD::FDIV: return LowerFDIV(Op, DAG);
4531   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4532   case ISD::STORE: return LowerSTORE(Op, DAG);
4533   case ISD::GlobalAddress: {
4534     MachineFunction &MF = DAG.getMachineFunction();
4535     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4536     return LowerGlobalAddress(MFI, Op, DAG);
4537   }
4538   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4539   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4540   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4541   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4542   case ISD::INSERT_SUBVECTOR:
4543     return lowerINSERT_SUBVECTOR(Op, DAG);
4544   case ISD::INSERT_VECTOR_ELT:
4545     return lowerINSERT_VECTOR_ELT(Op, DAG);
4546   case ISD::EXTRACT_VECTOR_ELT:
4547     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4548   case ISD::VECTOR_SHUFFLE:
4549     return lowerVECTOR_SHUFFLE(Op, DAG);
4550   case ISD::BUILD_VECTOR:
4551     return lowerBUILD_VECTOR(Op, DAG);
4552   case ISD::FP_ROUND:
4553     return lowerFP_ROUND(Op, DAG);
4554   case ISD::TRAP:
4555     return lowerTRAP(Op, DAG);
4556   case ISD::DEBUGTRAP:
4557     return lowerDEBUGTRAP(Op, DAG);
4558   case ISD::FABS:
4559   case ISD::FNEG:
4560   case ISD::FCANONICALIZE:
4561   case ISD::BSWAP:
4562     return splitUnaryVectorOp(Op, DAG);
4563   case ISD::FMINNUM:
4564   case ISD::FMAXNUM:
4565     return lowerFMINNUM_FMAXNUM(Op, DAG);
4566   case ISD::FMA:
4567     return splitTernaryVectorOp(Op, DAG);
4568   case ISD::SHL:
4569   case ISD::SRA:
4570   case ISD::SRL:
4571   case ISD::ADD:
4572   case ISD::SUB:
4573   case ISD::MUL:
4574   case ISD::SMIN:
4575   case ISD::SMAX:
4576   case ISD::UMIN:
4577   case ISD::UMAX:
4578   case ISD::FADD:
4579   case ISD::FMUL:
4580   case ISD::FMINNUM_IEEE:
4581   case ISD::FMAXNUM_IEEE:
4582   case ISD::UADDSAT:
4583   case ISD::USUBSAT:
4584   case ISD::SADDSAT:
4585   case ISD::SSUBSAT:
4586     return splitBinaryVectorOp(Op, DAG);
4587   case ISD::SMULO:
4588   case ISD::UMULO:
4589     return lowerXMULO(Op, DAG);
4590   case ISD::DYNAMIC_STACKALLOC:
4591     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4592   }
4593   return SDValue();
4594 }
4595 
4596 // Used for D16: Casts the result of an instruction into the right vector,
4597 // packs values if loads return unpacked values.
4598 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4599                                        const SDLoc &DL,
4600                                        SelectionDAG &DAG, bool Unpacked) {
4601   if (!LoadVT.isVector())
4602     return Result;
4603 
4604   // Cast back to the original packed type or to a larger type that is a
4605   // multiple of 32 bit for D16. Widening the return type is a required for
4606   // legalization.
4607   EVT FittingLoadVT = LoadVT;
4608   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4609     FittingLoadVT =
4610         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4611                          LoadVT.getVectorNumElements() + 1);
4612   }
4613 
4614   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4615     // Truncate to v2i16/v4i16.
4616     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4617 
4618     // Workaround legalizer not scalarizing truncate after vector op
4619     // legalization but not creating intermediate vector trunc.
4620     SmallVector<SDValue, 4> Elts;
4621     DAG.ExtractVectorElements(Result, Elts);
4622     for (SDValue &Elt : Elts)
4623       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4624 
4625     // Pad illegal v1i16/v3fi6 to v4i16
4626     if ((LoadVT.getVectorNumElements() % 2) == 1)
4627       Elts.push_back(DAG.getUNDEF(MVT::i16));
4628 
4629     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4630 
4631     // Bitcast to original type (v2f16/v4f16).
4632     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4633   }
4634 
4635   // Cast back to the original packed type.
4636   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4637 }
4638 
4639 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4640                                               MemSDNode *M,
4641                                               SelectionDAG &DAG,
4642                                               ArrayRef<SDValue> Ops,
4643                                               bool IsIntrinsic) const {
4644   SDLoc DL(M);
4645 
4646   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4647   EVT LoadVT = M->getValueType(0);
4648 
4649   EVT EquivLoadVT = LoadVT;
4650   if (LoadVT.isVector()) {
4651     if (Unpacked) {
4652       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4653                                      LoadVT.getVectorNumElements());
4654     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4655       // Widen v3f16 to legal type
4656       EquivLoadVT =
4657           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4658                            LoadVT.getVectorNumElements() + 1);
4659     }
4660   }
4661 
4662   // Change from v4f16/v2f16 to EquivLoadVT.
4663   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4664 
4665   SDValue Load
4666     = DAG.getMemIntrinsicNode(
4667       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4668       VTList, Ops, M->getMemoryVT(),
4669       M->getMemOperand());
4670 
4671   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4672 
4673   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4674 }
4675 
4676 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4677                                              SelectionDAG &DAG,
4678                                              ArrayRef<SDValue> Ops) const {
4679   SDLoc DL(M);
4680   EVT LoadVT = M->getValueType(0);
4681   EVT EltType = LoadVT.getScalarType();
4682   EVT IntVT = LoadVT.changeTypeToInteger();
4683 
4684   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4685 
4686   unsigned Opc =
4687       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4688 
4689   if (IsD16) {
4690     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4691   }
4692 
4693   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4694   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4695     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4696 
4697   if (isTypeLegal(LoadVT)) {
4698     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4699                                M->getMemOperand(), DAG);
4700   }
4701 
4702   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4703   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4704   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4705                                         M->getMemOperand(), DAG);
4706   return DAG.getMergeValues(
4707       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4708       DL);
4709 }
4710 
4711 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4712                                   SDNode *N, SelectionDAG &DAG) {
4713   EVT VT = N->getValueType(0);
4714   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4715   unsigned CondCode = CD->getZExtValue();
4716   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4717     return DAG.getUNDEF(VT);
4718 
4719   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4720 
4721   SDValue LHS = N->getOperand(1);
4722   SDValue RHS = N->getOperand(2);
4723 
4724   SDLoc DL(N);
4725 
4726   EVT CmpVT = LHS.getValueType();
4727   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4728     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4729       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4730     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4731     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4732   }
4733 
4734   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4735 
4736   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4737   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4738 
4739   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4740                               DAG.getCondCode(CCOpcode));
4741   if (VT.bitsEq(CCVT))
4742     return SetCC;
4743   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4744 }
4745 
4746 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4747                                   SDNode *N, SelectionDAG &DAG) {
4748   EVT VT = N->getValueType(0);
4749   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4750 
4751   unsigned CondCode = CD->getZExtValue();
4752   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4753     return DAG.getUNDEF(VT);
4754 
4755   SDValue Src0 = N->getOperand(1);
4756   SDValue Src1 = N->getOperand(2);
4757   EVT CmpVT = Src0.getValueType();
4758   SDLoc SL(N);
4759 
4760   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4761     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4762     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4763   }
4764 
4765   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4766   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4767   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4768   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4769   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4770                               Src1, DAG.getCondCode(CCOpcode));
4771   if (VT.bitsEq(CCVT))
4772     return SetCC;
4773   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4774 }
4775 
4776 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4777                                     SelectionDAG &DAG) {
4778   EVT VT = N->getValueType(0);
4779   SDValue Src = N->getOperand(1);
4780   SDLoc SL(N);
4781 
4782   if (Src.getOpcode() == ISD::SETCC) {
4783     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4784     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4785                        Src.getOperand(1), Src.getOperand(2));
4786   }
4787   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4788     // (ballot 0) -> 0
4789     if (Arg->isNullValue())
4790       return DAG.getConstant(0, SL, VT);
4791 
4792     // (ballot 1) -> EXEC/EXEC_LO
4793     if (Arg->isOne()) {
4794       Register Exec;
4795       if (VT.getScalarSizeInBits() == 32)
4796         Exec = AMDGPU::EXEC_LO;
4797       else if (VT.getScalarSizeInBits() == 64)
4798         Exec = AMDGPU::EXEC;
4799       else
4800         return SDValue();
4801 
4802       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4803     }
4804   }
4805 
4806   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4807   // ISD::SETNE)
4808   return DAG.getNode(
4809       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4810       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4811 }
4812 
4813 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4814                                           SmallVectorImpl<SDValue> &Results,
4815                                           SelectionDAG &DAG) const {
4816   switch (N->getOpcode()) {
4817   case ISD::INSERT_VECTOR_ELT: {
4818     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4819       Results.push_back(Res);
4820     return;
4821   }
4822   case ISD::EXTRACT_VECTOR_ELT: {
4823     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4824       Results.push_back(Res);
4825     return;
4826   }
4827   case ISD::INTRINSIC_WO_CHAIN: {
4828     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4829     switch (IID) {
4830     case Intrinsic::amdgcn_cvt_pkrtz: {
4831       SDValue Src0 = N->getOperand(1);
4832       SDValue Src1 = N->getOperand(2);
4833       SDLoc SL(N);
4834       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4835                                 Src0, Src1);
4836       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4837       return;
4838     }
4839     case Intrinsic::amdgcn_cvt_pknorm_i16:
4840     case Intrinsic::amdgcn_cvt_pknorm_u16:
4841     case Intrinsic::amdgcn_cvt_pk_i16:
4842     case Intrinsic::amdgcn_cvt_pk_u16: {
4843       SDValue Src0 = N->getOperand(1);
4844       SDValue Src1 = N->getOperand(2);
4845       SDLoc SL(N);
4846       unsigned Opcode;
4847 
4848       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4849         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4850       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4851         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4852       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4853         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4854       else
4855         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4856 
4857       EVT VT = N->getValueType(0);
4858       if (isTypeLegal(VT))
4859         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4860       else {
4861         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4862         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4863       }
4864       return;
4865     }
4866     }
4867     break;
4868   }
4869   case ISD::INTRINSIC_W_CHAIN: {
4870     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4871       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4872         // FIXME: Hacky
4873         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4874           Results.push_back(Res.getOperand(I));
4875         }
4876       } else {
4877         Results.push_back(Res);
4878         Results.push_back(Res.getValue(1));
4879       }
4880       return;
4881     }
4882 
4883     break;
4884   }
4885   case ISD::SELECT: {
4886     SDLoc SL(N);
4887     EVT VT = N->getValueType(0);
4888     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4889     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4890     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4891 
4892     EVT SelectVT = NewVT;
4893     if (NewVT.bitsLT(MVT::i32)) {
4894       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4895       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4896       SelectVT = MVT::i32;
4897     }
4898 
4899     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4900                                     N->getOperand(0), LHS, RHS);
4901 
4902     if (NewVT != SelectVT)
4903       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4904     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4905     return;
4906   }
4907   case ISD::FNEG: {
4908     if (N->getValueType(0) != MVT::v2f16)
4909       break;
4910 
4911     SDLoc SL(N);
4912     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4913 
4914     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4915                              BC,
4916                              DAG.getConstant(0x80008000, SL, MVT::i32));
4917     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4918     return;
4919   }
4920   case ISD::FABS: {
4921     if (N->getValueType(0) != MVT::v2f16)
4922       break;
4923 
4924     SDLoc SL(N);
4925     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4926 
4927     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4928                              BC,
4929                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4930     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4931     return;
4932   }
4933   default:
4934     break;
4935   }
4936 }
4937 
4938 /// Helper function for LowerBRCOND
4939 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4940 
4941   SDNode *Parent = Value.getNode();
4942   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4943        I != E; ++I) {
4944 
4945     if (I.getUse().get() != Value)
4946       continue;
4947 
4948     if (I->getOpcode() == Opcode)
4949       return *I;
4950   }
4951   return nullptr;
4952 }
4953 
4954 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4955   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4956     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4957     case Intrinsic::amdgcn_if:
4958       return AMDGPUISD::IF;
4959     case Intrinsic::amdgcn_else:
4960       return AMDGPUISD::ELSE;
4961     case Intrinsic::amdgcn_loop:
4962       return AMDGPUISD::LOOP;
4963     case Intrinsic::amdgcn_end_cf:
4964       llvm_unreachable("should not occur");
4965     default:
4966       return 0;
4967     }
4968   }
4969 
4970   // break, if_break, else_break are all only used as inputs to loop, not
4971   // directly as branch conditions.
4972   return 0;
4973 }
4974 
4975 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4976   const Triple &TT = getTargetMachine().getTargetTriple();
4977   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4978           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4979          AMDGPU::shouldEmitConstantsToTextSection(TT);
4980 }
4981 
4982 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4983   // FIXME: Either avoid relying on address space here or change the default
4984   // address space for functions to avoid the explicit check.
4985   return (GV->getValueType()->isFunctionTy() ||
4986           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4987          !shouldEmitFixup(GV) &&
4988          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4989 }
4990 
4991 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4992   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4993 }
4994 
4995 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4996   if (!GV->hasExternalLinkage())
4997     return true;
4998 
4999   const auto OS = getTargetMachine().getTargetTriple().getOS();
5000   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5001 }
5002 
5003 /// This transforms the control flow intrinsics to get the branch destination as
5004 /// last parameter, also switches branch target with BR if the need arise
5005 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5006                                       SelectionDAG &DAG) const {
5007   SDLoc DL(BRCOND);
5008 
5009   SDNode *Intr = BRCOND.getOperand(1).getNode();
5010   SDValue Target = BRCOND.getOperand(2);
5011   SDNode *BR = nullptr;
5012   SDNode *SetCC = nullptr;
5013 
5014   if (Intr->getOpcode() == ISD::SETCC) {
5015     // As long as we negate the condition everything is fine
5016     SetCC = Intr;
5017     Intr = SetCC->getOperand(0).getNode();
5018 
5019   } else {
5020     // Get the target from BR if we don't negate the condition
5021     BR = findUser(BRCOND, ISD::BR);
5022     assert(BR && "brcond missing unconditional branch user");
5023     Target = BR->getOperand(1);
5024   }
5025 
5026   unsigned CFNode = isCFIntrinsic(Intr);
5027   if (CFNode == 0) {
5028     // This is a uniform branch so we don't need to legalize.
5029     return BRCOND;
5030   }
5031 
5032   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5033                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5034 
5035   assert(!SetCC ||
5036         (SetCC->getConstantOperandVal(1) == 1 &&
5037          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5038                                                              ISD::SETNE));
5039 
5040   // operands of the new intrinsic call
5041   SmallVector<SDValue, 4> Ops;
5042   if (HaveChain)
5043     Ops.push_back(BRCOND.getOperand(0));
5044 
5045   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5046   Ops.push_back(Target);
5047 
5048   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5049 
5050   // build the new intrinsic call
5051   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5052 
5053   if (!HaveChain) {
5054     SDValue Ops[] =  {
5055       SDValue(Result, 0),
5056       BRCOND.getOperand(0)
5057     };
5058 
5059     Result = DAG.getMergeValues(Ops, DL).getNode();
5060   }
5061 
5062   if (BR) {
5063     // Give the branch instruction our target
5064     SDValue Ops[] = {
5065       BR->getOperand(0),
5066       BRCOND.getOperand(2)
5067     };
5068     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5069     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5070   }
5071 
5072   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5073 
5074   // Copy the intrinsic results to registers
5075   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5076     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5077     if (!CopyToReg)
5078       continue;
5079 
5080     Chain = DAG.getCopyToReg(
5081       Chain, DL,
5082       CopyToReg->getOperand(1),
5083       SDValue(Result, i - 1),
5084       SDValue());
5085 
5086     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5087   }
5088 
5089   // Remove the old intrinsic from the chain
5090   DAG.ReplaceAllUsesOfValueWith(
5091     SDValue(Intr, Intr->getNumValues() - 1),
5092     Intr->getOperand(0));
5093 
5094   return Chain;
5095 }
5096 
5097 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5098                                           SelectionDAG &DAG) const {
5099   MVT VT = Op.getSimpleValueType();
5100   SDLoc DL(Op);
5101   // Checking the depth
5102   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5103     return DAG.getConstant(0, DL, VT);
5104 
5105   MachineFunction &MF = DAG.getMachineFunction();
5106   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5107   // Check for kernel and shader functions
5108   if (Info->isEntryFunction())
5109     return DAG.getConstant(0, DL, VT);
5110 
5111   MachineFrameInfo &MFI = MF.getFrameInfo();
5112   // There is a call to @llvm.returnaddress in this function
5113   MFI.setReturnAddressIsTaken(true);
5114 
5115   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5116   // Get the return address reg and mark it as an implicit live-in
5117   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5118 
5119   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5120 }
5121 
5122 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5123                                             SDValue Op,
5124                                             const SDLoc &DL,
5125                                             EVT VT) const {
5126   return Op.getValueType().bitsLE(VT) ?
5127       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5128     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5129                 DAG.getTargetConstant(0, DL, MVT::i32));
5130 }
5131 
5132 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5133   assert(Op.getValueType() == MVT::f16 &&
5134          "Do not know how to custom lower FP_ROUND for non-f16 type");
5135 
5136   SDValue Src = Op.getOperand(0);
5137   EVT SrcVT = Src.getValueType();
5138   if (SrcVT != MVT::f64)
5139     return Op;
5140 
5141   SDLoc DL(Op);
5142 
5143   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5144   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5145   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5146 }
5147 
5148 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5149                                                SelectionDAG &DAG) const {
5150   EVT VT = Op.getValueType();
5151   const MachineFunction &MF = DAG.getMachineFunction();
5152   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5153   bool IsIEEEMode = Info->getMode().IEEE;
5154 
5155   // FIXME: Assert during selection that this is only selected for
5156   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5157   // mode functions, but this happens to be OK since it's only done in cases
5158   // where there is known no sNaN.
5159   if (IsIEEEMode)
5160     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5161 
5162   if (VT == MVT::v4f16)
5163     return splitBinaryVectorOp(Op, DAG);
5164   return Op;
5165 }
5166 
5167 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5168   EVT VT = Op.getValueType();
5169   SDLoc SL(Op);
5170   SDValue LHS = Op.getOperand(0);
5171   SDValue RHS = Op.getOperand(1);
5172   bool isSigned = Op.getOpcode() == ISD::SMULO;
5173 
5174   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5175     const APInt &C = RHSC->getAPIntValue();
5176     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5177     if (C.isPowerOf2()) {
5178       // smulo(x, signed_min) is same as umulo(x, signed_min).
5179       bool UseArithShift = isSigned && !C.isMinSignedValue();
5180       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5181       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5182       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5183           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5184                       SL, VT, Result, ShiftAmt),
5185           LHS, ISD::SETNE);
5186       return DAG.getMergeValues({ Result, Overflow }, SL);
5187     }
5188   }
5189 
5190   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5191   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5192                             SL, VT, LHS, RHS);
5193 
5194   SDValue Sign = isSigned
5195     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5196                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5197     : DAG.getConstant(0, SL, VT);
5198   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5199 
5200   return DAG.getMergeValues({ Result, Overflow }, SL);
5201 }
5202 
5203 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5204   SDLoc SL(Op);
5205   SDValue Chain = Op.getOperand(0);
5206 
5207   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5208       !Subtarget->isTrapHandlerEnabled())
5209     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5210 
5211   MachineFunction &MF = DAG.getMachineFunction();
5212   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5213   Register UserSGPR = Info->getQueuePtrUserSGPR();
5214   assert(UserSGPR != AMDGPU::NoRegister);
5215   SDValue QueuePtr = CreateLiveInRegister(
5216     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5217   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5218   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5219                                    QueuePtr, SDValue());
5220   SDValue Ops[] = {
5221     ToReg,
5222     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5223     SGPR01,
5224     ToReg.getValue(1)
5225   };
5226   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5227 }
5228 
5229 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5230   SDLoc SL(Op);
5231   SDValue Chain = Op.getOperand(0);
5232   MachineFunction &MF = DAG.getMachineFunction();
5233 
5234   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5235       !Subtarget->isTrapHandlerEnabled()) {
5236     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5237                                      "debugtrap handler not supported",
5238                                      Op.getDebugLoc(),
5239                                      DS_Warning);
5240     LLVMContext &Ctx = MF.getFunction().getContext();
5241     Ctx.diagnose(NoTrap);
5242     return Chain;
5243   }
5244 
5245   SDValue Ops[] = {
5246     Chain,
5247     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5248   };
5249   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5250 }
5251 
5252 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5253                                              SelectionDAG &DAG) const {
5254   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5255   if (Subtarget->hasApertureRegs()) {
5256     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5257         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5258         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5259     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5260         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5261         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5262     unsigned Encoding =
5263         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5264         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5265         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5266 
5267     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5268     SDValue ApertureReg = SDValue(
5269         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5270     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5271     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5272   }
5273 
5274   MachineFunction &MF = DAG.getMachineFunction();
5275   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5276   Register UserSGPR = Info->getQueuePtrUserSGPR();
5277   assert(UserSGPR != AMDGPU::NoRegister);
5278 
5279   SDValue QueuePtr = CreateLiveInRegister(
5280     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5281 
5282   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5283   // private_segment_aperture_base_hi.
5284   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5285 
5286   SDValue Ptr =
5287       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5288 
5289   // TODO: Use custom target PseudoSourceValue.
5290   // TODO: We should use the value from the IR intrinsic call, but it might not
5291   // be available and how do we get it?
5292   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5293   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5294                      commonAlignment(Align(64), StructOffset),
5295                      MachineMemOperand::MODereferenceable |
5296                          MachineMemOperand::MOInvariant);
5297 }
5298 
5299 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5300                                              SelectionDAG &DAG) const {
5301   SDLoc SL(Op);
5302   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5303 
5304   SDValue Src = ASC->getOperand(0);
5305   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5306 
5307   const AMDGPUTargetMachine &TM =
5308     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5309 
5310   // flat -> local/private
5311   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5312     unsigned DestAS = ASC->getDestAddressSpace();
5313 
5314     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5315         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5316       unsigned NullVal = TM.getNullPointerValue(DestAS);
5317       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5318       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5319       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5320 
5321       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5322                          NonNull, Ptr, SegmentNullPtr);
5323     }
5324   }
5325 
5326   // local/private -> flat
5327   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5328     unsigned SrcAS = ASC->getSrcAddressSpace();
5329 
5330     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5331         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5332       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5333       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5334 
5335       SDValue NonNull
5336         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5337 
5338       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5339       SDValue CvtPtr
5340         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5341 
5342       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5343                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5344                          FlatNullPtr);
5345     }
5346   }
5347 
5348   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5349       Src.getValueType() == MVT::i64)
5350     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5351 
5352   // global <-> flat are no-ops and never emitted.
5353 
5354   const MachineFunction &MF = DAG.getMachineFunction();
5355   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5356     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5357   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5358 
5359   return DAG.getUNDEF(ASC->getValueType(0));
5360 }
5361 
5362 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5363 // the small vector and inserting them into the big vector. That is better than
5364 // the default expansion of doing it via a stack slot. Even though the use of
5365 // the stack slot would be optimized away afterwards, the stack slot itself
5366 // remains.
5367 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5368                                                 SelectionDAG &DAG) const {
5369   SDValue Vec = Op.getOperand(0);
5370   SDValue Ins = Op.getOperand(1);
5371   SDValue Idx = Op.getOperand(2);
5372   EVT VecVT = Vec.getValueType();
5373   EVT InsVT = Ins.getValueType();
5374   EVT EltVT = VecVT.getVectorElementType();
5375   unsigned InsNumElts = InsVT.getVectorNumElements();
5376   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5377   SDLoc SL(Op);
5378 
5379   for (unsigned I = 0; I != InsNumElts; ++I) {
5380     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5381                               DAG.getConstant(I, SL, MVT::i32));
5382     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5383                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5384   }
5385   return Vec;
5386 }
5387 
5388 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5389                                                  SelectionDAG &DAG) const {
5390   SDValue Vec = Op.getOperand(0);
5391   SDValue InsVal = Op.getOperand(1);
5392   SDValue Idx = Op.getOperand(2);
5393   EVT VecVT = Vec.getValueType();
5394   EVT EltVT = VecVT.getVectorElementType();
5395   unsigned VecSize = VecVT.getSizeInBits();
5396   unsigned EltSize = EltVT.getSizeInBits();
5397 
5398 
5399   assert(VecSize <= 64);
5400 
5401   unsigned NumElts = VecVT.getVectorNumElements();
5402   SDLoc SL(Op);
5403   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5404 
5405   if (NumElts == 4 && EltSize == 16 && KIdx) {
5406     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5407 
5408     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5409                                  DAG.getConstant(0, SL, MVT::i32));
5410     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5411                                  DAG.getConstant(1, SL, MVT::i32));
5412 
5413     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5414     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5415 
5416     unsigned Idx = KIdx->getZExtValue();
5417     bool InsertLo = Idx < 2;
5418     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5419       InsertLo ? LoVec : HiVec,
5420       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5421       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5422 
5423     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5424 
5425     SDValue Concat = InsertLo ?
5426       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5427       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5428 
5429     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5430   }
5431 
5432   if (isa<ConstantSDNode>(Idx))
5433     return SDValue();
5434 
5435   MVT IntVT = MVT::getIntegerVT(VecSize);
5436 
5437   // Avoid stack access for dynamic indexing.
5438   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5439 
5440   // Create a congruent vector with the target value in each element so that
5441   // the required element can be masked and ORed into the target vector.
5442   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5443                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5444 
5445   assert(isPowerOf2_32(EltSize));
5446   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5447 
5448   // Convert vector index to bit-index.
5449   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5450 
5451   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5452   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5453                             DAG.getConstant(0xffff, SL, IntVT),
5454                             ScaledIdx);
5455 
5456   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5457   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5458                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5459 
5460   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5461   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5462 }
5463 
5464 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5465                                                   SelectionDAG &DAG) const {
5466   SDLoc SL(Op);
5467 
5468   EVT ResultVT = Op.getValueType();
5469   SDValue Vec = Op.getOperand(0);
5470   SDValue Idx = Op.getOperand(1);
5471   EVT VecVT = Vec.getValueType();
5472   unsigned VecSize = VecVT.getSizeInBits();
5473   EVT EltVT = VecVT.getVectorElementType();
5474   assert(VecSize <= 64);
5475 
5476   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5477 
5478   // Make sure we do any optimizations that will make it easier to fold
5479   // source modifiers before obscuring it with bit operations.
5480 
5481   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5482   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5483     return Combined;
5484 
5485   unsigned EltSize = EltVT.getSizeInBits();
5486   assert(isPowerOf2_32(EltSize));
5487 
5488   MVT IntVT = MVT::getIntegerVT(VecSize);
5489   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5490 
5491   // Convert vector index to bit-index (* EltSize)
5492   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5493 
5494   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5495   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5496 
5497   if (ResultVT == MVT::f16) {
5498     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5499     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5500   }
5501 
5502   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5503 }
5504 
5505 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5506   assert(Elt % 2 == 0);
5507   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5508 }
5509 
5510 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5511                                               SelectionDAG &DAG) const {
5512   SDLoc SL(Op);
5513   EVT ResultVT = Op.getValueType();
5514   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5515 
5516   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5517   EVT EltVT = PackVT.getVectorElementType();
5518   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5519 
5520   // vector_shuffle <0,1,6,7> lhs, rhs
5521   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5522   //
5523   // vector_shuffle <6,7,2,3> lhs, rhs
5524   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5525   //
5526   // vector_shuffle <6,7,0,1> lhs, rhs
5527   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5528 
5529   // Avoid scalarizing when both halves are reading from consecutive elements.
5530   SmallVector<SDValue, 4> Pieces;
5531   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5532     if (elementPairIsContiguous(SVN->getMask(), I)) {
5533       const int Idx = SVN->getMaskElt(I);
5534       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5535       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5536       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5537                                     PackVT, SVN->getOperand(VecIdx),
5538                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5539       Pieces.push_back(SubVec);
5540     } else {
5541       const int Idx0 = SVN->getMaskElt(I);
5542       const int Idx1 = SVN->getMaskElt(I + 1);
5543       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5544       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5545       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5546       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5547 
5548       SDValue Vec0 = SVN->getOperand(VecIdx0);
5549       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5550                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5551 
5552       SDValue Vec1 = SVN->getOperand(VecIdx1);
5553       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5554                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5555       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5556     }
5557   }
5558 
5559   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5560 }
5561 
5562 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5563                                             SelectionDAG &DAG) const {
5564   SDLoc SL(Op);
5565   EVT VT = Op.getValueType();
5566 
5567   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5568     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5569 
5570     // Turn into pair of packed build_vectors.
5571     // TODO: Special case for constants that can be materialized with s_mov_b64.
5572     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5573                                     { Op.getOperand(0), Op.getOperand(1) });
5574     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5575                                     { Op.getOperand(2), Op.getOperand(3) });
5576 
5577     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5578     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5579 
5580     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5581     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5582   }
5583 
5584   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5585   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5586 
5587   SDValue Lo = Op.getOperand(0);
5588   SDValue Hi = Op.getOperand(1);
5589 
5590   // Avoid adding defined bits with the zero_extend.
5591   if (Hi.isUndef()) {
5592     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5593     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5594     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5595   }
5596 
5597   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5598   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5599 
5600   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5601                               DAG.getConstant(16, SL, MVT::i32));
5602   if (Lo.isUndef())
5603     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5604 
5605   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5606   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5607 
5608   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5609   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5610 }
5611 
5612 bool
5613 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5614   // We can fold offsets for anything that doesn't require a GOT relocation.
5615   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5616           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5617           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5618          !shouldEmitGOTReloc(GA->getGlobal());
5619 }
5620 
5621 static SDValue
5622 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5623                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5624                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5625   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5626   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5627   // lowered to the following code sequence:
5628   //
5629   // For constant address space:
5630   //   s_getpc_b64 s[0:1]
5631   //   s_add_u32 s0, s0, $symbol
5632   //   s_addc_u32 s1, s1, 0
5633   //
5634   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5635   //   a fixup or relocation is emitted to replace $symbol with a literal
5636   //   constant, which is a pc-relative offset from the encoding of the $symbol
5637   //   operand to the global variable.
5638   //
5639   // For global address space:
5640   //   s_getpc_b64 s[0:1]
5641   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5642   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5643   //
5644   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5645   //   fixups or relocations are emitted to replace $symbol@*@lo and
5646   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5647   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5648   //   operand to the global variable.
5649   //
5650   // What we want here is an offset from the value returned by s_getpc
5651   // (which is the address of the s_add_u32 instruction) to the global
5652   // variable, but since the encoding of $symbol starts 4 bytes after the start
5653   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5654   // small. This requires us to add 4 to the global variable offset in order to
5655   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5656   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5657   // instruction.
5658   SDValue PtrLo =
5659       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5660   SDValue PtrHi;
5661   if (GAFlags == SIInstrInfo::MO_NONE) {
5662     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5663   } else {
5664     PtrHi =
5665         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5666   }
5667   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5668 }
5669 
5670 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5671                                              SDValue Op,
5672                                              SelectionDAG &DAG) const {
5673   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5674   SDLoc DL(GSD);
5675   EVT PtrVT = Op.getValueType();
5676 
5677   const GlobalValue *GV = GSD->getGlobal();
5678   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5679        shouldUseLDSConstAddress(GV)) ||
5680       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5681       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5682     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5683         GV->hasExternalLinkage()) {
5684       Type *Ty = GV->getValueType();
5685       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5686       // zero-sized type in other languages to declare the dynamic shared
5687       // memory which size is not known at the compile time. They will be
5688       // allocated by the runtime and placed directly after the static
5689       // allocated ones. They all share the same offset.
5690       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5691         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5692         // Adjust alignment for that dynamic shared memory array.
5693         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5694         return SDValue(
5695             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5696       }
5697     }
5698     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5699   }
5700 
5701   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5702     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5703                                             SIInstrInfo::MO_ABS32_LO);
5704     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5705   }
5706 
5707   if (shouldEmitFixup(GV))
5708     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5709   else if (shouldEmitPCReloc(GV))
5710     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5711                                    SIInstrInfo::MO_REL32);
5712 
5713   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5714                                             SIInstrInfo::MO_GOTPCREL32);
5715 
5716   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5717   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5718   const DataLayout &DataLayout = DAG.getDataLayout();
5719   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5720   MachinePointerInfo PtrInfo
5721     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5722 
5723   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5724                      MachineMemOperand::MODereferenceable |
5725                          MachineMemOperand::MOInvariant);
5726 }
5727 
5728 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5729                                    const SDLoc &DL, SDValue V) const {
5730   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5731   // the destination register.
5732   //
5733   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5734   // so we will end up with redundant moves to m0.
5735   //
5736   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5737 
5738   // A Null SDValue creates a glue result.
5739   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5740                                   V, Chain);
5741   return SDValue(M0, 0);
5742 }
5743 
5744 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5745                                                  SDValue Op,
5746                                                  MVT VT,
5747                                                  unsigned Offset) const {
5748   SDLoc SL(Op);
5749   SDValue Param = lowerKernargMemParameter(
5750       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5751   // The local size values will have the hi 16-bits as zero.
5752   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5753                      DAG.getValueType(VT));
5754 }
5755 
5756 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5757                                         EVT VT) {
5758   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5759                                       "non-hsa intrinsic with hsa target",
5760                                       DL.getDebugLoc());
5761   DAG.getContext()->diagnose(BadIntrin);
5762   return DAG.getUNDEF(VT);
5763 }
5764 
5765 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5766                                          EVT VT) {
5767   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5768                                       "intrinsic not supported on subtarget",
5769                                       DL.getDebugLoc());
5770   DAG.getContext()->diagnose(BadIntrin);
5771   return DAG.getUNDEF(VT);
5772 }
5773 
5774 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5775                                     ArrayRef<SDValue> Elts) {
5776   assert(!Elts.empty());
5777   MVT Type;
5778   unsigned NumElts;
5779 
5780   if (Elts.size() == 1) {
5781     Type = MVT::f32;
5782     NumElts = 1;
5783   } else if (Elts.size() == 2) {
5784     Type = MVT::v2f32;
5785     NumElts = 2;
5786   } else if (Elts.size() == 3) {
5787     Type = MVT::v3f32;
5788     NumElts = 3;
5789   } else if (Elts.size() <= 4) {
5790     Type = MVT::v4f32;
5791     NumElts = 4;
5792   } else if (Elts.size() <= 8) {
5793     Type = MVT::v8f32;
5794     NumElts = 8;
5795   } else {
5796     assert(Elts.size() <= 16);
5797     Type = MVT::v16f32;
5798     NumElts = 16;
5799   }
5800 
5801   SmallVector<SDValue, 16> VecElts(NumElts);
5802   for (unsigned i = 0; i < Elts.size(); ++i) {
5803     SDValue Elt = Elts[i];
5804     if (Elt.getValueType() != MVT::f32)
5805       Elt = DAG.getBitcast(MVT::f32, Elt);
5806     VecElts[i] = Elt;
5807   }
5808   for (unsigned i = Elts.size(); i < NumElts; ++i)
5809     VecElts[i] = DAG.getUNDEF(MVT::f32);
5810 
5811   if (NumElts == 1)
5812     return VecElts[0];
5813   return DAG.getBuildVector(Type, DL, VecElts);
5814 }
5815 
5816 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5817                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5818   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5819 
5820   uint64_t Value = CachePolicyConst->getZExtValue();
5821   SDLoc DL(CachePolicy);
5822   if (GLC) {
5823     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5824     Value &= ~(uint64_t)0x1;
5825   }
5826   if (SLC) {
5827     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5828     Value &= ~(uint64_t)0x2;
5829   }
5830   if (DLC) {
5831     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5832     Value &= ~(uint64_t)0x4;
5833   }
5834 
5835   return Value == 0;
5836 }
5837 
5838 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5839                               SDValue Src, int ExtraElts) {
5840   EVT SrcVT = Src.getValueType();
5841 
5842   SmallVector<SDValue, 8> Elts;
5843 
5844   if (SrcVT.isVector())
5845     DAG.ExtractVectorElements(Src, Elts);
5846   else
5847     Elts.push_back(Src);
5848 
5849   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5850   while (ExtraElts--)
5851     Elts.push_back(Undef);
5852 
5853   return DAG.getBuildVector(CastVT, DL, Elts);
5854 }
5855 
5856 // Re-construct the required return value for a image load intrinsic.
5857 // This is more complicated due to the optional use TexFailCtrl which means the required
5858 // return type is an aggregate
5859 static SDValue constructRetValue(SelectionDAG &DAG,
5860                                  MachineSDNode *Result,
5861                                  ArrayRef<EVT> ResultTypes,
5862                                  bool IsTexFail, bool Unpacked, bool IsD16,
5863                                  int DMaskPop, int NumVDataDwords,
5864                                  const SDLoc &DL, LLVMContext &Context) {
5865   // Determine the required return type. This is the same regardless of IsTexFail flag
5866   EVT ReqRetVT = ResultTypes[0];
5867   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5868   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5869     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5870 
5871   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5872     DMaskPop : (DMaskPop + 1) / 2;
5873 
5874   MVT DataDwordVT = NumDataDwords == 1 ?
5875     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5876 
5877   MVT MaskPopVT = MaskPopDwords == 1 ?
5878     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5879 
5880   SDValue Data(Result, 0);
5881   SDValue TexFail;
5882 
5883   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5884     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5885     if (MaskPopVT.isVector()) {
5886       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5887                          SDValue(Result, 0), ZeroIdx);
5888     } else {
5889       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5890                          SDValue(Result, 0), ZeroIdx);
5891     }
5892   }
5893 
5894   if (DataDwordVT.isVector())
5895     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5896                           NumDataDwords - MaskPopDwords);
5897 
5898   if (IsD16)
5899     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5900 
5901   EVT LegalReqRetVT = ReqRetVT;
5902   if (!ReqRetVT.isVector()) {
5903     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5904   } else {
5905     // We need to widen the return vector to a legal type
5906     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5907         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5908       LegalReqRetVT =
5909           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5910                            ReqRetVT.getVectorNumElements() + 1);
5911     }
5912   }
5913   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5914 
5915   if (IsTexFail) {
5916     TexFail =
5917         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5918                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5919 
5920     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5921   }
5922 
5923   if (Result->getNumValues() == 1)
5924     return Data;
5925 
5926   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5927 }
5928 
5929 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5930                          SDValue *LWE, bool &IsTexFail) {
5931   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5932 
5933   uint64_t Value = TexFailCtrlConst->getZExtValue();
5934   if (Value) {
5935     IsTexFail = true;
5936   }
5937 
5938   SDLoc DL(TexFailCtrlConst);
5939   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5940   Value &= ~(uint64_t)0x1;
5941   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5942   Value &= ~(uint64_t)0x2;
5943 
5944   return Value == 0;
5945 }
5946 
5947 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5948                                         MVT PackVectorVT,
5949                                         SmallVectorImpl<SDValue> &PackedAddrs,
5950                                         unsigned DimIdx, unsigned EndIdx,
5951                                         unsigned NumGradients) {
5952   SDLoc DL(Op);
5953   for (unsigned I = DimIdx; I < EndIdx; I++) {
5954     SDValue Addr = Op.getOperand(I);
5955 
5956     // Gradients are packed with undef for each coordinate.
5957     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5958     // 1D: undef,dx/dh; undef,dx/dv
5959     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5960     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5961     if (((I + 1) >= EndIdx) ||
5962         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5963                                          I == DimIdx + NumGradients - 1))) {
5964       if (Addr.getValueType() != MVT::i16)
5965         Addr = DAG.getBitcast(MVT::i16, Addr);
5966       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5967     } else {
5968       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5969       I++;
5970     }
5971     Addr = DAG.getBitcast(MVT::f32, Addr);
5972     PackedAddrs.push_back(Addr);
5973   }
5974 }
5975 
5976 SDValue SITargetLowering::lowerImage(SDValue Op,
5977                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5978                                      SelectionDAG &DAG, bool WithChain) const {
5979   SDLoc DL(Op);
5980   MachineFunction &MF = DAG.getMachineFunction();
5981   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5982   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5983       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5984   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5985   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5986       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5987   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5988       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5989   unsigned IntrOpcode = Intr->BaseOpcode;
5990   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5991 
5992   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5993   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5994   bool IsD16 = false;
5995   bool IsG16 = false;
5996   bool IsA16 = false;
5997   SDValue VData;
5998   int NumVDataDwords;
5999   bool AdjustRetType = false;
6000 
6001   // Offset of intrinsic arguments
6002   const unsigned ArgOffset = WithChain ? 2 : 1;
6003 
6004   unsigned DMask;
6005   unsigned DMaskLanes = 0;
6006 
6007   if (BaseOpcode->Atomic) {
6008     VData = Op.getOperand(2);
6009 
6010     bool Is64Bit = VData.getValueType() == MVT::i64;
6011     if (BaseOpcode->AtomicX2) {
6012       SDValue VData2 = Op.getOperand(3);
6013       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6014                                  {VData, VData2});
6015       if (Is64Bit)
6016         VData = DAG.getBitcast(MVT::v4i32, VData);
6017 
6018       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6019       DMask = Is64Bit ? 0xf : 0x3;
6020       NumVDataDwords = Is64Bit ? 4 : 2;
6021     } else {
6022       DMask = Is64Bit ? 0x3 : 0x1;
6023       NumVDataDwords = Is64Bit ? 2 : 1;
6024     }
6025   } else {
6026     auto *DMaskConst =
6027         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6028     DMask = DMaskConst->getZExtValue();
6029     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6030 
6031     if (BaseOpcode->Store) {
6032       VData = Op.getOperand(2);
6033 
6034       MVT StoreVT = VData.getSimpleValueType();
6035       if (StoreVT.getScalarType() == MVT::f16) {
6036         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6037           return Op; // D16 is unsupported for this instruction
6038 
6039         IsD16 = true;
6040         VData = handleD16VData(VData, DAG, true);
6041       }
6042 
6043       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6044     } else {
6045       // Work out the num dwords based on the dmask popcount and underlying type
6046       // and whether packing is supported.
6047       MVT LoadVT = ResultTypes[0].getSimpleVT();
6048       if (LoadVT.getScalarType() == MVT::f16) {
6049         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6050           return Op; // D16 is unsupported for this instruction
6051 
6052         IsD16 = true;
6053       }
6054 
6055       // Confirm that the return type is large enough for the dmask specified
6056       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6057           (!LoadVT.isVector() && DMaskLanes > 1))
6058           return Op;
6059 
6060       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6061       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6062       // instructions.
6063       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6064           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6065         NumVDataDwords = (DMaskLanes + 1) / 2;
6066       else
6067         NumVDataDwords = DMaskLanes;
6068 
6069       AdjustRetType = true;
6070     }
6071   }
6072 
6073   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6074   SmallVector<SDValue, 4> VAddrs;
6075 
6076   // Optimize _L to _LZ when _L is zero
6077   if (LZMappingInfo) {
6078     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6079             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6080       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6081         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6082         VAddrEnd--;                      // remove 'lod'
6083       }
6084     }
6085   }
6086 
6087   // Optimize _mip away, when 'lod' is zero
6088   if (MIPMappingInfo) {
6089     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6090             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6091       if (ConstantLod->isNullValue()) {
6092         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6093         VAddrEnd--;                           // remove 'mip'
6094       }
6095     }
6096   }
6097 
6098   // Push back extra arguments.
6099   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6100     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6101 
6102   // Check for 16 bit addresses or derivatives and pack if true.
6103   MVT VAddrVT =
6104       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6105   MVT VAddrScalarVT = VAddrVT.getScalarType();
6106   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6107   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6108 
6109   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6110   VAddrScalarVT = VAddrVT.getScalarType();
6111   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6112   if (IsA16 || IsG16) {
6113     if (IsA16) {
6114       if (!ST->hasA16()) {
6115         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6116                              "support 16 bit addresses\n");
6117         return Op;
6118       }
6119       if (!IsG16) {
6120         LLVM_DEBUG(
6121             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6122                       "need 16 bit derivatives but got 32 bit derivatives\n");
6123         return Op;
6124       }
6125     } else if (!ST->hasG16()) {
6126       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6127                            "support 16 bit derivatives\n");
6128       return Op;
6129     }
6130 
6131     if (BaseOpcode->Gradients && !IsA16) {
6132       if (!ST->hasG16()) {
6133         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6134                              "support 16 bit derivatives\n");
6135         return Op;
6136       }
6137       // Activate g16
6138       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6139           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6140       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6141     }
6142 
6143     // Don't compress addresses for G16
6144     const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6145     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs,
6146                                 ArgOffset + Intr->GradientStart, PackEndIdx,
6147                                 Intr->NumGradients);
6148 
6149     if (!IsA16) {
6150       // Add uncompressed address
6151       for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6152         VAddrs.push_back(Op.getOperand(I));
6153     }
6154   } else {
6155     for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++)
6156       VAddrs.push_back(Op.getOperand(I));
6157   }
6158 
6159   // If the register allocator cannot place the address registers contiguously
6160   // without introducing moves, then using the non-sequential address encoding
6161   // is always preferable, since it saves VALU instructions and is usually a
6162   // wash in terms of code size or even better.
6163   //
6164   // However, we currently have no way of hinting to the register allocator that
6165   // MIMG addresses should be placed contiguously when it is possible to do so,
6166   // so force non-NSA for the common 2-address case as a heuristic.
6167   //
6168   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6169   // allocation when possible.
6170   bool UseNSA =
6171       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6172   SDValue VAddr;
6173   if (!UseNSA)
6174     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6175 
6176   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6177   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6178   SDValue Unorm;
6179   if (!BaseOpcode->Sampler) {
6180     Unorm = True;
6181   } else {
6182     auto UnormConst =
6183         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6184 
6185     Unorm = UnormConst->getZExtValue() ? True : False;
6186   }
6187 
6188   SDValue TFE;
6189   SDValue LWE;
6190   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6191   bool IsTexFail = false;
6192   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6193     return Op;
6194 
6195   if (IsTexFail) {
6196     if (!DMaskLanes) {
6197       // Expecting to get an error flag since TFC is on - and dmask is 0
6198       // Force dmask to be at least 1 otherwise the instruction will fail
6199       DMask = 0x1;
6200       DMaskLanes = 1;
6201       NumVDataDwords = 1;
6202     }
6203     NumVDataDwords += 1;
6204     AdjustRetType = true;
6205   }
6206 
6207   // Has something earlier tagged that the return type needs adjusting
6208   // This happens if the instruction is a load or has set TexFailCtrl flags
6209   if (AdjustRetType) {
6210     // NumVDataDwords reflects the true number of dwords required in the return type
6211     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6212       // This is a no-op load. This can be eliminated
6213       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6214       if (isa<MemSDNode>(Op))
6215         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6216       return Undef;
6217     }
6218 
6219     EVT NewVT = NumVDataDwords > 1 ?
6220                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6221                 : MVT::i32;
6222 
6223     ResultTypes[0] = NewVT;
6224     if (ResultTypes.size() == 3) {
6225       // Original result was aggregate type used for TexFailCtrl results
6226       // The actual instruction returns as a vector type which has now been
6227       // created. Remove the aggregate result.
6228       ResultTypes.erase(&ResultTypes[1]);
6229     }
6230   }
6231 
6232   SDValue GLC;
6233   SDValue SLC;
6234   SDValue DLC;
6235   if (BaseOpcode->Atomic) {
6236     GLC = True; // TODO no-return optimization
6237     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6238                           DAG, nullptr, &SLC, IsGFX10 ? &DLC : nullptr))
6239       return Op;
6240   } else {
6241     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6242                           DAG, &GLC, &SLC, IsGFX10 ? &DLC : nullptr))
6243       return Op;
6244   }
6245 
6246   SmallVector<SDValue, 26> Ops;
6247   if (BaseOpcode->Store || BaseOpcode->Atomic)
6248     Ops.push_back(VData); // vdata
6249   if (UseNSA) {
6250     for (const SDValue &Addr : VAddrs)
6251       Ops.push_back(Addr);
6252   } else {
6253     Ops.push_back(VAddr);
6254   }
6255   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6256   if (BaseOpcode->Sampler)
6257     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6258   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6259   if (IsGFX10)
6260     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6261   Ops.push_back(Unorm);
6262   if (IsGFX10)
6263     Ops.push_back(DLC);
6264   Ops.push_back(GLC);
6265   Ops.push_back(SLC);
6266   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6267                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6268   if (IsGFX10)
6269     Ops.push_back(IsA16 ? True : False);
6270   Ops.push_back(TFE);
6271   Ops.push_back(LWE);
6272   if (!IsGFX10)
6273     Ops.push_back(DimInfo->DA ? True : False);
6274   if (BaseOpcode->HasD16)
6275     Ops.push_back(IsD16 ? True : False);
6276   if (isa<MemSDNode>(Op))
6277     Ops.push_back(Op.getOperand(0)); // chain
6278 
6279   int NumVAddrDwords =
6280       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6281   int Opcode = -1;
6282 
6283   if (IsGFX10) {
6284     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6285                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6286                                           : AMDGPU::MIMGEncGfx10Default,
6287                                    NumVDataDwords, NumVAddrDwords);
6288   } else {
6289     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6290       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6291                                      NumVDataDwords, NumVAddrDwords);
6292     if (Opcode == -1)
6293       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6294                                      NumVDataDwords, NumVAddrDwords);
6295   }
6296   assert(Opcode != -1);
6297 
6298   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6299   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6300     MachineMemOperand *MemRef = MemOp->getMemOperand();
6301     DAG.setNodeMemRefs(NewNode, {MemRef});
6302   }
6303 
6304   if (BaseOpcode->AtomicX2) {
6305     SmallVector<SDValue, 1> Elt;
6306     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6307     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6308   } else if (!BaseOpcode->Store) {
6309     return constructRetValue(DAG, NewNode,
6310                              OrigResultTypes, IsTexFail,
6311                              Subtarget->hasUnpackedD16VMem(), IsD16,
6312                              DMaskLanes, NumVDataDwords, DL,
6313                              *DAG.getContext());
6314   }
6315 
6316   return SDValue(NewNode, 0);
6317 }
6318 
6319 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6320                                        SDValue Offset, SDValue CachePolicy,
6321                                        SelectionDAG &DAG) const {
6322   MachineFunction &MF = DAG.getMachineFunction();
6323 
6324   const DataLayout &DataLayout = DAG.getDataLayout();
6325   Align Alignment =
6326       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6327 
6328   MachineMemOperand *MMO = MF.getMachineMemOperand(
6329       MachinePointerInfo(),
6330       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6331           MachineMemOperand::MOInvariant,
6332       VT.getStoreSize(), Alignment);
6333 
6334   if (!Offset->isDivergent()) {
6335     SDValue Ops[] = {
6336         Rsrc,
6337         Offset, // Offset
6338         CachePolicy
6339     };
6340 
6341     // Widen vec3 load to vec4.
6342     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6343       EVT WidenedVT =
6344           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6345       auto WidenedOp = DAG.getMemIntrinsicNode(
6346           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6347           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6348       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6349                                    DAG.getVectorIdxConstant(0, DL));
6350       return Subvector;
6351     }
6352 
6353     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6354                                    DAG.getVTList(VT), Ops, VT, MMO);
6355   }
6356 
6357   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6358   // assume that the buffer is unswizzled.
6359   SmallVector<SDValue, 4> Loads;
6360   unsigned NumLoads = 1;
6361   MVT LoadVT = VT.getSimpleVT();
6362   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6363   assert((LoadVT.getScalarType() == MVT::i32 ||
6364           LoadVT.getScalarType() == MVT::f32));
6365 
6366   if (NumElts == 8 || NumElts == 16) {
6367     NumLoads = NumElts / 4;
6368     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6369   }
6370 
6371   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6372   SDValue Ops[] = {
6373       DAG.getEntryNode(),                               // Chain
6374       Rsrc,                                             // rsrc
6375       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6376       {},                                               // voffset
6377       {},                                               // soffset
6378       {},                                               // offset
6379       CachePolicy,                                      // cachepolicy
6380       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6381   };
6382 
6383   // Use the alignment to ensure that the required offsets will fit into the
6384   // immediate offsets.
6385   setBufferOffsets(Offset, DAG, &Ops[3],
6386                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6387 
6388   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6389   for (unsigned i = 0; i < NumLoads; ++i) {
6390     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6391     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6392                                         LoadVT, MMO, DAG));
6393   }
6394 
6395   if (NumElts == 8 || NumElts == 16)
6396     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6397 
6398   return Loads[0];
6399 }
6400 
6401 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6402                                                   SelectionDAG &DAG) const {
6403   MachineFunction &MF = DAG.getMachineFunction();
6404   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6405 
6406   EVT VT = Op.getValueType();
6407   SDLoc DL(Op);
6408   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6409 
6410   // TODO: Should this propagate fast-math-flags?
6411 
6412   switch (IntrinsicID) {
6413   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6414     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6415       return emitNonHSAIntrinsicError(DAG, DL, VT);
6416     return getPreloadedValue(DAG, *MFI, VT,
6417                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6418   }
6419   case Intrinsic::amdgcn_dispatch_ptr:
6420   case Intrinsic::amdgcn_queue_ptr: {
6421     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6422       DiagnosticInfoUnsupported BadIntrin(
6423           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6424           DL.getDebugLoc());
6425       DAG.getContext()->diagnose(BadIntrin);
6426       return DAG.getUNDEF(VT);
6427     }
6428 
6429     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6430       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6431     return getPreloadedValue(DAG, *MFI, VT, RegID);
6432   }
6433   case Intrinsic::amdgcn_implicitarg_ptr: {
6434     if (MFI->isEntryFunction())
6435       return getImplicitArgPtr(DAG, DL);
6436     return getPreloadedValue(DAG, *MFI, VT,
6437                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6438   }
6439   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6440     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6441       // This only makes sense to call in a kernel, so just lower to null.
6442       return DAG.getConstant(0, DL, VT);
6443     }
6444 
6445     return getPreloadedValue(DAG, *MFI, VT,
6446                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6447   }
6448   case Intrinsic::amdgcn_dispatch_id: {
6449     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6450   }
6451   case Intrinsic::amdgcn_rcp:
6452     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6453   case Intrinsic::amdgcn_rsq:
6454     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6455   case Intrinsic::amdgcn_rsq_legacy:
6456     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6457       return emitRemovedIntrinsicError(DAG, DL, VT);
6458     return SDValue();
6459   case Intrinsic::amdgcn_rcp_legacy:
6460     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6461       return emitRemovedIntrinsicError(DAG, DL, VT);
6462     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6463   case Intrinsic::amdgcn_rsq_clamp: {
6464     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6465       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6466 
6467     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6468     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6469     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6470 
6471     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6472     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6473                               DAG.getConstantFP(Max, DL, VT));
6474     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6475                        DAG.getConstantFP(Min, DL, VT));
6476   }
6477   case Intrinsic::r600_read_ngroups_x:
6478     if (Subtarget->isAmdHsaOS())
6479       return emitNonHSAIntrinsicError(DAG, DL, VT);
6480 
6481     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6482                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6483                                     false);
6484   case Intrinsic::r600_read_ngroups_y:
6485     if (Subtarget->isAmdHsaOS())
6486       return emitNonHSAIntrinsicError(DAG, DL, VT);
6487 
6488     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6489                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6490                                     false);
6491   case Intrinsic::r600_read_ngroups_z:
6492     if (Subtarget->isAmdHsaOS())
6493       return emitNonHSAIntrinsicError(DAG, DL, VT);
6494 
6495     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6496                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6497                                     false);
6498   case Intrinsic::r600_read_global_size_x:
6499     if (Subtarget->isAmdHsaOS())
6500       return emitNonHSAIntrinsicError(DAG, DL, VT);
6501 
6502     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6503                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6504                                     Align(4), false);
6505   case Intrinsic::r600_read_global_size_y:
6506     if (Subtarget->isAmdHsaOS())
6507       return emitNonHSAIntrinsicError(DAG, DL, VT);
6508 
6509     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6510                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6511                                     Align(4), false);
6512   case Intrinsic::r600_read_global_size_z:
6513     if (Subtarget->isAmdHsaOS())
6514       return emitNonHSAIntrinsicError(DAG, DL, VT);
6515 
6516     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6517                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6518                                     Align(4), false);
6519   case Intrinsic::r600_read_local_size_x:
6520     if (Subtarget->isAmdHsaOS())
6521       return emitNonHSAIntrinsicError(DAG, DL, VT);
6522 
6523     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6524                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6525   case Intrinsic::r600_read_local_size_y:
6526     if (Subtarget->isAmdHsaOS())
6527       return emitNonHSAIntrinsicError(DAG, DL, VT);
6528 
6529     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6530                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6531   case Intrinsic::r600_read_local_size_z:
6532     if (Subtarget->isAmdHsaOS())
6533       return emitNonHSAIntrinsicError(DAG, DL, VT);
6534 
6535     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6536                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6537   case Intrinsic::amdgcn_workgroup_id_x:
6538     return getPreloadedValue(DAG, *MFI, VT,
6539                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6540   case Intrinsic::amdgcn_workgroup_id_y:
6541     return getPreloadedValue(DAG, *MFI, VT,
6542                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6543   case Intrinsic::amdgcn_workgroup_id_z:
6544     return getPreloadedValue(DAG, *MFI, VT,
6545                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6546   case Intrinsic::amdgcn_workitem_id_x:
6547     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6548                           SDLoc(DAG.getEntryNode()),
6549                           MFI->getArgInfo().WorkItemIDX);
6550   case Intrinsic::amdgcn_workitem_id_y:
6551     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6552                           SDLoc(DAG.getEntryNode()),
6553                           MFI->getArgInfo().WorkItemIDY);
6554   case Intrinsic::amdgcn_workitem_id_z:
6555     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6556                           SDLoc(DAG.getEntryNode()),
6557                           MFI->getArgInfo().WorkItemIDZ);
6558   case Intrinsic::amdgcn_wavefrontsize:
6559     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6560                            SDLoc(Op), MVT::i32);
6561   case Intrinsic::amdgcn_s_buffer_load: {
6562     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6563     SDValue GLC;
6564     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6565     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6566                           IsGFX10 ? &DLC : nullptr))
6567       return Op;
6568     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6569                         DAG);
6570   }
6571   case Intrinsic::amdgcn_fdiv_fast:
6572     return lowerFDIV_FAST(Op, DAG);
6573   case Intrinsic::amdgcn_sin:
6574     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6575 
6576   case Intrinsic::amdgcn_cos:
6577     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6578 
6579   case Intrinsic::amdgcn_mul_u24:
6580     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6581   case Intrinsic::amdgcn_mul_i24:
6582     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6583 
6584   case Intrinsic::amdgcn_log_clamp: {
6585     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6586       return SDValue();
6587 
6588     DiagnosticInfoUnsupported BadIntrin(
6589       MF.getFunction(), "intrinsic not supported on subtarget",
6590       DL.getDebugLoc());
6591       DAG.getContext()->diagnose(BadIntrin);
6592       return DAG.getUNDEF(VT);
6593   }
6594   case Intrinsic::amdgcn_ldexp:
6595     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6596                        Op.getOperand(1), Op.getOperand(2));
6597 
6598   case Intrinsic::amdgcn_fract:
6599     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6600 
6601   case Intrinsic::amdgcn_class:
6602     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6603                        Op.getOperand(1), Op.getOperand(2));
6604   case Intrinsic::amdgcn_div_fmas:
6605     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6606                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6607                        Op.getOperand(4));
6608 
6609   case Intrinsic::amdgcn_div_fixup:
6610     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6611                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6612 
6613   case Intrinsic::amdgcn_div_scale: {
6614     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6615 
6616     // Translate to the operands expected by the machine instruction. The
6617     // first parameter must be the same as the first instruction.
6618     SDValue Numerator = Op.getOperand(1);
6619     SDValue Denominator = Op.getOperand(2);
6620 
6621     // Note this order is opposite of the machine instruction's operations,
6622     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6623     // intrinsic has the numerator as the first operand to match a normal
6624     // division operation.
6625 
6626     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6627 
6628     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6629                        Denominator, Numerator);
6630   }
6631   case Intrinsic::amdgcn_icmp: {
6632     // There is a Pat that handles this variant, so return it as-is.
6633     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6634         Op.getConstantOperandVal(2) == 0 &&
6635         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6636       return Op;
6637     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6638   }
6639   case Intrinsic::amdgcn_fcmp: {
6640     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6641   }
6642   case Intrinsic::amdgcn_ballot:
6643     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6644   case Intrinsic::amdgcn_fmed3:
6645     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6646                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6647   case Intrinsic::amdgcn_fdot2:
6648     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6649                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6650                        Op.getOperand(4));
6651   case Intrinsic::amdgcn_fmul_legacy:
6652     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6653                        Op.getOperand(1), Op.getOperand(2));
6654   case Intrinsic::amdgcn_sffbh:
6655     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6656   case Intrinsic::amdgcn_sbfe:
6657     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6658                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6659   case Intrinsic::amdgcn_ubfe:
6660     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6661                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6662   case Intrinsic::amdgcn_cvt_pkrtz:
6663   case Intrinsic::amdgcn_cvt_pknorm_i16:
6664   case Intrinsic::amdgcn_cvt_pknorm_u16:
6665   case Intrinsic::amdgcn_cvt_pk_i16:
6666   case Intrinsic::amdgcn_cvt_pk_u16: {
6667     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6668     EVT VT = Op.getValueType();
6669     unsigned Opcode;
6670 
6671     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6672       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6673     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6674       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6675     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6676       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6677     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6678       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6679     else
6680       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6681 
6682     if (isTypeLegal(VT))
6683       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6684 
6685     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6686                                Op.getOperand(1), Op.getOperand(2));
6687     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6688   }
6689   case Intrinsic::amdgcn_fmad_ftz:
6690     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6691                        Op.getOperand(2), Op.getOperand(3));
6692 
6693   case Intrinsic::amdgcn_if_break:
6694     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6695                                       Op->getOperand(1), Op->getOperand(2)), 0);
6696 
6697   case Intrinsic::amdgcn_groupstaticsize: {
6698     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6699     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6700       return Op;
6701 
6702     const Module *M = MF.getFunction().getParent();
6703     const GlobalValue *GV =
6704         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6705     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6706                                             SIInstrInfo::MO_ABS32_LO);
6707     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6708   }
6709   case Intrinsic::amdgcn_is_shared:
6710   case Intrinsic::amdgcn_is_private: {
6711     SDLoc SL(Op);
6712     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6713       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6714     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6715     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6716                                  Op.getOperand(1));
6717 
6718     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6719                                 DAG.getConstant(1, SL, MVT::i32));
6720     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6721   }
6722   case Intrinsic::amdgcn_alignbit:
6723     return DAG.getNode(ISD::FSHR, DL, VT,
6724                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6725   case Intrinsic::amdgcn_reloc_constant: {
6726     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6727     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6728     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6729     auto RelocSymbol = cast<GlobalVariable>(
6730         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6731     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6732                                             SIInstrInfo::MO_ABS32_LO);
6733     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6734   }
6735   default:
6736     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6737             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6738       return lowerImage(Op, ImageDimIntr, DAG, false);
6739 
6740     return Op;
6741   }
6742 }
6743 
6744 // This function computes an appropriate offset to pass to
6745 // MachineMemOperand::setOffset() based on the offset inputs to
6746 // an intrinsic.  If any of the offsets are non-contstant or
6747 // if VIndex is non-zero then this function returns 0.  Otherwise,
6748 // it returns the sum of VOffset, SOffset, and Offset.
6749 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6750                                       SDValue SOffset,
6751                                       SDValue Offset,
6752                                       SDValue VIndex = SDValue()) {
6753 
6754   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6755       !isa<ConstantSDNode>(Offset))
6756     return 0;
6757 
6758   if (VIndex) {
6759     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6760       return 0;
6761   }
6762 
6763   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6764          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6765          cast<ConstantSDNode>(Offset)->getSExtValue();
6766 }
6767 
6768 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6769                                                      SelectionDAG &DAG,
6770                                                      unsigned NewOpcode) const {
6771   SDLoc DL(Op);
6772 
6773   SDValue VData = Op.getOperand(2);
6774   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6775   SDValue Ops[] = {
6776     Op.getOperand(0), // Chain
6777     VData,            // vdata
6778     Op.getOperand(3), // rsrc
6779     DAG.getConstant(0, DL, MVT::i32), // vindex
6780     Offsets.first,    // voffset
6781     Op.getOperand(5), // soffset
6782     Offsets.second,   // offset
6783     Op.getOperand(6), // cachepolicy
6784     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6785   };
6786 
6787   auto *M = cast<MemSDNode>(Op);
6788   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6789 
6790   EVT MemVT = VData.getValueType();
6791   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6792                                  M->getMemOperand());
6793 }
6794 
6795 SDValue
6796 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6797                                                 unsigned NewOpcode) const {
6798   SDLoc DL(Op);
6799 
6800   SDValue VData = Op.getOperand(2);
6801   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6802   SDValue Ops[] = {
6803     Op.getOperand(0), // Chain
6804     VData,            // vdata
6805     Op.getOperand(3), // rsrc
6806     Op.getOperand(4), // vindex
6807     Offsets.first,    // voffset
6808     Op.getOperand(6), // soffset
6809     Offsets.second,   // offset
6810     Op.getOperand(7), // cachepolicy
6811     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6812   };
6813 
6814   auto *M = cast<MemSDNode>(Op);
6815   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6816                                                       Ops[3]));
6817 
6818   EVT MemVT = VData.getValueType();
6819   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6820                                  M->getMemOperand());
6821 }
6822 
6823 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6824                                                  SelectionDAG &DAG) const {
6825   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6826   SDLoc DL(Op);
6827 
6828   switch (IntrID) {
6829   case Intrinsic::amdgcn_ds_ordered_add:
6830   case Intrinsic::amdgcn_ds_ordered_swap: {
6831     MemSDNode *M = cast<MemSDNode>(Op);
6832     SDValue Chain = M->getOperand(0);
6833     SDValue M0 = M->getOperand(2);
6834     SDValue Value = M->getOperand(3);
6835     unsigned IndexOperand = M->getConstantOperandVal(7);
6836     unsigned WaveRelease = M->getConstantOperandVal(8);
6837     unsigned WaveDone = M->getConstantOperandVal(9);
6838 
6839     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6840     IndexOperand &= ~0x3f;
6841     unsigned CountDw = 0;
6842 
6843     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6844       CountDw = (IndexOperand >> 24) & 0xf;
6845       IndexOperand &= ~(0xf << 24);
6846 
6847       if (CountDw < 1 || CountDw > 4) {
6848         report_fatal_error(
6849             "ds_ordered_count: dword count must be between 1 and 4");
6850       }
6851     }
6852 
6853     if (IndexOperand)
6854       report_fatal_error("ds_ordered_count: bad index operand");
6855 
6856     if (WaveDone && !WaveRelease)
6857       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6858 
6859     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6860     unsigned ShaderType =
6861         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6862     unsigned Offset0 = OrderedCountIndex << 2;
6863     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6864                        (Instruction << 4);
6865 
6866     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6867       Offset1 |= (CountDw - 1) << 6;
6868 
6869     unsigned Offset = Offset0 | (Offset1 << 8);
6870 
6871     SDValue Ops[] = {
6872       Chain,
6873       Value,
6874       DAG.getTargetConstant(Offset, DL, MVT::i16),
6875       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6876     };
6877     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6878                                    M->getVTList(), Ops, M->getMemoryVT(),
6879                                    M->getMemOperand());
6880   }
6881   case Intrinsic::amdgcn_ds_fadd: {
6882     MemSDNode *M = cast<MemSDNode>(Op);
6883     unsigned Opc;
6884     switch (IntrID) {
6885     case Intrinsic::amdgcn_ds_fadd:
6886       Opc = ISD::ATOMIC_LOAD_FADD;
6887       break;
6888     }
6889 
6890     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6891                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6892                          M->getMemOperand());
6893   }
6894   case Intrinsic::amdgcn_atomic_inc:
6895   case Intrinsic::amdgcn_atomic_dec:
6896   case Intrinsic::amdgcn_ds_fmin:
6897   case Intrinsic::amdgcn_ds_fmax: {
6898     MemSDNode *M = cast<MemSDNode>(Op);
6899     unsigned Opc;
6900     switch (IntrID) {
6901     case Intrinsic::amdgcn_atomic_inc:
6902       Opc = AMDGPUISD::ATOMIC_INC;
6903       break;
6904     case Intrinsic::amdgcn_atomic_dec:
6905       Opc = AMDGPUISD::ATOMIC_DEC;
6906       break;
6907     case Intrinsic::amdgcn_ds_fmin:
6908       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6909       break;
6910     case Intrinsic::amdgcn_ds_fmax:
6911       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6912       break;
6913     default:
6914       llvm_unreachable("Unknown intrinsic!");
6915     }
6916     SDValue Ops[] = {
6917       M->getOperand(0), // Chain
6918       M->getOperand(2), // Ptr
6919       M->getOperand(3)  // Value
6920     };
6921 
6922     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6923                                    M->getMemoryVT(), M->getMemOperand());
6924   }
6925   case Intrinsic::amdgcn_buffer_load:
6926   case Intrinsic::amdgcn_buffer_load_format: {
6927     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6928     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6929     unsigned IdxEn = 1;
6930     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6931       IdxEn = Idx->getZExtValue() != 0;
6932     SDValue Ops[] = {
6933       Op.getOperand(0), // Chain
6934       Op.getOperand(2), // rsrc
6935       Op.getOperand(3), // vindex
6936       SDValue(),        // voffset -- will be set by setBufferOffsets
6937       SDValue(),        // soffset -- will be set by setBufferOffsets
6938       SDValue(),        // offset -- will be set by setBufferOffsets
6939       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6940       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6941     };
6942 
6943     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6944     // We don't know the offset if vindex is non-zero, so clear it.
6945     if (IdxEn)
6946       Offset = 0;
6947 
6948     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6949         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6950 
6951     EVT VT = Op.getValueType();
6952     EVT IntVT = VT.changeTypeToInteger();
6953     auto *M = cast<MemSDNode>(Op);
6954     M->getMemOperand()->setOffset(Offset);
6955     EVT LoadVT = Op.getValueType();
6956 
6957     if (LoadVT.getScalarType() == MVT::f16)
6958       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6959                                  M, DAG, Ops);
6960 
6961     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6962     if (LoadVT.getScalarType() == MVT::i8 ||
6963         LoadVT.getScalarType() == MVT::i16)
6964       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6965 
6966     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6967                                M->getMemOperand(), DAG);
6968   }
6969   case Intrinsic::amdgcn_raw_buffer_load:
6970   case Intrinsic::amdgcn_raw_buffer_load_format: {
6971     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6972 
6973     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6974     SDValue Ops[] = {
6975       Op.getOperand(0), // Chain
6976       Op.getOperand(2), // rsrc
6977       DAG.getConstant(0, DL, MVT::i32), // vindex
6978       Offsets.first,    // voffset
6979       Op.getOperand(4), // soffset
6980       Offsets.second,   // offset
6981       Op.getOperand(5), // cachepolicy, swizzled buffer
6982       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6983     };
6984 
6985     auto *M = cast<MemSDNode>(Op);
6986     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6987     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6988   }
6989   case Intrinsic::amdgcn_struct_buffer_load:
6990   case Intrinsic::amdgcn_struct_buffer_load_format: {
6991     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6992 
6993     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6994     SDValue Ops[] = {
6995       Op.getOperand(0), // Chain
6996       Op.getOperand(2), // rsrc
6997       Op.getOperand(3), // vindex
6998       Offsets.first,    // voffset
6999       Op.getOperand(5), // soffset
7000       Offsets.second,   // offset
7001       Op.getOperand(6), // cachepolicy, swizzled buffer
7002       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7003     };
7004 
7005     auto *M = cast<MemSDNode>(Op);
7006     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
7007                                                         Ops[2]));
7008     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7009   }
7010   case Intrinsic::amdgcn_tbuffer_load: {
7011     MemSDNode *M = cast<MemSDNode>(Op);
7012     EVT LoadVT = Op.getValueType();
7013 
7014     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7015     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7016     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7017     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7018     unsigned IdxEn = 1;
7019     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
7020       IdxEn = Idx->getZExtValue() != 0;
7021     SDValue Ops[] = {
7022       Op.getOperand(0),  // Chain
7023       Op.getOperand(2),  // rsrc
7024       Op.getOperand(3),  // vindex
7025       Op.getOperand(4),  // voffset
7026       Op.getOperand(5),  // soffset
7027       Op.getOperand(6),  // offset
7028       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7029       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7030       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7031     };
7032 
7033     if (LoadVT.getScalarType() == MVT::f16)
7034       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7035                                  M, DAG, Ops);
7036     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7037                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7038                                DAG);
7039   }
7040   case Intrinsic::amdgcn_raw_tbuffer_load: {
7041     MemSDNode *M = cast<MemSDNode>(Op);
7042     EVT LoadVT = Op.getValueType();
7043     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7044 
7045     SDValue Ops[] = {
7046       Op.getOperand(0),  // Chain
7047       Op.getOperand(2),  // rsrc
7048       DAG.getConstant(0, DL, MVT::i32), // vindex
7049       Offsets.first,     // voffset
7050       Op.getOperand(4),  // soffset
7051       Offsets.second,    // offset
7052       Op.getOperand(5),  // format
7053       Op.getOperand(6),  // cachepolicy, swizzled buffer
7054       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7055     };
7056 
7057     if (LoadVT.getScalarType() == MVT::f16)
7058       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7059                                  M, DAG, Ops);
7060     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7061                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7062                                DAG);
7063   }
7064   case Intrinsic::amdgcn_struct_tbuffer_load: {
7065     MemSDNode *M = cast<MemSDNode>(Op);
7066     EVT LoadVT = Op.getValueType();
7067     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7068 
7069     SDValue Ops[] = {
7070       Op.getOperand(0),  // Chain
7071       Op.getOperand(2),  // rsrc
7072       Op.getOperand(3),  // vindex
7073       Offsets.first,     // voffset
7074       Op.getOperand(5),  // soffset
7075       Offsets.second,    // offset
7076       Op.getOperand(6),  // format
7077       Op.getOperand(7),  // cachepolicy, swizzled buffer
7078       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7079     };
7080 
7081     if (LoadVT.getScalarType() == MVT::f16)
7082       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7083                                  M, DAG, Ops);
7084     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7085                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7086                                DAG);
7087   }
7088   case Intrinsic::amdgcn_buffer_atomic_swap:
7089   case Intrinsic::amdgcn_buffer_atomic_add:
7090   case Intrinsic::amdgcn_buffer_atomic_sub:
7091   case Intrinsic::amdgcn_buffer_atomic_csub:
7092   case Intrinsic::amdgcn_buffer_atomic_smin:
7093   case Intrinsic::amdgcn_buffer_atomic_umin:
7094   case Intrinsic::amdgcn_buffer_atomic_smax:
7095   case Intrinsic::amdgcn_buffer_atomic_umax:
7096   case Intrinsic::amdgcn_buffer_atomic_and:
7097   case Intrinsic::amdgcn_buffer_atomic_or:
7098   case Intrinsic::amdgcn_buffer_atomic_xor:
7099   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7100     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7101     unsigned IdxEn = 1;
7102     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7103       IdxEn = Idx->getZExtValue() != 0;
7104     SDValue Ops[] = {
7105       Op.getOperand(0), // Chain
7106       Op.getOperand(2), // vdata
7107       Op.getOperand(3), // rsrc
7108       Op.getOperand(4), // vindex
7109       SDValue(),        // voffset -- will be set by setBufferOffsets
7110       SDValue(),        // soffset -- will be set by setBufferOffsets
7111       SDValue(),        // offset -- will be set by setBufferOffsets
7112       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7113       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7114     };
7115     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7116     // We don't know the offset if vindex is non-zero, so clear it.
7117     if (IdxEn)
7118       Offset = 0;
7119     EVT VT = Op.getValueType();
7120 
7121     auto *M = cast<MemSDNode>(Op);
7122     M->getMemOperand()->setOffset(Offset);
7123     unsigned Opcode = 0;
7124 
7125     switch (IntrID) {
7126     case Intrinsic::amdgcn_buffer_atomic_swap:
7127       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7128       break;
7129     case Intrinsic::amdgcn_buffer_atomic_add:
7130       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7131       break;
7132     case Intrinsic::amdgcn_buffer_atomic_sub:
7133       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7134       break;
7135     case Intrinsic::amdgcn_buffer_atomic_csub:
7136       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7137       break;
7138     case Intrinsic::amdgcn_buffer_atomic_smin:
7139       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7140       break;
7141     case Intrinsic::amdgcn_buffer_atomic_umin:
7142       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7143       break;
7144     case Intrinsic::amdgcn_buffer_atomic_smax:
7145       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7146       break;
7147     case Intrinsic::amdgcn_buffer_atomic_umax:
7148       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7149       break;
7150     case Intrinsic::amdgcn_buffer_atomic_and:
7151       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7152       break;
7153     case Intrinsic::amdgcn_buffer_atomic_or:
7154       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7155       break;
7156     case Intrinsic::amdgcn_buffer_atomic_xor:
7157       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7158       break;
7159     case Intrinsic::amdgcn_buffer_atomic_fadd:
7160       if (!Op.getValue(0).use_empty()) {
7161         DiagnosticInfoUnsupported
7162           NoFpRet(DAG.getMachineFunction().getFunction(),
7163                   "return versions of fp atomics not supported",
7164                   DL.getDebugLoc(), DS_Error);
7165         DAG.getContext()->diagnose(NoFpRet);
7166         return SDValue();
7167       }
7168       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7169       break;
7170     default:
7171       llvm_unreachable("unhandled atomic opcode");
7172     }
7173 
7174     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7175                                    M->getMemOperand());
7176   }
7177   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7178     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7179   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7180     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7181   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7182     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7183   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7184     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7185   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7186     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7187   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7188     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7189   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7190     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7191   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7192     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7193   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7194     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7195   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7196     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7197   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7198     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7199   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7200     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7201   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7202     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7203   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7204     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7205   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7206     return lowerStructBufferAtomicIntrin(Op, DAG,
7207                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7208   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7209     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7210   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7211     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7212   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7213     return lowerStructBufferAtomicIntrin(Op, DAG,
7214                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7215   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7216     return lowerStructBufferAtomicIntrin(Op, DAG,
7217                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7218   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7219     return lowerStructBufferAtomicIntrin(Op, DAG,
7220                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7221   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7222     return lowerStructBufferAtomicIntrin(Op, DAG,
7223                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7224   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7225     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7226   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7227     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7228   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7229     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7230   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7231     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7232   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7233     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7234 
7235   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7236     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7237     unsigned IdxEn = 1;
7238     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7239       IdxEn = Idx->getZExtValue() != 0;
7240     SDValue Ops[] = {
7241       Op.getOperand(0), // Chain
7242       Op.getOperand(2), // src
7243       Op.getOperand(3), // cmp
7244       Op.getOperand(4), // rsrc
7245       Op.getOperand(5), // vindex
7246       SDValue(),        // voffset -- will be set by setBufferOffsets
7247       SDValue(),        // soffset -- will be set by setBufferOffsets
7248       SDValue(),        // offset -- will be set by setBufferOffsets
7249       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7250       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7251     };
7252     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7253     // We don't know the offset if vindex is non-zero, so clear it.
7254     if (IdxEn)
7255       Offset = 0;
7256     EVT VT = Op.getValueType();
7257     auto *M = cast<MemSDNode>(Op);
7258     M->getMemOperand()->setOffset(Offset);
7259 
7260     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7261                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7262   }
7263   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7264     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7265     SDValue Ops[] = {
7266       Op.getOperand(0), // Chain
7267       Op.getOperand(2), // src
7268       Op.getOperand(3), // cmp
7269       Op.getOperand(4), // rsrc
7270       DAG.getConstant(0, DL, MVT::i32), // vindex
7271       Offsets.first,    // voffset
7272       Op.getOperand(6), // soffset
7273       Offsets.second,   // offset
7274       Op.getOperand(7), // cachepolicy
7275       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7276     };
7277     EVT VT = Op.getValueType();
7278     auto *M = cast<MemSDNode>(Op);
7279     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7280 
7281     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7282                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7283   }
7284   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7285     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7286     SDValue Ops[] = {
7287       Op.getOperand(0), // Chain
7288       Op.getOperand(2), // src
7289       Op.getOperand(3), // cmp
7290       Op.getOperand(4), // rsrc
7291       Op.getOperand(5), // vindex
7292       Offsets.first,    // voffset
7293       Op.getOperand(7), // soffset
7294       Offsets.second,   // offset
7295       Op.getOperand(8), // cachepolicy
7296       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7297     };
7298     EVT VT = Op.getValueType();
7299     auto *M = cast<MemSDNode>(Op);
7300     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7301                                                         Ops[4]));
7302 
7303     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7304                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7305   }
7306   case Intrinsic::amdgcn_global_atomic_fadd: {
7307     if (!Op.getValue(0).use_empty()) {
7308       DiagnosticInfoUnsupported
7309         NoFpRet(DAG.getMachineFunction().getFunction(),
7310                 "return versions of fp atomics not supported",
7311                 DL.getDebugLoc(), DS_Error);
7312       DAG.getContext()->diagnose(NoFpRet);
7313       return SDValue();
7314     }
7315     MemSDNode *M = cast<MemSDNode>(Op);
7316     SDValue Ops[] = {
7317       M->getOperand(0), // Chain
7318       M->getOperand(2), // Ptr
7319       M->getOperand(3)  // Value
7320     };
7321 
7322     EVT VT = Op.getOperand(3).getValueType();
7323     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7324                          DAG.getVTList(VT, MVT::Other), Ops,
7325                          M->getMemOperand());
7326   }
7327   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7328     SDLoc DL(Op);
7329     MemSDNode *M = cast<MemSDNode>(Op);
7330     SDValue NodePtr = M->getOperand(2);
7331     SDValue RayExtent = M->getOperand(3);
7332     SDValue RayOrigin = M->getOperand(4);
7333     SDValue RayDir = M->getOperand(5);
7334     SDValue RayInvDir = M->getOperand(6);
7335     SDValue TDescr = M->getOperand(7);
7336 
7337     assert(NodePtr.getValueType() == MVT::i32 ||
7338            NodePtr.getValueType() == MVT::i64);
7339     assert(RayDir.getValueType() == MVT::v4f16 ||
7340            RayDir.getValueType() == MVT::v4f32);
7341 
7342     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7343     bool Is64 = NodePtr.getValueType() == MVT::i64;
7344     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7345                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7346                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7347                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7348 
7349     SmallVector<SDValue, 16> Ops;
7350 
7351     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7352       SmallVector<SDValue, 3> Lanes;
7353       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7354       if (Lanes[0].getValueSizeInBits() == 32) {
7355         for (unsigned I = 0; I < 3; ++I)
7356           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7357       } else {
7358         if (IsAligned) {
7359           Ops.push_back(
7360             DAG.getBitcast(MVT::i32,
7361                            DAG.getBuildVector(MVT::v2f16, DL,
7362                                               { Lanes[0], Lanes[1] })));
7363           Ops.push_back(Lanes[2]);
7364         } else {
7365           SDValue Elt0 = Ops.pop_back_val();
7366           Ops.push_back(
7367             DAG.getBitcast(MVT::i32,
7368                            DAG.getBuildVector(MVT::v2f16, DL,
7369                                               { Elt0, Lanes[0] })));
7370           Ops.push_back(
7371             DAG.getBitcast(MVT::i32,
7372                            DAG.getBuildVector(MVT::v2f16, DL,
7373                                               { Lanes[1], Lanes[2] })));
7374         }
7375       }
7376     };
7377 
7378     if (Is64)
7379       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7380     else
7381       Ops.push_back(NodePtr);
7382 
7383     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7384     packLanes(RayOrigin, true);
7385     packLanes(RayDir, true);
7386     packLanes(RayInvDir, false);
7387     Ops.push_back(TDescr);
7388     if (IsA16)
7389       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7390     Ops.push_back(M->getChain());
7391 
7392     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7393     MachineMemOperand *MemRef = M->getMemOperand();
7394     DAG.setNodeMemRefs(NewNode, {MemRef});
7395     return SDValue(NewNode, 0);
7396   }
7397   default:
7398     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7399             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7400       return lowerImage(Op, ImageDimIntr, DAG, true);
7401 
7402     return SDValue();
7403   }
7404 }
7405 
7406 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7407 // dwordx4 if on SI.
7408 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7409                                               SDVTList VTList,
7410                                               ArrayRef<SDValue> Ops, EVT MemVT,
7411                                               MachineMemOperand *MMO,
7412                                               SelectionDAG &DAG) const {
7413   EVT VT = VTList.VTs[0];
7414   EVT WidenedVT = VT;
7415   EVT WidenedMemVT = MemVT;
7416   if (!Subtarget->hasDwordx3LoadStores() &&
7417       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7418     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7419                                  WidenedVT.getVectorElementType(), 4);
7420     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7421                                     WidenedMemVT.getVectorElementType(), 4);
7422     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7423   }
7424 
7425   assert(VTList.NumVTs == 2);
7426   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7427 
7428   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7429                                        WidenedMemVT, MMO);
7430   if (WidenedVT != VT) {
7431     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7432                                DAG.getVectorIdxConstant(0, DL));
7433     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7434   }
7435   return NewOp;
7436 }
7437 
7438 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7439                                          bool ImageStore) const {
7440   EVT StoreVT = VData.getValueType();
7441 
7442   // No change for f16 and legal vector D16 types.
7443   if (!StoreVT.isVector())
7444     return VData;
7445 
7446   SDLoc DL(VData);
7447   unsigned NumElements = StoreVT.getVectorNumElements();
7448 
7449   if (Subtarget->hasUnpackedD16VMem()) {
7450     // We need to unpack the packed data to store.
7451     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7452     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7453 
7454     EVT EquivStoreVT =
7455         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7456     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7457     return DAG.UnrollVectorOp(ZExt.getNode());
7458   }
7459 
7460   // The sq block of gfx8.1 does not estimate register use correctly for d16
7461   // image store instructions. The data operand is computed as if it were not a
7462   // d16 image instruction.
7463   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7464     // Bitcast to i16
7465     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7466     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7467 
7468     // Decompose into scalars
7469     SmallVector<SDValue, 4> Elts;
7470     DAG.ExtractVectorElements(IntVData, Elts);
7471 
7472     // Group pairs of i16 into v2i16 and bitcast to i32
7473     SmallVector<SDValue, 4> PackedElts;
7474     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7475       SDValue Pair =
7476           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7477       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7478       PackedElts.push_back(IntPair);
7479     }
7480     if ((NumElements % 2) == 1) {
7481       // Handle v3i16
7482       unsigned I = Elts.size() / 2;
7483       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7484                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7485       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7486       PackedElts.push_back(IntPair);
7487     }
7488 
7489     // Pad using UNDEF
7490     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7491 
7492     // Build final vector
7493     EVT VecVT =
7494         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7495     return DAG.getBuildVector(VecVT, DL, PackedElts);
7496   }
7497 
7498   if (NumElements == 3) {
7499     EVT IntStoreVT =
7500         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7501     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7502 
7503     EVT WidenedStoreVT = EVT::getVectorVT(
7504         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7505     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7506                                          WidenedStoreVT.getStoreSizeInBits());
7507     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7508     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7509   }
7510 
7511   assert(isTypeLegal(StoreVT));
7512   return VData;
7513 }
7514 
7515 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7516                                               SelectionDAG &DAG) const {
7517   SDLoc DL(Op);
7518   SDValue Chain = Op.getOperand(0);
7519   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7520   MachineFunction &MF = DAG.getMachineFunction();
7521 
7522   switch (IntrinsicID) {
7523   case Intrinsic::amdgcn_exp_compr: {
7524     SDValue Src0 = Op.getOperand(4);
7525     SDValue Src1 = Op.getOperand(5);
7526     // Hack around illegal type on SI by directly selecting it.
7527     if (isTypeLegal(Src0.getValueType()))
7528       return SDValue();
7529 
7530     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7531     SDValue Undef = DAG.getUNDEF(MVT::f32);
7532     const SDValue Ops[] = {
7533       Op.getOperand(2), // tgt
7534       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7535       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7536       Undef, // src2
7537       Undef, // src3
7538       Op.getOperand(7), // vm
7539       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7540       Op.getOperand(3), // en
7541       Op.getOperand(0) // Chain
7542     };
7543 
7544     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7545     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7546   }
7547   case Intrinsic::amdgcn_s_barrier: {
7548     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7549       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7550       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7551       if (WGSize <= ST.getWavefrontSize())
7552         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7553                                           Op.getOperand(0)), 0);
7554     }
7555     return SDValue();
7556   };
7557   case Intrinsic::amdgcn_tbuffer_store: {
7558     SDValue VData = Op.getOperand(2);
7559     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7560     if (IsD16)
7561       VData = handleD16VData(VData, DAG);
7562     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7563     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7564     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7565     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7566     unsigned IdxEn = 1;
7567     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7568       IdxEn = Idx->getZExtValue() != 0;
7569     SDValue Ops[] = {
7570       Chain,
7571       VData,             // vdata
7572       Op.getOperand(3),  // rsrc
7573       Op.getOperand(4),  // vindex
7574       Op.getOperand(5),  // voffset
7575       Op.getOperand(6),  // soffset
7576       Op.getOperand(7),  // offset
7577       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7578       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7579       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7580     };
7581     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7582                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7583     MemSDNode *M = cast<MemSDNode>(Op);
7584     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7585                                    M->getMemoryVT(), M->getMemOperand());
7586   }
7587 
7588   case Intrinsic::amdgcn_struct_tbuffer_store: {
7589     SDValue VData = Op.getOperand(2);
7590     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7591     if (IsD16)
7592       VData = handleD16VData(VData, DAG);
7593     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7594     SDValue Ops[] = {
7595       Chain,
7596       VData,             // vdata
7597       Op.getOperand(3),  // rsrc
7598       Op.getOperand(4),  // vindex
7599       Offsets.first,     // voffset
7600       Op.getOperand(6),  // soffset
7601       Offsets.second,    // offset
7602       Op.getOperand(7),  // format
7603       Op.getOperand(8),  // cachepolicy, swizzled buffer
7604       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7605     };
7606     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7607                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7608     MemSDNode *M = cast<MemSDNode>(Op);
7609     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7610                                    M->getMemoryVT(), M->getMemOperand());
7611   }
7612 
7613   case Intrinsic::amdgcn_raw_tbuffer_store: {
7614     SDValue VData = Op.getOperand(2);
7615     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7616     if (IsD16)
7617       VData = handleD16VData(VData, DAG);
7618     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7619     SDValue Ops[] = {
7620       Chain,
7621       VData,             // vdata
7622       Op.getOperand(3),  // rsrc
7623       DAG.getConstant(0, DL, MVT::i32), // vindex
7624       Offsets.first,     // voffset
7625       Op.getOperand(5),  // soffset
7626       Offsets.second,    // offset
7627       Op.getOperand(6),  // format
7628       Op.getOperand(7),  // cachepolicy, swizzled buffer
7629       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7630     };
7631     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7632                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7633     MemSDNode *M = cast<MemSDNode>(Op);
7634     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7635                                    M->getMemoryVT(), M->getMemOperand());
7636   }
7637 
7638   case Intrinsic::amdgcn_buffer_store:
7639   case Intrinsic::amdgcn_buffer_store_format: {
7640     SDValue VData = Op.getOperand(2);
7641     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7642     if (IsD16)
7643       VData = handleD16VData(VData, DAG);
7644     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7645     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7646     unsigned IdxEn = 1;
7647     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7648       IdxEn = Idx->getZExtValue() != 0;
7649     SDValue Ops[] = {
7650       Chain,
7651       VData,
7652       Op.getOperand(3), // rsrc
7653       Op.getOperand(4), // vindex
7654       SDValue(), // voffset -- will be set by setBufferOffsets
7655       SDValue(), // soffset -- will be set by setBufferOffsets
7656       SDValue(), // offset -- will be set by setBufferOffsets
7657       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7658       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7659     };
7660     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7661     // We don't know the offset if vindex is non-zero, so clear it.
7662     if (IdxEn)
7663       Offset = 0;
7664     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7665                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7666     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7667     MemSDNode *M = cast<MemSDNode>(Op);
7668     M->getMemOperand()->setOffset(Offset);
7669 
7670     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7671     EVT VDataType = VData.getValueType().getScalarType();
7672     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7673       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7674 
7675     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7676                                    M->getMemoryVT(), M->getMemOperand());
7677   }
7678 
7679   case Intrinsic::amdgcn_raw_buffer_store:
7680   case Intrinsic::amdgcn_raw_buffer_store_format: {
7681     const bool IsFormat =
7682         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7683 
7684     SDValue VData = Op.getOperand(2);
7685     EVT VDataVT = VData.getValueType();
7686     EVT EltType = VDataVT.getScalarType();
7687     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7688     if (IsD16) {
7689       VData = handleD16VData(VData, DAG);
7690       VDataVT = VData.getValueType();
7691     }
7692 
7693     if (!isTypeLegal(VDataVT)) {
7694       VData =
7695           DAG.getNode(ISD::BITCAST, DL,
7696                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7697     }
7698 
7699     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7700     SDValue Ops[] = {
7701       Chain,
7702       VData,
7703       Op.getOperand(3), // rsrc
7704       DAG.getConstant(0, DL, MVT::i32), // vindex
7705       Offsets.first,    // voffset
7706       Op.getOperand(5), // soffset
7707       Offsets.second,   // offset
7708       Op.getOperand(6), // cachepolicy, swizzled buffer
7709       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7710     };
7711     unsigned Opc =
7712         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7713     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7714     MemSDNode *M = cast<MemSDNode>(Op);
7715     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7716 
7717     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7718     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7719       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7720 
7721     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7722                                    M->getMemoryVT(), M->getMemOperand());
7723   }
7724 
7725   case Intrinsic::amdgcn_struct_buffer_store:
7726   case Intrinsic::amdgcn_struct_buffer_store_format: {
7727     const bool IsFormat =
7728         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7729 
7730     SDValue VData = Op.getOperand(2);
7731     EVT VDataVT = VData.getValueType();
7732     EVT EltType = VDataVT.getScalarType();
7733     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7734 
7735     if (IsD16) {
7736       VData = handleD16VData(VData, DAG);
7737       VDataVT = VData.getValueType();
7738     }
7739 
7740     if (!isTypeLegal(VDataVT)) {
7741       VData =
7742           DAG.getNode(ISD::BITCAST, DL,
7743                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7744     }
7745 
7746     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7747     SDValue Ops[] = {
7748       Chain,
7749       VData,
7750       Op.getOperand(3), // rsrc
7751       Op.getOperand(4), // vindex
7752       Offsets.first,    // voffset
7753       Op.getOperand(6), // soffset
7754       Offsets.second,   // offset
7755       Op.getOperand(7), // cachepolicy, swizzled buffer
7756       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7757     };
7758     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7759                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7760     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7761     MemSDNode *M = cast<MemSDNode>(Op);
7762     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7763                                                         Ops[3]));
7764 
7765     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7766     EVT VDataType = VData.getValueType().getScalarType();
7767     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7768       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7769 
7770     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7771                                    M->getMemoryVT(), M->getMemOperand());
7772   }
7773   case Intrinsic::amdgcn_end_cf:
7774     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7775                                       Op->getOperand(2), Chain), 0);
7776 
7777   default: {
7778     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7779             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7780       return lowerImage(Op, ImageDimIntr, DAG, true);
7781 
7782     return Op;
7783   }
7784   }
7785 }
7786 
7787 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7788 // offset (the offset that is included in bounds checking and swizzling, to be
7789 // split between the instruction's voffset and immoffset fields) and soffset
7790 // (the offset that is excluded from bounds checking and swizzling, to go in
7791 // the instruction's soffset field).  This function takes the first kind of
7792 // offset and figures out how to split it between voffset and immoffset.
7793 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7794     SDValue Offset, SelectionDAG &DAG) const {
7795   SDLoc DL(Offset);
7796   const unsigned MaxImm = 4095;
7797   SDValue N0 = Offset;
7798   ConstantSDNode *C1 = nullptr;
7799 
7800   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7801     N0 = SDValue();
7802   else if (DAG.isBaseWithConstantOffset(N0)) {
7803     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7804     N0 = N0.getOperand(0);
7805   }
7806 
7807   if (C1) {
7808     unsigned ImmOffset = C1->getZExtValue();
7809     // If the immediate value is too big for the immoffset field, put the value
7810     // and -4096 into the immoffset field so that the value that is copied/added
7811     // for the voffset field is a multiple of 4096, and it stands more chance
7812     // of being CSEd with the copy/add for another similar load/store.
7813     // However, do not do that rounding down to a multiple of 4096 if that is a
7814     // negative number, as it appears to be illegal to have a negative offset
7815     // in the vgpr, even if adding the immediate offset makes it positive.
7816     unsigned Overflow = ImmOffset & ~MaxImm;
7817     ImmOffset -= Overflow;
7818     if ((int32_t)Overflow < 0) {
7819       Overflow += ImmOffset;
7820       ImmOffset = 0;
7821     }
7822     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7823     if (Overflow) {
7824       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7825       if (!N0)
7826         N0 = OverflowVal;
7827       else {
7828         SDValue Ops[] = { N0, OverflowVal };
7829         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7830       }
7831     }
7832   }
7833   if (!N0)
7834     N0 = DAG.getConstant(0, DL, MVT::i32);
7835   if (!C1)
7836     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7837   return {N0, SDValue(C1, 0)};
7838 }
7839 
7840 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7841 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7842 // pointed to by Offsets.
7843 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7844                                             SelectionDAG &DAG, SDValue *Offsets,
7845                                             Align Alignment) const {
7846   SDLoc DL(CombinedOffset);
7847   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7848     uint32_t Imm = C->getZExtValue();
7849     uint32_t SOffset, ImmOffset;
7850     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7851                                  Alignment)) {
7852       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7853       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7854       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7855       return SOffset + ImmOffset;
7856     }
7857   }
7858   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7859     SDValue N0 = CombinedOffset.getOperand(0);
7860     SDValue N1 = CombinedOffset.getOperand(1);
7861     uint32_t SOffset, ImmOffset;
7862     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7863     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7864                                                 Subtarget, Alignment)) {
7865       Offsets[0] = N0;
7866       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7867       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7868       return 0;
7869     }
7870   }
7871   Offsets[0] = CombinedOffset;
7872   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7873   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7874   return 0;
7875 }
7876 
7877 // Handle 8 bit and 16 bit buffer loads
7878 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7879                                                      EVT LoadVT, SDLoc DL,
7880                                                      ArrayRef<SDValue> Ops,
7881                                                      MemSDNode *M) const {
7882   EVT IntVT = LoadVT.changeTypeToInteger();
7883   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7884          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7885 
7886   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7887   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7888                                                Ops, IntVT,
7889                                                M->getMemOperand());
7890   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7891   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7892 
7893   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7894 }
7895 
7896 // Handle 8 bit and 16 bit buffer stores
7897 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7898                                                       EVT VDataType, SDLoc DL,
7899                                                       SDValue Ops[],
7900                                                       MemSDNode *M) const {
7901   if (VDataType == MVT::f16)
7902     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7903 
7904   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7905   Ops[1] = BufferStoreExt;
7906   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7907                                  AMDGPUISD::BUFFER_STORE_SHORT;
7908   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7909   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7910                                      M->getMemOperand());
7911 }
7912 
7913 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7914                                  ISD::LoadExtType ExtType, SDValue Op,
7915                                  const SDLoc &SL, EVT VT) {
7916   if (VT.bitsLT(Op.getValueType()))
7917     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7918 
7919   switch (ExtType) {
7920   case ISD::SEXTLOAD:
7921     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7922   case ISD::ZEXTLOAD:
7923     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7924   case ISD::EXTLOAD:
7925     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7926   case ISD::NON_EXTLOAD:
7927     return Op;
7928   }
7929 
7930   llvm_unreachable("invalid ext type");
7931 }
7932 
7933 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7934   SelectionDAG &DAG = DCI.DAG;
7935   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7936     return SDValue();
7937 
7938   // FIXME: Constant loads should all be marked invariant.
7939   unsigned AS = Ld->getAddressSpace();
7940   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7941       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7942       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7943     return SDValue();
7944 
7945   // Don't do this early, since it may interfere with adjacent load merging for
7946   // illegal types. We can avoid losing alignment information for exotic types
7947   // pre-legalize.
7948   EVT MemVT = Ld->getMemoryVT();
7949   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7950       MemVT.getSizeInBits() >= 32)
7951     return SDValue();
7952 
7953   SDLoc SL(Ld);
7954 
7955   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7956          "unexpected vector extload");
7957 
7958   // TODO: Drop only high part of range.
7959   SDValue Ptr = Ld->getBasePtr();
7960   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7961                                 MVT::i32, SL, Ld->getChain(), Ptr,
7962                                 Ld->getOffset(),
7963                                 Ld->getPointerInfo(), MVT::i32,
7964                                 Ld->getAlignment(),
7965                                 Ld->getMemOperand()->getFlags(),
7966                                 Ld->getAAInfo(),
7967                                 nullptr); // Drop ranges
7968 
7969   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7970   if (MemVT.isFloatingPoint()) {
7971     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7972            "unexpected fp extload");
7973     TruncVT = MemVT.changeTypeToInteger();
7974   }
7975 
7976   SDValue Cvt = NewLoad;
7977   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7978     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7979                       DAG.getValueType(TruncVT));
7980   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7981              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7982     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7983   } else {
7984     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7985   }
7986 
7987   EVT VT = Ld->getValueType(0);
7988   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7989 
7990   DCI.AddToWorklist(Cvt.getNode());
7991 
7992   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7993   // the appropriate extension from the 32-bit load.
7994   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7995   DCI.AddToWorklist(Cvt.getNode());
7996 
7997   // Handle conversion back to floating point if necessary.
7998   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7999 
8000   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8001 }
8002 
8003 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8004   SDLoc DL(Op);
8005   LoadSDNode *Load = cast<LoadSDNode>(Op);
8006   ISD::LoadExtType ExtType = Load->getExtensionType();
8007   EVT MemVT = Load->getMemoryVT();
8008 
8009   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8010     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8011       return SDValue();
8012 
8013     // FIXME: Copied from PPC
8014     // First, load into 32 bits, then truncate to 1 bit.
8015 
8016     SDValue Chain = Load->getChain();
8017     SDValue BasePtr = Load->getBasePtr();
8018     MachineMemOperand *MMO = Load->getMemOperand();
8019 
8020     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8021 
8022     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8023                                    BasePtr, RealMemVT, MMO);
8024 
8025     if (!MemVT.isVector()) {
8026       SDValue Ops[] = {
8027         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8028         NewLD.getValue(1)
8029       };
8030 
8031       return DAG.getMergeValues(Ops, DL);
8032     }
8033 
8034     SmallVector<SDValue, 3> Elts;
8035     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8036       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8037                                 DAG.getConstant(I, DL, MVT::i32));
8038 
8039       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8040     }
8041 
8042     SDValue Ops[] = {
8043       DAG.getBuildVector(MemVT, DL, Elts),
8044       NewLD.getValue(1)
8045     };
8046 
8047     return DAG.getMergeValues(Ops, DL);
8048   }
8049 
8050   if (!MemVT.isVector())
8051     return SDValue();
8052 
8053   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8054          "Custom lowering for non-i32 vectors hasn't been implemented.");
8055 
8056   unsigned Alignment = Load->getAlignment();
8057   unsigned AS = Load->getAddressSpace();
8058   if (Subtarget->hasLDSMisalignedBug() &&
8059       AS == AMDGPUAS::FLAT_ADDRESS &&
8060       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8061     return SplitVectorLoad(Op, DAG);
8062   }
8063 
8064   MachineFunction &MF = DAG.getMachineFunction();
8065   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8066   // If there is a possibilty that flat instruction access scratch memory
8067   // then we need to use the same legalization rules we use for private.
8068   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8069       !Subtarget->hasMultiDwordFlatScratchAddressing())
8070     AS = MFI->hasFlatScratchInit() ?
8071          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8072 
8073   unsigned NumElements = MemVT.getVectorNumElements();
8074 
8075   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8076       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8077     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8078       if (MemVT.isPow2VectorType())
8079         return SDValue();
8080       return WidenOrSplitVectorLoad(Op, DAG);
8081     }
8082     // Non-uniform loads will be selected to MUBUF instructions, so they
8083     // have the same legalization requirements as global and private
8084     // loads.
8085     //
8086   }
8087 
8088   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8089       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8090       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8091     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8092         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8093         Alignment >= 4 && NumElements < 32) {
8094       if (MemVT.isPow2VectorType())
8095         return SDValue();
8096       return WidenOrSplitVectorLoad(Op, DAG);
8097     }
8098     // Non-uniform loads will be selected to MUBUF instructions, so they
8099     // have the same legalization requirements as global and private
8100     // loads.
8101     //
8102   }
8103   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8104       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8105       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8106       AS == AMDGPUAS::FLAT_ADDRESS) {
8107     if (NumElements > 4)
8108       return SplitVectorLoad(Op, DAG);
8109     // v3 loads not supported on SI.
8110     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8111       return WidenOrSplitVectorLoad(Op, DAG);
8112 
8113     // v3 and v4 loads are supported for private and global memory.
8114     return SDValue();
8115   }
8116   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8117     // Depending on the setting of the private_element_size field in the
8118     // resource descriptor, we can only make private accesses up to a certain
8119     // size.
8120     switch (Subtarget->getMaxPrivateElementSize()) {
8121     case 4: {
8122       SDValue Ops[2];
8123       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8124       return DAG.getMergeValues(Ops, DL);
8125     }
8126     case 8:
8127       if (NumElements > 2)
8128         return SplitVectorLoad(Op, DAG);
8129       return SDValue();
8130     case 16:
8131       // Same as global/flat
8132       if (NumElements > 4)
8133         return SplitVectorLoad(Op, DAG);
8134       // v3 loads not supported on SI.
8135       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8136         return WidenOrSplitVectorLoad(Op, DAG);
8137 
8138       return SDValue();
8139     default:
8140       llvm_unreachable("unsupported private_element_size");
8141     }
8142   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8143     // Use ds_read_b128 or ds_read_b96 when possible.
8144     if (Subtarget->hasDS96AndDS128() &&
8145         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8146          MemVT.getStoreSize() == 12) &&
8147         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8148                                            Load->getAlign()))
8149       return SDValue();
8150 
8151     if (NumElements > 2)
8152       return SplitVectorLoad(Op, DAG);
8153 
8154     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8155     // address is negative, then the instruction is incorrectly treated as
8156     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8157     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8158     // load later in the SILoadStoreOptimizer.
8159     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8160         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8161         Load->getAlignment() < 8) {
8162       return SplitVectorLoad(Op, DAG);
8163     }
8164   }
8165 
8166   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8167                                       MemVT, *Load->getMemOperand())) {
8168     SDValue Ops[2];
8169     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8170     return DAG.getMergeValues(Ops, DL);
8171   }
8172 
8173   return SDValue();
8174 }
8175 
8176 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8177   EVT VT = Op.getValueType();
8178   assert(VT.getSizeInBits() == 64);
8179 
8180   SDLoc DL(Op);
8181   SDValue Cond = Op.getOperand(0);
8182 
8183   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8184   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8185 
8186   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8187   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8188 
8189   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8190   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8191 
8192   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8193 
8194   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8195   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8196 
8197   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8198 
8199   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8200   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8201 }
8202 
8203 // Catch division cases where we can use shortcuts with rcp and rsq
8204 // instructions.
8205 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8206                                               SelectionDAG &DAG) const {
8207   SDLoc SL(Op);
8208   SDValue LHS = Op.getOperand(0);
8209   SDValue RHS = Op.getOperand(1);
8210   EVT VT = Op.getValueType();
8211   const SDNodeFlags Flags = Op->getFlags();
8212 
8213   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
8214                             Flags.hasApproximateFuncs();
8215 
8216   // Without !fpmath accuracy information, we can't do more because we don't
8217   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8218   if (!AllowInaccurateRcp)
8219     return SDValue();
8220 
8221   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8222     if (CLHS->isExactlyValue(1.0)) {
8223       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8224       // the CI documentation has a worst case error of 1 ulp.
8225       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8226       // use it as long as we aren't trying to use denormals.
8227       //
8228       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8229 
8230       // 1.0 / sqrt(x) -> rsq(x)
8231 
8232       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8233       // error seems really high at 2^29 ULP.
8234       if (RHS.getOpcode() == ISD::FSQRT)
8235         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8236 
8237       // 1.0 / x -> rcp(x)
8238       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8239     }
8240 
8241     // Same as for 1.0, but expand the sign out of the constant.
8242     if (CLHS->isExactlyValue(-1.0)) {
8243       // -1.0 / x -> rcp (fneg x)
8244       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8245       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8246     }
8247   }
8248 
8249   // Turn into multiply by the reciprocal.
8250   // x / y -> x * (1.0 / y)
8251   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8252   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8253 }
8254 
8255 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8256                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8257                           SDNodeFlags Flags) {
8258   if (GlueChain->getNumValues() <= 1) {
8259     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8260   }
8261 
8262   assert(GlueChain->getNumValues() == 3);
8263 
8264   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8265   switch (Opcode) {
8266   default: llvm_unreachable("no chain equivalent for opcode");
8267   case ISD::FMUL:
8268     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8269     break;
8270   }
8271 
8272   return DAG.getNode(Opcode, SL, VTList,
8273                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8274                      Flags);
8275 }
8276 
8277 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8278                            EVT VT, SDValue A, SDValue B, SDValue C,
8279                            SDValue GlueChain, SDNodeFlags Flags) {
8280   if (GlueChain->getNumValues() <= 1) {
8281     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8282   }
8283 
8284   assert(GlueChain->getNumValues() == 3);
8285 
8286   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8287   switch (Opcode) {
8288   default: llvm_unreachable("no chain equivalent for opcode");
8289   case ISD::FMA:
8290     Opcode = AMDGPUISD::FMA_W_CHAIN;
8291     break;
8292   }
8293 
8294   return DAG.getNode(Opcode, SL, VTList,
8295                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8296                      Flags);
8297 }
8298 
8299 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8300   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8301     return FastLowered;
8302 
8303   SDLoc SL(Op);
8304   SDValue Src0 = Op.getOperand(0);
8305   SDValue Src1 = Op.getOperand(1);
8306 
8307   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8308   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8309 
8310   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8311   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8312 
8313   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8314   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8315 
8316   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8317 }
8318 
8319 // Faster 2.5 ULP division that does not support denormals.
8320 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8321   SDLoc SL(Op);
8322   SDValue LHS = Op.getOperand(1);
8323   SDValue RHS = Op.getOperand(2);
8324 
8325   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8326 
8327   const APFloat K0Val(BitsToFloat(0x6f800000));
8328   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8329 
8330   const APFloat K1Val(BitsToFloat(0x2f800000));
8331   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8332 
8333   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8334 
8335   EVT SetCCVT =
8336     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8337 
8338   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8339 
8340   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8341 
8342   // TODO: Should this propagate fast-math-flags?
8343   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8344 
8345   // rcp does not support denormals.
8346   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8347 
8348   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8349 
8350   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8351 }
8352 
8353 // Returns immediate value for setting the F32 denorm mode when using the
8354 // S_DENORM_MODE instruction.
8355 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8356                                           const SDLoc &SL, const GCNSubtarget *ST) {
8357   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8358   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8359                                 ? FP_DENORM_FLUSH_NONE
8360                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8361 
8362   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8363   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8364 }
8365 
8366 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8367   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8368     return FastLowered;
8369 
8370   // The selection matcher assumes anything with a chain selecting to a
8371   // mayRaiseFPException machine instruction. Since we're introducing a chain
8372   // here, we need to explicitly report nofpexcept for the regular fdiv
8373   // lowering.
8374   SDNodeFlags Flags = Op->getFlags();
8375   Flags.setNoFPExcept(true);
8376 
8377   SDLoc SL(Op);
8378   SDValue LHS = Op.getOperand(0);
8379   SDValue RHS = Op.getOperand(1);
8380 
8381   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8382 
8383   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8384 
8385   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8386                                           {RHS, RHS, LHS}, Flags);
8387   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8388                                         {LHS, RHS, LHS}, Flags);
8389 
8390   // Denominator is scaled to not be denormal, so using rcp is ok.
8391   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8392                                   DenominatorScaled, Flags);
8393   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8394                                      DenominatorScaled, Flags);
8395 
8396   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8397                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8398                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8399   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8400 
8401   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8402 
8403   if (!HasFP32Denormals) {
8404     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8405     // lowering. The chain dependence is insufficient, and we need glue. We do
8406     // not need the glue variants in a strictfp function.
8407 
8408     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8409 
8410     SDNode *EnableDenorm;
8411     if (Subtarget->hasDenormModeInst()) {
8412       const SDValue EnableDenormValue =
8413           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8414 
8415       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8416                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8417     } else {
8418       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8419                                                         SL, MVT::i32);
8420       EnableDenorm =
8421           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8422                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8423     }
8424 
8425     SDValue Ops[3] = {
8426       NegDivScale0,
8427       SDValue(EnableDenorm, 0),
8428       SDValue(EnableDenorm, 1)
8429     };
8430 
8431     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8432   }
8433 
8434   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8435                              ApproxRcp, One, NegDivScale0, Flags);
8436 
8437   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8438                              ApproxRcp, Fma0, Flags);
8439 
8440   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8441                            Fma1, Fma1, Flags);
8442 
8443   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8444                              NumeratorScaled, Mul, Flags);
8445 
8446   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8447                              Fma2, Fma1, Mul, Fma2, Flags);
8448 
8449   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8450                              NumeratorScaled, Fma3, Flags);
8451 
8452   if (!HasFP32Denormals) {
8453     SDNode *DisableDenorm;
8454     if (Subtarget->hasDenormModeInst()) {
8455       const SDValue DisableDenormValue =
8456           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8457 
8458       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8459                                   Fma4.getValue(1), DisableDenormValue,
8460                                   Fma4.getValue(2)).getNode();
8461     } else {
8462       const SDValue DisableDenormValue =
8463           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8464 
8465       DisableDenorm = DAG.getMachineNode(
8466           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8467           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8468     }
8469 
8470     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8471                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8472     DAG.setRoot(OutputChain);
8473   }
8474 
8475   SDValue Scale = NumeratorScaled.getValue(1);
8476   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8477                              {Fma4, Fma1, Fma3, Scale}, Flags);
8478 
8479   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8480 }
8481 
8482 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8483   if (DAG.getTarget().Options.UnsafeFPMath)
8484     return lowerFastUnsafeFDIV(Op, DAG);
8485 
8486   SDLoc SL(Op);
8487   SDValue X = Op.getOperand(0);
8488   SDValue Y = Op.getOperand(1);
8489 
8490   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8491 
8492   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8493 
8494   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8495 
8496   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8497 
8498   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8499 
8500   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8501 
8502   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8503 
8504   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8505 
8506   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8507 
8508   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8509   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8510 
8511   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8512                              NegDivScale0, Mul, DivScale1);
8513 
8514   SDValue Scale;
8515 
8516   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8517     // Workaround a hardware bug on SI where the condition output from div_scale
8518     // is not usable.
8519 
8520     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8521 
8522     // Figure out if the scale to use for div_fmas.
8523     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8524     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8525     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8526     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8527 
8528     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8529     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8530 
8531     SDValue Scale0Hi
8532       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8533     SDValue Scale1Hi
8534       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8535 
8536     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8537     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8538     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8539   } else {
8540     Scale = DivScale1.getValue(1);
8541   }
8542 
8543   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8544                              Fma4, Fma3, Mul, Scale);
8545 
8546   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8547 }
8548 
8549 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8550   EVT VT = Op.getValueType();
8551 
8552   if (VT == MVT::f32)
8553     return LowerFDIV32(Op, DAG);
8554 
8555   if (VT == MVT::f64)
8556     return LowerFDIV64(Op, DAG);
8557 
8558   if (VT == MVT::f16)
8559     return LowerFDIV16(Op, DAG);
8560 
8561   llvm_unreachable("Unexpected type for fdiv");
8562 }
8563 
8564 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8565   SDLoc DL(Op);
8566   StoreSDNode *Store = cast<StoreSDNode>(Op);
8567   EVT VT = Store->getMemoryVT();
8568 
8569   if (VT == MVT::i1) {
8570     return DAG.getTruncStore(Store->getChain(), DL,
8571        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8572        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8573   }
8574 
8575   assert(VT.isVector() &&
8576          Store->getValue().getValueType().getScalarType() == MVT::i32);
8577 
8578   unsigned AS = Store->getAddressSpace();
8579   if (Subtarget->hasLDSMisalignedBug() &&
8580       AS == AMDGPUAS::FLAT_ADDRESS &&
8581       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8582     return SplitVectorStore(Op, DAG);
8583   }
8584 
8585   MachineFunction &MF = DAG.getMachineFunction();
8586   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8587   // If there is a possibilty that flat instruction access scratch memory
8588   // then we need to use the same legalization rules we use for private.
8589   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8590       !Subtarget->hasMultiDwordFlatScratchAddressing())
8591     AS = MFI->hasFlatScratchInit() ?
8592          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8593 
8594   unsigned NumElements = VT.getVectorNumElements();
8595   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8596       AS == AMDGPUAS::FLAT_ADDRESS) {
8597     if (NumElements > 4)
8598       return SplitVectorStore(Op, DAG);
8599     // v3 stores not supported on SI.
8600     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8601       return SplitVectorStore(Op, DAG);
8602 
8603     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8604                                         VT, *Store->getMemOperand()))
8605       return expandUnalignedStore(Store, DAG);
8606 
8607     return SDValue();
8608   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8609     switch (Subtarget->getMaxPrivateElementSize()) {
8610     case 4:
8611       return scalarizeVectorStore(Store, DAG);
8612     case 8:
8613       if (NumElements > 2)
8614         return SplitVectorStore(Op, DAG);
8615       return SDValue();
8616     case 16:
8617       if (NumElements > 4 ||
8618           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8619         return SplitVectorStore(Op, DAG);
8620       return SDValue();
8621     default:
8622       llvm_unreachable("unsupported private_element_size");
8623     }
8624   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8625     // Use ds_write_b128 or ds_write_b96 when possible.
8626     if (Subtarget->hasDS96AndDS128() &&
8627         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8628          (VT.getStoreSize() == 12)) &&
8629         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8630                                            Store->getAlign()))
8631       return SDValue();
8632 
8633     if (NumElements > 2)
8634       return SplitVectorStore(Op, DAG);
8635 
8636     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8637     // address is negative, then the instruction is incorrectly treated as
8638     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8639     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8640     // store later in the SILoadStoreOptimizer.
8641     if (!Subtarget->hasUsableDSOffset() &&
8642         NumElements == 2 && VT.getStoreSize() == 8 &&
8643         Store->getAlignment() < 8) {
8644       return SplitVectorStore(Op, DAG);
8645     }
8646 
8647     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8648                                         VT, *Store->getMemOperand())) {
8649       if (VT.isVector())
8650         return SplitVectorStore(Op, DAG);
8651       return expandUnalignedStore(Store, DAG);
8652     }
8653 
8654     return SDValue();
8655   } else {
8656     llvm_unreachable("unhandled address space");
8657   }
8658 }
8659 
8660 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8661   SDLoc DL(Op);
8662   EVT VT = Op.getValueType();
8663   SDValue Arg = Op.getOperand(0);
8664   SDValue TrigVal;
8665 
8666   // Propagate fast-math flags so that the multiply we introduce can be folded
8667   // if Arg is already the result of a multiply by constant.
8668   auto Flags = Op->getFlags();
8669 
8670   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8671 
8672   if (Subtarget->hasTrigReducedRange()) {
8673     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8674     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8675   } else {
8676     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8677   }
8678 
8679   switch (Op.getOpcode()) {
8680   case ISD::FCOS:
8681     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8682   case ISD::FSIN:
8683     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8684   default:
8685     llvm_unreachable("Wrong trig opcode");
8686   }
8687 }
8688 
8689 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8690   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8691   assert(AtomicNode->isCompareAndSwap());
8692   unsigned AS = AtomicNode->getAddressSpace();
8693 
8694   // No custom lowering required for local address space
8695   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8696     return Op;
8697 
8698   // Non-local address space requires custom lowering for atomic compare
8699   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8700   SDLoc DL(Op);
8701   SDValue ChainIn = Op.getOperand(0);
8702   SDValue Addr = Op.getOperand(1);
8703   SDValue Old = Op.getOperand(2);
8704   SDValue New = Op.getOperand(3);
8705   EVT VT = Op.getValueType();
8706   MVT SimpleVT = VT.getSimpleVT();
8707   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8708 
8709   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8710   SDValue Ops[] = { ChainIn, Addr, NewOld };
8711 
8712   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8713                                  Ops, VT, AtomicNode->getMemOperand());
8714 }
8715 
8716 //===----------------------------------------------------------------------===//
8717 // Custom DAG optimizations
8718 //===----------------------------------------------------------------------===//
8719 
8720 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8721                                                      DAGCombinerInfo &DCI) const {
8722   EVT VT = N->getValueType(0);
8723   EVT ScalarVT = VT.getScalarType();
8724   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8725     return SDValue();
8726 
8727   SelectionDAG &DAG = DCI.DAG;
8728   SDLoc DL(N);
8729 
8730   SDValue Src = N->getOperand(0);
8731   EVT SrcVT = Src.getValueType();
8732 
8733   // TODO: We could try to match extracting the higher bytes, which would be
8734   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8735   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8736   // about in practice.
8737   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8738     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8739       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8740       DCI.AddToWorklist(Cvt.getNode());
8741 
8742       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8743       if (ScalarVT != MVT::f32) {
8744         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8745                           DAG.getTargetConstant(0, DL, MVT::i32));
8746       }
8747       return Cvt;
8748     }
8749   }
8750 
8751   return SDValue();
8752 }
8753 
8754 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8755 
8756 // This is a variant of
8757 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8758 //
8759 // The normal DAG combiner will do this, but only if the add has one use since
8760 // that would increase the number of instructions.
8761 //
8762 // This prevents us from seeing a constant offset that can be folded into a
8763 // memory instruction's addressing mode. If we know the resulting add offset of
8764 // a pointer can be folded into an addressing offset, we can replace the pointer
8765 // operand with the add of new constant offset. This eliminates one of the uses,
8766 // and may allow the remaining use to also be simplified.
8767 //
8768 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8769                                                unsigned AddrSpace,
8770                                                EVT MemVT,
8771                                                DAGCombinerInfo &DCI) const {
8772   SDValue N0 = N->getOperand(0);
8773   SDValue N1 = N->getOperand(1);
8774 
8775   // We only do this to handle cases where it's profitable when there are
8776   // multiple uses of the add, so defer to the standard combine.
8777   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8778       N0->hasOneUse())
8779     return SDValue();
8780 
8781   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8782   if (!CN1)
8783     return SDValue();
8784 
8785   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8786   if (!CAdd)
8787     return SDValue();
8788 
8789   // If the resulting offset is too large, we can't fold it into the addressing
8790   // mode offset.
8791   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8792   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8793 
8794   AddrMode AM;
8795   AM.HasBaseReg = true;
8796   AM.BaseOffs = Offset.getSExtValue();
8797   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8798     return SDValue();
8799 
8800   SelectionDAG &DAG = DCI.DAG;
8801   SDLoc SL(N);
8802   EVT VT = N->getValueType(0);
8803 
8804   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8805   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8806 
8807   SDNodeFlags Flags;
8808   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8809                           (N0.getOpcode() == ISD::OR ||
8810                            N0->getFlags().hasNoUnsignedWrap()));
8811 
8812   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8813 }
8814 
8815 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8816 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8817 /// specific intrinsic, but they all place the pointer operand first.
8818 static unsigned getBasePtrIndex(const MemSDNode *N) {
8819   switch (N->getOpcode()) {
8820   case ISD::STORE:
8821   case ISD::INTRINSIC_W_CHAIN:
8822   case ISD::INTRINSIC_VOID:
8823     return 2;
8824   default:
8825     return 1;
8826   }
8827 }
8828 
8829 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8830                                                   DAGCombinerInfo &DCI) const {
8831   SelectionDAG &DAG = DCI.DAG;
8832   SDLoc SL(N);
8833 
8834   unsigned PtrIdx = getBasePtrIndex(N);
8835   SDValue Ptr = N->getOperand(PtrIdx);
8836 
8837   // TODO: We could also do this for multiplies.
8838   if (Ptr.getOpcode() == ISD::SHL) {
8839     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8840                                           N->getMemoryVT(), DCI);
8841     if (NewPtr) {
8842       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8843 
8844       NewOps[PtrIdx] = NewPtr;
8845       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8846     }
8847   }
8848 
8849   return SDValue();
8850 }
8851 
8852 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8853   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8854          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8855          (Opc == ISD::XOR && Val == 0);
8856 }
8857 
8858 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8859 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8860 // integer combine opportunities since most 64-bit operations are decomposed
8861 // this way.  TODO: We won't want this for SALU especially if it is an inline
8862 // immediate.
8863 SDValue SITargetLowering::splitBinaryBitConstantOp(
8864   DAGCombinerInfo &DCI,
8865   const SDLoc &SL,
8866   unsigned Opc, SDValue LHS,
8867   const ConstantSDNode *CRHS) const {
8868   uint64_t Val = CRHS->getZExtValue();
8869   uint32_t ValLo = Lo_32(Val);
8870   uint32_t ValHi = Hi_32(Val);
8871   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8872 
8873     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8874          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8875         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8876     // If we need to materialize a 64-bit immediate, it will be split up later
8877     // anyway. Avoid creating the harder to understand 64-bit immediate
8878     // materialization.
8879     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8880   }
8881 
8882   return SDValue();
8883 }
8884 
8885 // Returns true if argument is a boolean value which is not serialized into
8886 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8887 static bool isBoolSGPR(SDValue V) {
8888   if (V.getValueType() != MVT::i1)
8889     return false;
8890   switch (V.getOpcode()) {
8891   default: break;
8892   case ISD::SETCC:
8893   case ISD::AND:
8894   case ISD::OR:
8895   case ISD::XOR:
8896   case AMDGPUISD::FP_CLASS:
8897     return true;
8898   }
8899   return false;
8900 }
8901 
8902 // If a constant has all zeroes or all ones within each byte return it.
8903 // Otherwise return 0.
8904 static uint32_t getConstantPermuteMask(uint32_t C) {
8905   // 0xff for any zero byte in the mask
8906   uint32_t ZeroByteMask = 0;
8907   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8908   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8909   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8910   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8911   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8912   if ((NonZeroByteMask & C) != NonZeroByteMask)
8913     return 0; // Partial bytes selected.
8914   return C;
8915 }
8916 
8917 // Check if a node selects whole bytes from its operand 0 starting at a byte
8918 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8919 // or -1 if not succeeded.
8920 // Note byte select encoding:
8921 // value 0-3 selects corresponding source byte;
8922 // value 0xc selects zero;
8923 // value 0xff selects 0xff.
8924 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8925   assert(V.getValueSizeInBits() == 32);
8926 
8927   if (V.getNumOperands() != 2)
8928     return ~0;
8929 
8930   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8931   if (!N1)
8932     return ~0;
8933 
8934   uint32_t C = N1->getZExtValue();
8935 
8936   switch (V.getOpcode()) {
8937   default:
8938     break;
8939   case ISD::AND:
8940     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8941       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8942     }
8943     break;
8944 
8945   case ISD::OR:
8946     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8947       return (0x03020100 & ~ConstMask) | ConstMask;
8948     }
8949     break;
8950 
8951   case ISD::SHL:
8952     if (C % 8)
8953       return ~0;
8954 
8955     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8956 
8957   case ISD::SRL:
8958     if (C % 8)
8959       return ~0;
8960 
8961     return uint32_t(0x0c0c0c0c03020100ull >> C);
8962   }
8963 
8964   return ~0;
8965 }
8966 
8967 SDValue SITargetLowering::performAndCombine(SDNode *N,
8968                                             DAGCombinerInfo &DCI) const {
8969   if (DCI.isBeforeLegalize())
8970     return SDValue();
8971 
8972   SelectionDAG &DAG = DCI.DAG;
8973   EVT VT = N->getValueType(0);
8974   SDValue LHS = N->getOperand(0);
8975   SDValue RHS = N->getOperand(1);
8976 
8977 
8978   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8979   if (VT == MVT::i64 && CRHS) {
8980     if (SDValue Split
8981         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8982       return Split;
8983   }
8984 
8985   if (CRHS && VT == MVT::i32) {
8986     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8987     // nb = number of trailing zeroes in mask
8988     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8989     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8990     uint64_t Mask = CRHS->getZExtValue();
8991     unsigned Bits = countPopulation(Mask);
8992     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8993         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8994       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8995         unsigned Shift = CShift->getZExtValue();
8996         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8997         unsigned Offset = NB + Shift;
8998         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8999           SDLoc SL(N);
9000           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9001                                     LHS->getOperand(0),
9002                                     DAG.getConstant(Offset, SL, MVT::i32),
9003                                     DAG.getConstant(Bits, SL, MVT::i32));
9004           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9005           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9006                                     DAG.getValueType(NarrowVT));
9007           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9008                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9009           return Shl;
9010         }
9011       }
9012     }
9013 
9014     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9015     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9016         isa<ConstantSDNode>(LHS.getOperand(2))) {
9017       uint32_t Sel = getConstantPermuteMask(Mask);
9018       if (!Sel)
9019         return SDValue();
9020 
9021       // Select 0xc for all zero bytes
9022       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9023       SDLoc DL(N);
9024       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9025                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9026     }
9027   }
9028 
9029   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9030   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9031   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9032     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9033     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9034 
9035     SDValue X = LHS.getOperand(0);
9036     SDValue Y = RHS.getOperand(0);
9037     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9038       return SDValue();
9039 
9040     if (LCC == ISD::SETO) {
9041       if (X != LHS.getOperand(1))
9042         return SDValue();
9043 
9044       if (RCC == ISD::SETUNE) {
9045         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9046         if (!C1 || !C1->isInfinity() || C1->isNegative())
9047           return SDValue();
9048 
9049         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9050                               SIInstrFlags::N_SUBNORMAL |
9051                               SIInstrFlags::N_ZERO |
9052                               SIInstrFlags::P_ZERO |
9053                               SIInstrFlags::P_SUBNORMAL |
9054                               SIInstrFlags::P_NORMAL;
9055 
9056         static_assert(((~(SIInstrFlags::S_NAN |
9057                           SIInstrFlags::Q_NAN |
9058                           SIInstrFlags::N_INFINITY |
9059                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9060                       "mask not equal");
9061 
9062         SDLoc DL(N);
9063         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9064                            X, DAG.getConstant(Mask, DL, MVT::i32));
9065       }
9066     }
9067   }
9068 
9069   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9070     std::swap(LHS, RHS);
9071 
9072   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9073       RHS.hasOneUse()) {
9074     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9075     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9076     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9077     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9078     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9079         (RHS.getOperand(0) == LHS.getOperand(0) &&
9080          LHS.getOperand(0) == LHS.getOperand(1))) {
9081       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9082       unsigned NewMask = LCC == ISD::SETO ?
9083         Mask->getZExtValue() & ~OrdMask :
9084         Mask->getZExtValue() & OrdMask;
9085 
9086       SDLoc DL(N);
9087       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9088                          DAG.getConstant(NewMask, DL, MVT::i32));
9089     }
9090   }
9091 
9092   if (VT == MVT::i32 &&
9093       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9094     // and x, (sext cc from i1) => select cc, x, 0
9095     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9096       std::swap(LHS, RHS);
9097     if (isBoolSGPR(RHS.getOperand(0)))
9098       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9099                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9100   }
9101 
9102   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9103   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9104   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9105       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9106     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9107     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9108     if (LHSMask != ~0u && RHSMask != ~0u) {
9109       // Canonicalize the expression in an attempt to have fewer unique masks
9110       // and therefore fewer registers used to hold the masks.
9111       if (LHSMask > RHSMask) {
9112         std::swap(LHSMask, RHSMask);
9113         std::swap(LHS, RHS);
9114       }
9115 
9116       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9117       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9118       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9119       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9120 
9121       // Check of we need to combine values from two sources within a byte.
9122       if (!(LHSUsedLanes & RHSUsedLanes) &&
9123           // If we select high and lower word keep it for SDWA.
9124           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9125           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9126         // Each byte in each mask is either selector mask 0-3, or has higher
9127         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9128         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9129         // mask which is not 0xff wins. By anding both masks we have a correct
9130         // result except that 0x0c shall be corrected to give 0x0c only.
9131         uint32_t Mask = LHSMask & RHSMask;
9132         for (unsigned I = 0; I < 32; I += 8) {
9133           uint32_t ByteSel = 0xff << I;
9134           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9135             Mask &= (0x0c << I) & 0xffffffff;
9136         }
9137 
9138         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9139         // or 0x0c.
9140         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9141         SDLoc DL(N);
9142 
9143         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9144                            LHS.getOperand(0), RHS.getOperand(0),
9145                            DAG.getConstant(Sel, DL, MVT::i32));
9146       }
9147     }
9148   }
9149 
9150   return SDValue();
9151 }
9152 
9153 SDValue SITargetLowering::performOrCombine(SDNode *N,
9154                                            DAGCombinerInfo &DCI) const {
9155   SelectionDAG &DAG = DCI.DAG;
9156   SDValue LHS = N->getOperand(0);
9157   SDValue RHS = N->getOperand(1);
9158 
9159   EVT VT = N->getValueType(0);
9160   if (VT == MVT::i1) {
9161     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9162     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9163         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9164       SDValue Src = LHS.getOperand(0);
9165       if (Src != RHS.getOperand(0))
9166         return SDValue();
9167 
9168       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9169       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9170       if (!CLHS || !CRHS)
9171         return SDValue();
9172 
9173       // Only 10 bits are used.
9174       static const uint32_t MaxMask = 0x3ff;
9175 
9176       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9177       SDLoc DL(N);
9178       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9179                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9180     }
9181 
9182     return SDValue();
9183   }
9184 
9185   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9186   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9187       LHS.getOpcode() == AMDGPUISD::PERM &&
9188       isa<ConstantSDNode>(LHS.getOperand(2))) {
9189     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9190     if (!Sel)
9191       return SDValue();
9192 
9193     Sel |= LHS.getConstantOperandVal(2);
9194     SDLoc DL(N);
9195     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9196                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9197   }
9198 
9199   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9200   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9201   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9202       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9203     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9204     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9205     if (LHSMask != ~0u && RHSMask != ~0u) {
9206       // Canonicalize the expression in an attempt to have fewer unique masks
9207       // and therefore fewer registers used to hold the masks.
9208       if (LHSMask > RHSMask) {
9209         std::swap(LHSMask, RHSMask);
9210         std::swap(LHS, RHS);
9211       }
9212 
9213       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9214       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9215       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9216       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9217 
9218       // Check of we need to combine values from two sources within a byte.
9219       if (!(LHSUsedLanes & RHSUsedLanes) &&
9220           // If we select high and lower word keep it for SDWA.
9221           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9222           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9223         // Kill zero bytes selected by other mask. Zero value is 0xc.
9224         LHSMask &= ~RHSUsedLanes;
9225         RHSMask &= ~LHSUsedLanes;
9226         // Add 4 to each active LHS lane
9227         LHSMask |= LHSUsedLanes & 0x04040404;
9228         // Combine masks
9229         uint32_t Sel = LHSMask | RHSMask;
9230         SDLoc DL(N);
9231 
9232         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9233                            LHS.getOperand(0), RHS.getOperand(0),
9234                            DAG.getConstant(Sel, DL, MVT::i32));
9235       }
9236     }
9237   }
9238 
9239   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9240     return SDValue();
9241 
9242   // TODO: This could be a generic combine with a predicate for extracting the
9243   // high half of an integer being free.
9244 
9245   // (or i64:x, (zero_extend i32:y)) ->
9246   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9247   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9248       RHS.getOpcode() != ISD::ZERO_EXTEND)
9249     std::swap(LHS, RHS);
9250 
9251   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9252     SDValue ExtSrc = RHS.getOperand(0);
9253     EVT SrcVT = ExtSrc.getValueType();
9254     if (SrcVT == MVT::i32) {
9255       SDLoc SL(N);
9256       SDValue LowLHS, HiBits;
9257       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9258       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9259 
9260       DCI.AddToWorklist(LowOr.getNode());
9261       DCI.AddToWorklist(HiBits.getNode());
9262 
9263       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9264                                 LowOr, HiBits);
9265       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9266     }
9267   }
9268 
9269   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9270   if (CRHS) {
9271     if (SDValue Split
9272           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9273       return Split;
9274   }
9275 
9276   return SDValue();
9277 }
9278 
9279 SDValue SITargetLowering::performXorCombine(SDNode *N,
9280                                             DAGCombinerInfo &DCI) const {
9281   EVT VT = N->getValueType(0);
9282   if (VT != MVT::i64)
9283     return SDValue();
9284 
9285   SDValue LHS = N->getOperand(0);
9286   SDValue RHS = N->getOperand(1);
9287 
9288   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9289   if (CRHS) {
9290     if (SDValue Split
9291           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9292       return Split;
9293   }
9294 
9295   return SDValue();
9296 }
9297 
9298 // Instructions that will be lowered with a final instruction that zeros the
9299 // high result bits.
9300 // XXX - probably only need to list legal operations.
9301 static bool fp16SrcZerosHighBits(unsigned Opc) {
9302   switch (Opc) {
9303   case ISD::FADD:
9304   case ISD::FSUB:
9305   case ISD::FMUL:
9306   case ISD::FDIV:
9307   case ISD::FREM:
9308   case ISD::FMA:
9309   case ISD::FMAD:
9310   case ISD::FCANONICALIZE:
9311   case ISD::FP_ROUND:
9312   case ISD::UINT_TO_FP:
9313   case ISD::SINT_TO_FP:
9314   case ISD::FABS:
9315     // Fabs is lowered to a bit operation, but it's an and which will clear the
9316     // high bits anyway.
9317   case ISD::FSQRT:
9318   case ISD::FSIN:
9319   case ISD::FCOS:
9320   case ISD::FPOWI:
9321   case ISD::FPOW:
9322   case ISD::FLOG:
9323   case ISD::FLOG2:
9324   case ISD::FLOG10:
9325   case ISD::FEXP:
9326   case ISD::FEXP2:
9327   case ISD::FCEIL:
9328   case ISD::FTRUNC:
9329   case ISD::FRINT:
9330   case ISD::FNEARBYINT:
9331   case ISD::FROUND:
9332   case ISD::FFLOOR:
9333   case ISD::FMINNUM:
9334   case ISD::FMAXNUM:
9335   case AMDGPUISD::FRACT:
9336   case AMDGPUISD::CLAMP:
9337   case AMDGPUISD::COS_HW:
9338   case AMDGPUISD::SIN_HW:
9339   case AMDGPUISD::FMIN3:
9340   case AMDGPUISD::FMAX3:
9341   case AMDGPUISD::FMED3:
9342   case AMDGPUISD::FMAD_FTZ:
9343   case AMDGPUISD::RCP:
9344   case AMDGPUISD::RSQ:
9345   case AMDGPUISD::RCP_IFLAG:
9346   case AMDGPUISD::LDEXP:
9347     return true;
9348   default:
9349     // fcopysign, select and others may be lowered to 32-bit bit operations
9350     // which don't zero the high bits.
9351     return false;
9352   }
9353 }
9354 
9355 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9356                                                    DAGCombinerInfo &DCI) const {
9357   if (!Subtarget->has16BitInsts() ||
9358       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9359     return SDValue();
9360 
9361   EVT VT = N->getValueType(0);
9362   if (VT != MVT::i32)
9363     return SDValue();
9364 
9365   SDValue Src = N->getOperand(0);
9366   if (Src.getValueType() != MVT::i16)
9367     return SDValue();
9368 
9369   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9370   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9371   if (Src.getOpcode() == ISD::BITCAST) {
9372     SDValue BCSrc = Src.getOperand(0);
9373     if (BCSrc.getValueType() == MVT::f16 &&
9374         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9375       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9376   }
9377 
9378   return SDValue();
9379 }
9380 
9381 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9382                                                         DAGCombinerInfo &DCI)
9383                                                         const {
9384   SDValue Src = N->getOperand(0);
9385   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9386 
9387   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9388       VTSign->getVT() == MVT::i8) ||
9389       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9390       VTSign->getVT() == MVT::i16)) &&
9391       Src.hasOneUse()) {
9392     auto *M = cast<MemSDNode>(Src);
9393     SDValue Ops[] = {
9394       Src.getOperand(0), // Chain
9395       Src.getOperand(1), // rsrc
9396       Src.getOperand(2), // vindex
9397       Src.getOperand(3), // voffset
9398       Src.getOperand(4), // soffset
9399       Src.getOperand(5), // offset
9400       Src.getOperand(6),
9401       Src.getOperand(7)
9402     };
9403     // replace with BUFFER_LOAD_BYTE/SHORT
9404     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9405                                          Src.getOperand(0).getValueType());
9406     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9407                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9408     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9409                                                           ResList,
9410                                                           Ops, M->getMemoryVT(),
9411                                                           M->getMemOperand());
9412     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9413                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9414   }
9415   return SDValue();
9416 }
9417 
9418 SDValue SITargetLowering::performClassCombine(SDNode *N,
9419                                               DAGCombinerInfo &DCI) const {
9420   SelectionDAG &DAG = DCI.DAG;
9421   SDValue Mask = N->getOperand(1);
9422 
9423   // fp_class x, 0 -> false
9424   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9425     if (CMask->isNullValue())
9426       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9427   }
9428 
9429   if (N->getOperand(0).isUndef())
9430     return DAG.getUNDEF(MVT::i1);
9431 
9432   return SDValue();
9433 }
9434 
9435 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9436                                             DAGCombinerInfo &DCI) const {
9437   EVT VT = N->getValueType(0);
9438   SDValue N0 = N->getOperand(0);
9439 
9440   if (N0.isUndef())
9441     return N0;
9442 
9443   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9444                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9445     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9446                            N->getFlags());
9447   }
9448 
9449   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9450     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9451                            N0.getOperand(0), N->getFlags());
9452   }
9453 
9454   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9455 }
9456 
9457 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9458                                        unsigned MaxDepth) const {
9459   unsigned Opcode = Op.getOpcode();
9460   if (Opcode == ISD::FCANONICALIZE)
9461     return true;
9462 
9463   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9464     auto F = CFP->getValueAPF();
9465     if (F.isNaN() && F.isSignaling())
9466       return false;
9467     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9468   }
9469 
9470   // If source is a result of another standard FP operation it is already in
9471   // canonical form.
9472   if (MaxDepth == 0)
9473     return false;
9474 
9475   switch (Opcode) {
9476   // These will flush denorms if required.
9477   case ISD::FADD:
9478   case ISD::FSUB:
9479   case ISD::FMUL:
9480   case ISD::FCEIL:
9481   case ISD::FFLOOR:
9482   case ISD::FMA:
9483   case ISD::FMAD:
9484   case ISD::FSQRT:
9485   case ISD::FDIV:
9486   case ISD::FREM:
9487   case ISD::FP_ROUND:
9488   case ISD::FP_EXTEND:
9489   case AMDGPUISD::FMUL_LEGACY:
9490   case AMDGPUISD::FMAD_FTZ:
9491   case AMDGPUISD::RCP:
9492   case AMDGPUISD::RSQ:
9493   case AMDGPUISD::RSQ_CLAMP:
9494   case AMDGPUISD::RCP_LEGACY:
9495   case AMDGPUISD::RCP_IFLAG:
9496   case AMDGPUISD::DIV_SCALE:
9497   case AMDGPUISD::DIV_FMAS:
9498   case AMDGPUISD::DIV_FIXUP:
9499   case AMDGPUISD::FRACT:
9500   case AMDGPUISD::LDEXP:
9501   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9502   case AMDGPUISD::CVT_F32_UBYTE0:
9503   case AMDGPUISD::CVT_F32_UBYTE1:
9504   case AMDGPUISD::CVT_F32_UBYTE2:
9505   case AMDGPUISD::CVT_F32_UBYTE3:
9506     return true;
9507 
9508   // It can/will be lowered or combined as a bit operation.
9509   // Need to check their input recursively to handle.
9510   case ISD::FNEG:
9511   case ISD::FABS:
9512   case ISD::FCOPYSIGN:
9513     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9514 
9515   case ISD::FSIN:
9516   case ISD::FCOS:
9517   case ISD::FSINCOS:
9518     return Op.getValueType().getScalarType() != MVT::f16;
9519 
9520   case ISD::FMINNUM:
9521   case ISD::FMAXNUM:
9522   case ISD::FMINNUM_IEEE:
9523   case ISD::FMAXNUM_IEEE:
9524   case AMDGPUISD::CLAMP:
9525   case AMDGPUISD::FMED3:
9526   case AMDGPUISD::FMAX3:
9527   case AMDGPUISD::FMIN3: {
9528     // FIXME: Shouldn't treat the generic operations different based these.
9529     // However, we aren't really required to flush the result from
9530     // minnum/maxnum..
9531 
9532     // snans will be quieted, so we only need to worry about denormals.
9533     if (Subtarget->supportsMinMaxDenormModes() ||
9534         denormalsEnabledForType(DAG, Op.getValueType()))
9535       return true;
9536 
9537     // Flushing may be required.
9538     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9539     // targets need to check their input recursively.
9540 
9541     // FIXME: Does this apply with clamp? It's implemented with max.
9542     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9543       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9544         return false;
9545     }
9546 
9547     return true;
9548   }
9549   case ISD::SELECT: {
9550     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9551            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9552   }
9553   case ISD::BUILD_VECTOR: {
9554     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9555       SDValue SrcOp = Op.getOperand(i);
9556       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9557         return false;
9558     }
9559 
9560     return true;
9561   }
9562   case ISD::EXTRACT_VECTOR_ELT:
9563   case ISD::EXTRACT_SUBVECTOR: {
9564     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9565   }
9566   case ISD::INSERT_VECTOR_ELT: {
9567     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9568            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9569   }
9570   case ISD::UNDEF:
9571     // Could be anything.
9572     return false;
9573 
9574   case ISD::BITCAST: {
9575     // Hack round the mess we make when legalizing extract_vector_elt
9576     SDValue Src = Op.getOperand(0);
9577     if (Src.getValueType() == MVT::i16 &&
9578         Src.getOpcode() == ISD::TRUNCATE) {
9579       SDValue TruncSrc = Src.getOperand(0);
9580       if (TruncSrc.getValueType() == MVT::i32 &&
9581           TruncSrc.getOpcode() == ISD::BITCAST &&
9582           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9583         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9584       }
9585     }
9586 
9587     return false;
9588   }
9589   case ISD::INTRINSIC_WO_CHAIN: {
9590     unsigned IntrinsicID
9591       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9592     // TODO: Handle more intrinsics
9593     switch (IntrinsicID) {
9594     case Intrinsic::amdgcn_cvt_pkrtz:
9595     case Intrinsic::amdgcn_cubeid:
9596     case Intrinsic::amdgcn_frexp_mant:
9597     case Intrinsic::amdgcn_fdot2:
9598     case Intrinsic::amdgcn_rcp:
9599     case Intrinsic::amdgcn_rsq:
9600     case Intrinsic::amdgcn_rsq_clamp:
9601     case Intrinsic::amdgcn_rcp_legacy:
9602     case Intrinsic::amdgcn_rsq_legacy:
9603     case Intrinsic::amdgcn_trig_preop:
9604       return true;
9605     default:
9606       break;
9607     }
9608 
9609     LLVM_FALLTHROUGH;
9610   }
9611   default:
9612     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9613            DAG.isKnownNeverSNaN(Op);
9614   }
9615 
9616   llvm_unreachable("invalid operation");
9617 }
9618 
9619 // Constant fold canonicalize.
9620 SDValue SITargetLowering::getCanonicalConstantFP(
9621   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9622   // Flush denormals to 0 if not enabled.
9623   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9624     return DAG.getConstantFP(0.0, SL, VT);
9625 
9626   if (C.isNaN()) {
9627     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9628     if (C.isSignaling()) {
9629       // Quiet a signaling NaN.
9630       // FIXME: Is this supposed to preserve payload bits?
9631       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9632     }
9633 
9634     // Make sure it is the canonical NaN bitpattern.
9635     //
9636     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9637     // immediate?
9638     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9639       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9640   }
9641 
9642   // Already canonical.
9643   return DAG.getConstantFP(C, SL, VT);
9644 }
9645 
9646 static bool vectorEltWillFoldAway(SDValue Op) {
9647   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9648 }
9649 
9650 SDValue SITargetLowering::performFCanonicalizeCombine(
9651   SDNode *N,
9652   DAGCombinerInfo &DCI) const {
9653   SelectionDAG &DAG = DCI.DAG;
9654   SDValue N0 = N->getOperand(0);
9655   EVT VT = N->getValueType(0);
9656 
9657   // fcanonicalize undef -> qnan
9658   if (N0.isUndef()) {
9659     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9660     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9661   }
9662 
9663   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9664     EVT VT = N->getValueType(0);
9665     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9666   }
9667 
9668   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9669   //                                                   (fcanonicalize k)
9670   //
9671   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9672 
9673   // TODO: This could be better with wider vectors that will be split to v2f16,
9674   // and to consider uses since there aren't that many packed operations.
9675   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9676       isTypeLegal(MVT::v2f16)) {
9677     SDLoc SL(N);
9678     SDValue NewElts[2];
9679     SDValue Lo = N0.getOperand(0);
9680     SDValue Hi = N0.getOperand(1);
9681     EVT EltVT = Lo.getValueType();
9682 
9683     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9684       for (unsigned I = 0; I != 2; ++I) {
9685         SDValue Op = N0.getOperand(I);
9686         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9687           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9688                                               CFP->getValueAPF());
9689         } else if (Op.isUndef()) {
9690           // Handled below based on what the other operand is.
9691           NewElts[I] = Op;
9692         } else {
9693           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9694         }
9695       }
9696 
9697       // If one half is undef, and one is constant, perfer a splat vector rather
9698       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9699       // cheaper to use and may be free with a packed operation.
9700       if (NewElts[0].isUndef()) {
9701         if (isa<ConstantFPSDNode>(NewElts[1]))
9702           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9703             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9704       }
9705 
9706       if (NewElts[1].isUndef()) {
9707         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9708           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9709       }
9710 
9711       return DAG.getBuildVector(VT, SL, NewElts);
9712     }
9713   }
9714 
9715   unsigned SrcOpc = N0.getOpcode();
9716 
9717   // If it's free to do so, push canonicalizes further up the source, which may
9718   // find a canonical source.
9719   //
9720   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9721   // sNaNs.
9722   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9723     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9724     if (CRHS && N0.hasOneUse()) {
9725       SDLoc SL(N);
9726       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9727                                    N0.getOperand(0));
9728       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9729       DCI.AddToWorklist(Canon0.getNode());
9730 
9731       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9732     }
9733   }
9734 
9735   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9736 }
9737 
9738 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9739   switch (Opc) {
9740   case ISD::FMAXNUM:
9741   case ISD::FMAXNUM_IEEE:
9742     return AMDGPUISD::FMAX3;
9743   case ISD::SMAX:
9744     return AMDGPUISD::SMAX3;
9745   case ISD::UMAX:
9746     return AMDGPUISD::UMAX3;
9747   case ISD::FMINNUM:
9748   case ISD::FMINNUM_IEEE:
9749     return AMDGPUISD::FMIN3;
9750   case ISD::SMIN:
9751     return AMDGPUISD::SMIN3;
9752   case ISD::UMIN:
9753     return AMDGPUISD::UMIN3;
9754   default:
9755     llvm_unreachable("Not a min/max opcode");
9756   }
9757 }
9758 
9759 SDValue SITargetLowering::performIntMed3ImmCombine(
9760   SelectionDAG &DAG, const SDLoc &SL,
9761   SDValue Op0, SDValue Op1, bool Signed) const {
9762   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9763   if (!K1)
9764     return SDValue();
9765 
9766   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9767   if (!K0)
9768     return SDValue();
9769 
9770   if (Signed) {
9771     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9772       return SDValue();
9773   } else {
9774     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9775       return SDValue();
9776   }
9777 
9778   EVT VT = K0->getValueType(0);
9779   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9780   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9781     return DAG.getNode(Med3Opc, SL, VT,
9782                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9783   }
9784 
9785   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9786   MVT NVT = MVT::i32;
9787   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9788 
9789   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9790   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9791   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9792 
9793   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9794   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9795 }
9796 
9797 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9798   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9799     return C;
9800 
9801   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9802     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9803       return C;
9804   }
9805 
9806   return nullptr;
9807 }
9808 
9809 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9810                                                   const SDLoc &SL,
9811                                                   SDValue Op0,
9812                                                   SDValue Op1) const {
9813   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9814   if (!K1)
9815     return SDValue();
9816 
9817   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9818   if (!K0)
9819     return SDValue();
9820 
9821   // Ordered >= (although NaN inputs should have folded away by now).
9822   if (K0->getValueAPF() > K1->getValueAPF())
9823     return SDValue();
9824 
9825   const MachineFunction &MF = DAG.getMachineFunction();
9826   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9827 
9828   // TODO: Check IEEE bit enabled?
9829   EVT VT = Op0.getValueType();
9830   if (Info->getMode().DX10Clamp) {
9831     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9832     // hardware fmed3 behavior converting to a min.
9833     // FIXME: Should this be allowing -0.0?
9834     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9835       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9836   }
9837 
9838   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9839   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9840     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9841     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9842     // then give the other result, which is different from med3 with a NaN
9843     // input.
9844     SDValue Var = Op0.getOperand(0);
9845     if (!DAG.isKnownNeverSNaN(Var))
9846       return SDValue();
9847 
9848     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9849 
9850     if ((!K0->hasOneUse() ||
9851          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9852         (!K1->hasOneUse() ||
9853          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9854       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9855                          Var, SDValue(K0, 0), SDValue(K1, 0));
9856     }
9857   }
9858 
9859   return SDValue();
9860 }
9861 
9862 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9863                                                DAGCombinerInfo &DCI) const {
9864   SelectionDAG &DAG = DCI.DAG;
9865 
9866   EVT VT = N->getValueType(0);
9867   unsigned Opc = N->getOpcode();
9868   SDValue Op0 = N->getOperand(0);
9869   SDValue Op1 = N->getOperand(1);
9870 
9871   // Only do this if the inner op has one use since this will just increases
9872   // register pressure for no benefit.
9873 
9874   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9875       !VT.isVector() &&
9876       (VT == MVT::i32 || VT == MVT::f32 ||
9877        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9878     // max(max(a, b), c) -> max3(a, b, c)
9879     // min(min(a, b), c) -> min3(a, b, c)
9880     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9881       SDLoc DL(N);
9882       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9883                          DL,
9884                          N->getValueType(0),
9885                          Op0.getOperand(0),
9886                          Op0.getOperand(1),
9887                          Op1);
9888     }
9889 
9890     // Try commuted.
9891     // max(a, max(b, c)) -> max3(a, b, c)
9892     // min(a, min(b, c)) -> min3(a, b, c)
9893     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9894       SDLoc DL(N);
9895       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9896                          DL,
9897                          N->getValueType(0),
9898                          Op0,
9899                          Op1.getOperand(0),
9900                          Op1.getOperand(1));
9901     }
9902   }
9903 
9904   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9905   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9906     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9907       return Med3;
9908   }
9909 
9910   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9911     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9912       return Med3;
9913   }
9914 
9915   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9916   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9917        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9918        (Opc == AMDGPUISD::FMIN_LEGACY &&
9919         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9920       (VT == MVT::f32 || VT == MVT::f64 ||
9921        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9922        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9923       Op0.hasOneUse()) {
9924     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9925       return Res;
9926   }
9927 
9928   return SDValue();
9929 }
9930 
9931 static bool isClampZeroToOne(SDValue A, SDValue B) {
9932   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9933     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9934       // FIXME: Should this be allowing -0.0?
9935       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9936              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9937     }
9938   }
9939 
9940   return false;
9941 }
9942 
9943 // FIXME: Should only worry about snans for version with chain.
9944 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9945                                               DAGCombinerInfo &DCI) const {
9946   EVT VT = N->getValueType(0);
9947   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9948   // NaNs. With a NaN input, the order of the operands may change the result.
9949 
9950   SelectionDAG &DAG = DCI.DAG;
9951   SDLoc SL(N);
9952 
9953   SDValue Src0 = N->getOperand(0);
9954   SDValue Src1 = N->getOperand(1);
9955   SDValue Src2 = N->getOperand(2);
9956 
9957   if (isClampZeroToOne(Src0, Src1)) {
9958     // const_a, const_b, x -> clamp is safe in all cases including signaling
9959     // nans.
9960     // FIXME: Should this be allowing -0.0?
9961     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9962   }
9963 
9964   const MachineFunction &MF = DAG.getMachineFunction();
9965   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9966 
9967   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9968   // handling no dx10-clamp?
9969   if (Info->getMode().DX10Clamp) {
9970     // If NaNs is clamped to 0, we are free to reorder the inputs.
9971 
9972     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9973       std::swap(Src0, Src1);
9974 
9975     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9976       std::swap(Src1, Src2);
9977 
9978     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9979       std::swap(Src0, Src1);
9980 
9981     if (isClampZeroToOne(Src1, Src2))
9982       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9983   }
9984 
9985   return SDValue();
9986 }
9987 
9988 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9989                                                  DAGCombinerInfo &DCI) const {
9990   SDValue Src0 = N->getOperand(0);
9991   SDValue Src1 = N->getOperand(1);
9992   if (Src0.isUndef() && Src1.isUndef())
9993     return DCI.DAG.getUNDEF(N->getValueType(0));
9994   return SDValue();
9995 }
9996 
9997 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9998 // expanded into a set of cmp/select instructions.
9999 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10000                                                 unsigned NumElem,
10001                                                 bool IsDivergentIdx) {
10002   if (UseDivergentRegisterIndexing)
10003     return false;
10004 
10005   unsigned VecSize = EltSize * NumElem;
10006 
10007   // Sub-dword vectors of size 2 dword or less have better implementation.
10008   if (VecSize <= 64 && EltSize < 32)
10009     return false;
10010 
10011   // Always expand the rest of sub-dword instructions, otherwise it will be
10012   // lowered via memory.
10013   if (EltSize < 32)
10014     return true;
10015 
10016   // Always do this if var-idx is divergent, otherwise it will become a loop.
10017   if (IsDivergentIdx)
10018     return true;
10019 
10020   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10021   unsigned NumInsts = NumElem /* Number of compares */ +
10022                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10023   return NumInsts <= 16;
10024 }
10025 
10026 static bool shouldExpandVectorDynExt(SDNode *N) {
10027   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10028   if (isa<ConstantSDNode>(Idx))
10029     return false;
10030 
10031   SDValue Vec = N->getOperand(0);
10032   EVT VecVT = Vec.getValueType();
10033   EVT EltVT = VecVT.getVectorElementType();
10034   unsigned EltSize = EltVT.getSizeInBits();
10035   unsigned NumElem = VecVT.getVectorNumElements();
10036 
10037   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10038                                                     Idx->isDivergent());
10039 }
10040 
10041 SDValue SITargetLowering::performExtractVectorEltCombine(
10042   SDNode *N, DAGCombinerInfo &DCI) const {
10043   SDValue Vec = N->getOperand(0);
10044   SelectionDAG &DAG = DCI.DAG;
10045 
10046   EVT VecVT = Vec.getValueType();
10047   EVT EltVT = VecVT.getVectorElementType();
10048 
10049   if ((Vec.getOpcode() == ISD::FNEG ||
10050        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10051     SDLoc SL(N);
10052     EVT EltVT = N->getValueType(0);
10053     SDValue Idx = N->getOperand(1);
10054     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10055                               Vec.getOperand(0), Idx);
10056     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10057   }
10058 
10059   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10060   //    =>
10061   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10062   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10063   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10064   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10065     SDLoc SL(N);
10066     EVT EltVT = N->getValueType(0);
10067     SDValue Idx = N->getOperand(1);
10068     unsigned Opc = Vec.getOpcode();
10069 
10070     switch(Opc) {
10071     default:
10072       break;
10073       // TODO: Support other binary operations.
10074     case ISD::FADD:
10075     case ISD::FSUB:
10076     case ISD::FMUL:
10077     case ISD::ADD:
10078     case ISD::UMIN:
10079     case ISD::UMAX:
10080     case ISD::SMIN:
10081     case ISD::SMAX:
10082     case ISD::FMAXNUM:
10083     case ISD::FMINNUM:
10084     case ISD::FMAXNUM_IEEE:
10085     case ISD::FMINNUM_IEEE: {
10086       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10087                                  Vec.getOperand(0), Idx);
10088       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10089                                  Vec.getOperand(1), Idx);
10090 
10091       DCI.AddToWorklist(Elt0.getNode());
10092       DCI.AddToWorklist(Elt1.getNode());
10093       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10094     }
10095     }
10096   }
10097 
10098   unsigned VecSize = VecVT.getSizeInBits();
10099   unsigned EltSize = EltVT.getSizeInBits();
10100 
10101   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10102   if (::shouldExpandVectorDynExt(N)) {
10103     SDLoc SL(N);
10104     SDValue Idx = N->getOperand(1);
10105     SDValue V;
10106     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10107       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10108       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10109       if (I == 0)
10110         V = Elt;
10111       else
10112         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10113     }
10114     return V;
10115   }
10116 
10117   if (!DCI.isBeforeLegalize())
10118     return SDValue();
10119 
10120   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10121   // elements. This exposes more load reduction opportunities by replacing
10122   // multiple small extract_vector_elements with a single 32-bit extract.
10123   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10124   if (isa<MemSDNode>(Vec) &&
10125       EltSize <= 16 &&
10126       EltVT.isByteSized() &&
10127       VecSize > 32 &&
10128       VecSize % 32 == 0 &&
10129       Idx) {
10130     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10131 
10132     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10133     unsigned EltIdx = BitIndex / 32;
10134     unsigned LeftoverBitIdx = BitIndex % 32;
10135     SDLoc SL(N);
10136 
10137     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10138     DCI.AddToWorklist(Cast.getNode());
10139 
10140     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10141                               DAG.getConstant(EltIdx, SL, MVT::i32));
10142     DCI.AddToWorklist(Elt.getNode());
10143     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10144                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10145     DCI.AddToWorklist(Srl.getNode());
10146 
10147     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10148     DCI.AddToWorklist(Trunc.getNode());
10149     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10150   }
10151 
10152   return SDValue();
10153 }
10154 
10155 SDValue
10156 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10157                                                 DAGCombinerInfo &DCI) const {
10158   SDValue Vec = N->getOperand(0);
10159   SDValue Idx = N->getOperand(2);
10160   EVT VecVT = Vec.getValueType();
10161   EVT EltVT = VecVT.getVectorElementType();
10162 
10163   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10164   // => BUILD_VECTOR n x select (e, const-idx)
10165   if (!::shouldExpandVectorDynExt(N))
10166     return SDValue();
10167 
10168   SelectionDAG &DAG = DCI.DAG;
10169   SDLoc SL(N);
10170   SDValue Ins = N->getOperand(1);
10171   EVT IdxVT = Idx.getValueType();
10172 
10173   SmallVector<SDValue, 16> Ops;
10174   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10175     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10176     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10177     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10178     Ops.push_back(V);
10179   }
10180 
10181   return DAG.getBuildVector(VecVT, SL, Ops);
10182 }
10183 
10184 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10185                                           const SDNode *N0,
10186                                           const SDNode *N1) const {
10187   EVT VT = N0->getValueType(0);
10188 
10189   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10190   // support denormals ever.
10191   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10192        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10193         getSubtarget()->hasMadF16())) &&
10194        isOperationLegal(ISD::FMAD, VT))
10195     return ISD::FMAD;
10196 
10197   const TargetOptions &Options = DAG.getTarget().Options;
10198   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10199        (N0->getFlags().hasAllowContract() &&
10200         N1->getFlags().hasAllowContract())) &&
10201       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10202     return ISD::FMA;
10203   }
10204 
10205   return 0;
10206 }
10207 
10208 // For a reassociatable opcode perform:
10209 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10210 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10211                                                SelectionDAG &DAG) const {
10212   EVT VT = N->getValueType(0);
10213   if (VT != MVT::i32 && VT != MVT::i64)
10214     return SDValue();
10215 
10216   unsigned Opc = N->getOpcode();
10217   SDValue Op0 = N->getOperand(0);
10218   SDValue Op1 = N->getOperand(1);
10219 
10220   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10221     return SDValue();
10222 
10223   if (Op0->isDivergent())
10224     std::swap(Op0, Op1);
10225 
10226   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10227     return SDValue();
10228 
10229   SDValue Op2 = Op1.getOperand(1);
10230   Op1 = Op1.getOperand(0);
10231   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10232     return SDValue();
10233 
10234   if (Op1->isDivergent())
10235     std::swap(Op1, Op2);
10236 
10237   // If either operand is constant this will conflict with
10238   // DAGCombiner::ReassociateOps().
10239   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10240       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10241     return SDValue();
10242 
10243   SDLoc SL(N);
10244   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10245   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10246 }
10247 
10248 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10249                            EVT VT,
10250                            SDValue N0, SDValue N1, SDValue N2,
10251                            bool Signed) {
10252   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10253   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10254   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10255   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10256 }
10257 
10258 SDValue SITargetLowering::performAddCombine(SDNode *N,
10259                                             DAGCombinerInfo &DCI) const {
10260   SelectionDAG &DAG = DCI.DAG;
10261   EVT VT = N->getValueType(0);
10262   SDLoc SL(N);
10263   SDValue LHS = N->getOperand(0);
10264   SDValue RHS = N->getOperand(1);
10265 
10266   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10267       && Subtarget->hasMad64_32() &&
10268       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10269       VT.getScalarSizeInBits() <= 64) {
10270     if (LHS.getOpcode() != ISD::MUL)
10271       std::swap(LHS, RHS);
10272 
10273     SDValue MulLHS = LHS.getOperand(0);
10274     SDValue MulRHS = LHS.getOperand(1);
10275     SDValue AddRHS = RHS;
10276 
10277     // TODO: Maybe restrict if SGPR inputs.
10278     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10279         numBitsUnsigned(MulRHS, DAG) <= 32) {
10280       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10281       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10282       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10283       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10284     }
10285 
10286     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10287       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10288       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10289       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10290       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10291     }
10292 
10293     return SDValue();
10294   }
10295 
10296   if (SDValue V = reassociateScalarOps(N, DAG)) {
10297     return V;
10298   }
10299 
10300   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10301     return SDValue();
10302 
10303   // add x, zext (setcc) => addcarry x, 0, setcc
10304   // add x, sext (setcc) => subcarry x, 0, setcc
10305   unsigned Opc = LHS.getOpcode();
10306   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10307       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10308     std::swap(RHS, LHS);
10309 
10310   Opc = RHS.getOpcode();
10311   switch (Opc) {
10312   default: break;
10313   case ISD::ZERO_EXTEND:
10314   case ISD::SIGN_EXTEND:
10315   case ISD::ANY_EXTEND: {
10316     auto Cond = RHS.getOperand(0);
10317     // If this won't be a real VOPC output, we would still need to insert an
10318     // extra instruction anyway.
10319     if (!isBoolSGPR(Cond))
10320       break;
10321     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10322     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10323     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10324     return DAG.getNode(Opc, SL, VTList, Args);
10325   }
10326   case ISD::ADDCARRY: {
10327     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10328     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10329     if (!C || C->getZExtValue() != 0) break;
10330     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10331     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10332   }
10333   }
10334   return SDValue();
10335 }
10336 
10337 SDValue SITargetLowering::performSubCombine(SDNode *N,
10338                                             DAGCombinerInfo &DCI) const {
10339   SelectionDAG &DAG = DCI.DAG;
10340   EVT VT = N->getValueType(0);
10341 
10342   if (VT != MVT::i32)
10343     return SDValue();
10344 
10345   SDLoc SL(N);
10346   SDValue LHS = N->getOperand(0);
10347   SDValue RHS = N->getOperand(1);
10348 
10349   // sub x, zext (setcc) => subcarry x, 0, setcc
10350   // sub x, sext (setcc) => addcarry x, 0, setcc
10351   unsigned Opc = RHS.getOpcode();
10352   switch (Opc) {
10353   default: break;
10354   case ISD::ZERO_EXTEND:
10355   case ISD::SIGN_EXTEND:
10356   case ISD::ANY_EXTEND: {
10357     auto Cond = RHS.getOperand(0);
10358     // If this won't be a real VOPC output, we would still need to insert an
10359     // extra instruction anyway.
10360     if (!isBoolSGPR(Cond))
10361       break;
10362     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10363     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10364     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10365     return DAG.getNode(Opc, SL, VTList, Args);
10366   }
10367   }
10368 
10369   if (LHS.getOpcode() == ISD::SUBCARRY) {
10370     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10371     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10372     if (!C || !C->isNullValue())
10373       return SDValue();
10374     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10375     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10376   }
10377   return SDValue();
10378 }
10379 
10380 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10381   DAGCombinerInfo &DCI) const {
10382 
10383   if (N->getValueType(0) != MVT::i32)
10384     return SDValue();
10385 
10386   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10387   if (!C || C->getZExtValue() != 0)
10388     return SDValue();
10389 
10390   SelectionDAG &DAG = DCI.DAG;
10391   SDValue LHS = N->getOperand(0);
10392 
10393   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10394   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10395   unsigned LHSOpc = LHS.getOpcode();
10396   unsigned Opc = N->getOpcode();
10397   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10398       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10399     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10400     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10401   }
10402   return SDValue();
10403 }
10404 
10405 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10406                                              DAGCombinerInfo &DCI) const {
10407   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10408     return SDValue();
10409 
10410   SelectionDAG &DAG = DCI.DAG;
10411   EVT VT = N->getValueType(0);
10412 
10413   SDLoc SL(N);
10414   SDValue LHS = N->getOperand(0);
10415   SDValue RHS = N->getOperand(1);
10416 
10417   // These should really be instruction patterns, but writing patterns with
10418   // source modiifiers is a pain.
10419 
10420   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10421   if (LHS.getOpcode() == ISD::FADD) {
10422     SDValue A = LHS.getOperand(0);
10423     if (A == LHS.getOperand(1)) {
10424       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10425       if (FusedOp != 0) {
10426         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10427         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10428       }
10429     }
10430   }
10431 
10432   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10433   if (RHS.getOpcode() == ISD::FADD) {
10434     SDValue A = RHS.getOperand(0);
10435     if (A == RHS.getOperand(1)) {
10436       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10437       if (FusedOp != 0) {
10438         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10439         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10440       }
10441     }
10442   }
10443 
10444   return SDValue();
10445 }
10446 
10447 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10448                                              DAGCombinerInfo &DCI) const {
10449   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10450     return SDValue();
10451 
10452   SelectionDAG &DAG = DCI.DAG;
10453   SDLoc SL(N);
10454   EVT VT = N->getValueType(0);
10455   assert(!VT.isVector());
10456 
10457   // Try to get the fneg to fold into the source modifier. This undoes generic
10458   // DAG combines and folds them into the mad.
10459   //
10460   // Only do this if we are not trying to support denormals. v_mad_f32 does
10461   // not support denormals ever.
10462   SDValue LHS = N->getOperand(0);
10463   SDValue RHS = N->getOperand(1);
10464   if (LHS.getOpcode() == ISD::FADD) {
10465     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10466     SDValue A = LHS.getOperand(0);
10467     if (A == LHS.getOperand(1)) {
10468       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10469       if (FusedOp != 0){
10470         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10471         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10472 
10473         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10474       }
10475     }
10476   }
10477 
10478   if (RHS.getOpcode() == ISD::FADD) {
10479     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10480 
10481     SDValue A = RHS.getOperand(0);
10482     if (A == RHS.getOperand(1)) {
10483       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10484       if (FusedOp != 0){
10485         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10486         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10487       }
10488     }
10489   }
10490 
10491   return SDValue();
10492 }
10493 
10494 SDValue SITargetLowering::performFMACombine(SDNode *N,
10495                                             DAGCombinerInfo &DCI) const {
10496   SelectionDAG &DAG = DCI.DAG;
10497   EVT VT = N->getValueType(0);
10498   SDLoc SL(N);
10499 
10500   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10501     return SDValue();
10502 
10503   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10504   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10505   SDValue Op1 = N->getOperand(0);
10506   SDValue Op2 = N->getOperand(1);
10507   SDValue FMA = N->getOperand(2);
10508 
10509   if (FMA.getOpcode() != ISD::FMA ||
10510       Op1.getOpcode() != ISD::FP_EXTEND ||
10511       Op2.getOpcode() != ISD::FP_EXTEND)
10512     return SDValue();
10513 
10514   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10515   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10516   // is sufficient to allow generaing fdot2.
10517   const TargetOptions &Options = DAG.getTarget().Options;
10518   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10519       (N->getFlags().hasAllowContract() &&
10520        FMA->getFlags().hasAllowContract())) {
10521     Op1 = Op1.getOperand(0);
10522     Op2 = Op2.getOperand(0);
10523     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10524         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10525       return SDValue();
10526 
10527     SDValue Vec1 = Op1.getOperand(0);
10528     SDValue Idx1 = Op1.getOperand(1);
10529     SDValue Vec2 = Op2.getOperand(0);
10530 
10531     SDValue FMAOp1 = FMA.getOperand(0);
10532     SDValue FMAOp2 = FMA.getOperand(1);
10533     SDValue FMAAcc = FMA.getOperand(2);
10534 
10535     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10536         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10537       return SDValue();
10538 
10539     FMAOp1 = FMAOp1.getOperand(0);
10540     FMAOp2 = FMAOp2.getOperand(0);
10541     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10542         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10543       return SDValue();
10544 
10545     SDValue Vec3 = FMAOp1.getOperand(0);
10546     SDValue Vec4 = FMAOp2.getOperand(0);
10547     SDValue Idx2 = FMAOp1.getOperand(1);
10548 
10549     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10550         // Idx1 and Idx2 cannot be the same.
10551         Idx1 == Idx2)
10552       return SDValue();
10553 
10554     if (Vec1 == Vec2 || Vec3 == Vec4)
10555       return SDValue();
10556 
10557     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10558       return SDValue();
10559 
10560     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10561         (Vec1 == Vec4 && Vec2 == Vec3)) {
10562       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10563                          DAG.getTargetConstant(0, SL, MVT::i1));
10564     }
10565   }
10566   return SDValue();
10567 }
10568 
10569 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10570                                               DAGCombinerInfo &DCI) const {
10571   SelectionDAG &DAG = DCI.DAG;
10572   SDLoc SL(N);
10573 
10574   SDValue LHS = N->getOperand(0);
10575   SDValue RHS = N->getOperand(1);
10576   EVT VT = LHS.getValueType();
10577   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10578 
10579   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10580   if (!CRHS) {
10581     CRHS = dyn_cast<ConstantSDNode>(LHS);
10582     if (CRHS) {
10583       std::swap(LHS, RHS);
10584       CC = getSetCCSwappedOperands(CC);
10585     }
10586   }
10587 
10588   if (CRHS) {
10589     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10590         isBoolSGPR(LHS.getOperand(0))) {
10591       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10592       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10593       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10594       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10595       if ((CRHS->isAllOnesValue() &&
10596            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10597           (CRHS->isNullValue() &&
10598            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10599         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10600                            DAG.getConstant(-1, SL, MVT::i1));
10601       if ((CRHS->isAllOnesValue() &&
10602            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10603           (CRHS->isNullValue() &&
10604            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10605         return LHS.getOperand(0);
10606     }
10607 
10608     uint64_t CRHSVal = CRHS->getZExtValue();
10609     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10610         LHS.getOpcode() == ISD::SELECT &&
10611         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10612         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10613         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10614         isBoolSGPR(LHS.getOperand(0))) {
10615       // Given CT != FT:
10616       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10617       // setcc (select cc, CT, CF), CF, ne => cc
10618       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10619       // setcc (select cc, CT, CF), CT, eq => cc
10620       uint64_t CT = LHS.getConstantOperandVal(1);
10621       uint64_t CF = LHS.getConstantOperandVal(2);
10622 
10623       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10624           (CT == CRHSVal && CC == ISD::SETNE))
10625         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10626                            DAG.getConstant(-1, SL, MVT::i1));
10627       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10628           (CT == CRHSVal && CC == ISD::SETEQ))
10629         return LHS.getOperand(0);
10630     }
10631   }
10632 
10633   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10634                                            VT != MVT::f16))
10635     return SDValue();
10636 
10637   // Match isinf/isfinite pattern
10638   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10639   // (fcmp one (fabs x), inf) -> (fp_class x,
10640   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10641   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10642     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10643     if (!CRHS)
10644       return SDValue();
10645 
10646     const APFloat &APF = CRHS->getValueAPF();
10647     if (APF.isInfinity() && !APF.isNegative()) {
10648       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10649                                  SIInstrFlags::N_INFINITY;
10650       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10651                                     SIInstrFlags::P_ZERO |
10652                                     SIInstrFlags::N_NORMAL |
10653                                     SIInstrFlags::P_NORMAL |
10654                                     SIInstrFlags::N_SUBNORMAL |
10655                                     SIInstrFlags::P_SUBNORMAL;
10656       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10657       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10658                          DAG.getConstant(Mask, SL, MVT::i32));
10659     }
10660   }
10661 
10662   return SDValue();
10663 }
10664 
10665 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10666                                                      DAGCombinerInfo &DCI) const {
10667   SelectionDAG &DAG = DCI.DAG;
10668   SDLoc SL(N);
10669   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10670 
10671   SDValue Src = N->getOperand(0);
10672   SDValue Shift = N->getOperand(0);
10673 
10674   // TODO: Extend type shouldn't matter (assuming legal types).
10675   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10676     Shift = Shift.getOperand(0);
10677 
10678   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10679     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10680     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10681     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10682     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10683     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10684     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10685       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10686                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10687 
10688       unsigned ShiftOffset = 8 * Offset;
10689       if (Shift.getOpcode() == ISD::SHL)
10690         ShiftOffset -= C->getZExtValue();
10691       else
10692         ShiftOffset += C->getZExtValue();
10693 
10694       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10695         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10696                            MVT::f32, Shift);
10697       }
10698     }
10699   }
10700 
10701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10702   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10703   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10704     // We simplified Src. If this node is not dead, visit it again so it is
10705     // folded properly.
10706     if (N->getOpcode() != ISD::DELETED_NODE)
10707       DCI.AddToWorklist(N);
10708     return SDValue(N, 0);
10709   }
10710 
10711   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10712   if (SDValue DemandedSrc =
10713           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10714     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10715 
10716   return SDValue();
10717 }
10718 
10719 SDValue SITargetLowering::performClampCombine(SDNode *N,
10720                                               DAGCombinerInfo &DCI) const {
10721   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10722   if (!CSrc)
10723     return SDValue();
10724 
10725   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10726   const APFloat &F = CSrc->getValueAPF();
10727   APFloat Zero = APFloat::getZero(F.getSemantics());
10728   if (F < Zero ||
10729       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10730     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10731   }
10732 
10733   APFloat One(F.getSemantics(), "1.0");
10734   if (F > One)
10735     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10736 
10737   return SDValue(CSrc, 0);
10738 }
10739 
10740 
10741 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10742                                             DAGCombinerInfo &DCI) const {
10743   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10744     return SDValue();
10745   switch (N->getOpcode()) {
10746   case ISD::ADD:
10747     return performAddCombine(N, DCI);
10748   case ISD::SUB:
10749     return performSubCombine(N, DCI);
10750   case ISD::ADDCARRY:
10751   case ISD::SUBCARRY:
10752     return performAddCarrySubCarryCombine(N, DCI);
10753   case ISD::FADD:
10754     return performFAddCombine(N, DCI);
10755   case ISD::FSUB:
10756     return performFSubCombine(N, DCI);
10757   case ISD::SETCC:
10758     return performSetCCCombine(N, DCI);
10759   case ISD::FMAXNUM:
10760   case ISD::FMINNUM:
10761   case ISD::FMAXNUM_IEEE:
10762   case ISD::FMINNUM_IEEE:
10763   case ISD::SMAX:
10764   case ISD::SMIN:
10765   case ISD::UMAX:
10766   case ISD::UMIN:
10767   case AMDGPUISD::FMIN_LEGACY:
10768   case AMDGPUISD::FMAX_LEGACY:
10769     return performMinMaxCombine(N, DCI);
10770   case ISD::FMA:
10771     return performFMACombine(N, DCI);
10772   case ISD::AND:
10773     return performAndCombine(N, DCI);
10774   case ISD::OR:
10775     return performOrCombine(N, DCI);
10776   case ISD::XOR:
10777     return performXorCombine(N, DCI);
10778   case ISD::ZERO_EXTEND:
10779     return performZeroExtendCombine(N, DCI);
10780   case ISD::SIGN_EXTEND_INREG:
10781     return performSignExtendInRegCombine(N , DCI);
10782   case AMDGPUISD::FP_CLASS:
10783     return performClassCombine(N, DCI);
10784   case ISD::FCANONICALIZE:
10785     return performFCanonicalizeCombine(N, DCI);
10786   case AMDGPUISD::RCP:
10787     return performRcpCombine(N, DCI);
10788   case AMDGPUISD::FRACT:
10789   case AMDGPUISD::RSQ:
10790   case AMDGPUISD::RCP_LEGACY:
10791   case AMDGPUISD::RCP_IFLAG:
10792   case AMDGPUISD::RSQ_CLAMP:
10793   case AMDGPUISD::LDEXP: {
10794     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10795     SDValue Src = N->getOperand(0);
10796     if (Src.isUndef())
10797       return Src;
10798     break;
10799   }
10800   case ISD::SINT_TO_FP:
10801   case ISD::UINT_TO_FP:
10802     return performUCharToFloatCombine(N, DCI);
10803   case AMDGPUISD::CVT_F32_UBYTE0:
10804   case AMDGPUISD::CVT_F32_UBYTE1:
10805   case AMDGPUISD::CVT_F32_UBYTE2:
10806   case AMDGPUISD::CVT_F32_UBYTE3:
10807     return performCvtF32UByteNCombine(N, DCI);
10808   case AMDGPUISD::FMED3:
10809     return performFMed3Combine(N, DCI);
10810   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10811     return performCvtPkRTZCombine(N, DCI);
10812   case AMDGPUISD::CLAMP:
10813     return performClampCombine(N, DCI);
10814   case ISD::SCALAR_TO_VECTOR: {
10815     SelectionDAG &DAG = DCI.DAG;
10816     EVT VT = N->getValueType(0);
10817 
10818     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10819     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10820       SDLoc SL(N);
10821       SDValue Src = N->getOperand(0);
10822       EVT EltVT = Src.getValueType();
10823       if (EltVT == MVT::f16)
10824         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10825 
10826       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10827       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10828     }
10829 
10830     break;
10831   }
10832   case ISD::EXTRACT_VECTOR_ELT:
10833     return performExtractVectorEltCombine(N, DCI);
10834   case ISD::INSERT_VECTOR_ELT:
10835     return performInsertVectorEltCombine(N, DCI);
10836   case ISD::LOAD: {
10837     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10838       return Widended;
10839     LLVM_FALLTHROUGH;
10840   }
10841   default: {
10842     if (!DCI.isBeforeLegalize()) {
10843       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10844         return performMemSDNodeCombine(MemNode, DCI);
10845     }
10846 
10847     break;
10848   }
10849   }
10850 
10851   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10852 }
10853 
10854 /// Helper function for adjustWritemask
10855 static unsigned SubIdx2Lane(unsigned Idx) {
10856   switch (Idx) {
10857   default: return 0;
10858   case AMDGPU::sub0: return 0;
10859   case AMDGPU::sub1: return 1;
10860   case AMDGPU::sub2: return 2;
10861   case AMDGPU::sub3: return 3;
10862   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10863   }
10864 }
10865 
10866 /// Adjust the writemask of MIMG instructions
10867 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10868                                           SelectionDAG &DAG) const {
10869   unsigned Opcode = Node->getMachineOpcode();
10870 
10871   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10872   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10873   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10874     return Node; // not implemented for D16
10875 
10876   SDNode *Users[5] = { nullptr };
10877   unsigned Lane = 0;
10878   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10879   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10880   unsigned NewDmask = 0;
10881   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10882   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10883   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10884                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10885   unsigned TFCLane = 0;
10886   bool HasChain = Node->getNumValues() > 1;
10887 
10888   if (OldDmask == 0) {
10889     // These are folded out, but on the chance it happens don't assert.
10890     return Node;
10891   }
10892 
10893   unsigned OldBitsSet = countPopulation(OldDmask);
10894   // Work out which is the TFE/LWE lane if that is enabled.
10895   if (UsesTFC) {
10896     TFCLane = OldBitsSet;
10897   }
10898 
10899   // Try to figure out the used register components
10900   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10901        I != E; ++I) {
10902 
10903     // Don't look at users of the chain.
10904     if (I.getUse().getResNo() != 0)
10905       continue;
10906 
10907     // Abort if we can't understand the usage
10908     if (!I->isMachineOpcode() ||
10909         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10910       return Node;
10911 
10912     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10913     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10914     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10915     // set, etc.
10916     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10917 
10918     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10919     if (UsesTFC && Lane == TFCLane) {
10920       Users[Lane] = *I;
10921     } else {
10922       // Set which texture component corresponds to the lane.
10923       unsigned Comp;
10924       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10925         Comp = countTrailingZeros(Dmask);
10926         Dmask &= ~(1 << Comp);
10927       }
10928 
10929       // Abort if we have more than one user per component.
10930       if (Users[Lane])
10931         return Node;
10932 
10933       Users[Lane] = *I;
10934       NewDmask |= 1 << Comp;
10935     }
10936   }
10937 
10938   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10939   bool NoChannels = !NewDmask;
10940   if (NoChannels) {
10941     if (!UsesTFC) {
10942       // No uses of the result and not using TFC. Then do nothing.
10943       return Node;
10944     }
10945     // If the original dmask has one channel - then nothing to do
10946     if (OldBitsSet == 1)
10947       return Node;
10948     // Use an arbitrary dmask - required for the instruction to work
10949     NewDmask = 1;
10950   }
10951   // Abort if there's no change
10952   if (NewDmask == OldDmask)
10953     return Node;
10954 
10955   unsigned BitsSet = countPopulation(NewDmask);
10956 
10957   // Check for TFE or LWE - increase the number of channels by one to account
10958   // for the extra return value
10959   // This will need adjustment for D16 if this is also included in
10960   // adjustWriteMask (this function) but at present D16 are excluded.
10961   unsigned NewChannels = BitsSet + UsesTFC;
10962 
10963   int NewOpcode =
10964       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10965   assert(NewOpcode != -1 &&
10966          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10967          "failed to find equivalent MIMG op");
10968 
10969   // Adjust the writemask in the node
10970   SmallVector<SDValue, 12> Ops;
10971   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10972   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10973   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10974 
10975   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10976 
10977   MVT ResultVT = NewChannels == 1 ?
10978     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10979                            NewChannels == 5 ? 8 : NewChannels);
10980   SDVTList NewVTList = HasChain ?
10981     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10982 
10983 
10984   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10985                                               NewVTList, Ops);
10986 
10987   if (HasChain) {
10988     // Update chain.
10989     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10990     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10991   }
10992 
10993   if (NewChannels == 1) {
10994     assert(Node->hasNUsesOfValue(1, 0));
10995     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10996                                       SDLoc(Node), Users[Lane]->getValueType(0),
10997                                       SDValue(NewNode, 0));
10998     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10999     return nullptr;
11000   }
11001 
11002   // Update the users of the node with the new indices
11003   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11004     SDNode *User = Users[i];
11005     if (!User) {
11006       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11007       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11008       if (i || !NoChannels)
11009         continue;
11010     } else {
11011       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11012       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11013     }
11014 
11015     switch (Idx) {
11016     default: break;
11017     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11018     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11019     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11020     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11021     }
11022   }
11023 
11024   DAG.RemoveDeadNode(Node);
11025   return nullptr;
11026 }
11027 
11028 static bool isFrameIndexOp(SDValue Op) {
11029   if (Op.getOpcode() == ISD::AssertZext)
11030     Op = Op.getOperand(0);
11031 
11032   return isa<FrameIndexSDNode>(Op);
11033 }
11034 
11035 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11036 /// with frame index operands.
11037 /// LLVM assumes that inputs are to these instructions are registers.
11038 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11039                                                         SelectionDAG &DAG) const {
11040   if (Node->getOpcode() == ISD::CopyToReg) {
11041     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11042     SDValue SrcVal = Node->getOperand(2);
11043 
11044     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11045     // to try understanding copies to physical registers.
11046     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11047       SDLoc SL(Node);
11048       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11049       SDValue VReg = DAG.getRegister(
11050         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11051 
11052       SDNode *Glued = Node->getGluedNode();
11053       SDValue ToVReg
11054         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11055                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11056       SDValue ToResultReg
11057         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11058                            VReg, ToVReg.getValue(1));
11059       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11060       DAG.RemoveDeadNode(Node);
11061       return ToResultReg.getNode();
11062     }
11063   }
11064 
11065   SmallVector<SDValue, 8> Ops;
11066   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11067     if (!isFrameIndexOp(Node->getOperand(i))) {
11068       Ops.push_back(Node->getOperand(i));
11069       continue;
11070     }
11071 
11072     SDLoc DL(Node);
11073     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11074                                      Node->getOperand(i).getValueType(),
11075                                      Node->getOperand(i)), 0));
11076   }
11077 
11078   return DAG.UpdateNodeOperands(Node, Ops);
11079 }
11080 
11081 /// Fold the instructions after selecting them.
11082 /// Returns null if users were already updated.
11083 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11084                                           SelectionDAG &DAG) const {
11085   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11086   unsigned Opcode = Node->getMachineOpcode();
11087 
11088   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11089       !TII->isGather4(Opcode) &&
11090       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11091     return adjustWritemask(Node, DAG);
11092   }
11093 
11094   if (Opcode == AMDGPU::INSERT_SUBREG ||
11095       Opcode == AMDGPU::REG_SEQUENCE) {
11096     legalizeTargetIndependentNode(Node, DAG);
11097     return Node;
11098   }
11099 
11100   switch (Opcode) {
11101   case AMDGPU::V_DIV_SCALE_F32:
11102   case AMDGPU::V_DIV_SCALE_F64: {
11103     // Satisfy the operand register constraint when one of the inputs is
11104     // undefined. Ordinarily each undef value will have its own implicit_def of
11105     // a vreg, so force these to use a single register.
11106     SDValue Src0 = Node->getOperand(1);
11107     SDValue Src1 = Node->getOperand(3);
11108     SDValue Src2 = Node->getOperand(5);
11109 
11110     if ((Src0.isMachineOpcode() &&
11111          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11112         (Src0 == Src1 || Src0 == Src2))
11113       break;
11114 
11115     MVT VT = Src0.getValueType().getSimpleVT();
11116     const TargetRegisterClass *RC =
11117         getRegClassFor(VT, Src0.getNode()->isDivergent());
11118 
11119     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11120     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11121 
11122     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11123                                       UndefReg, Src0, SDValue());
11124 
11125     // src0 must be the same register as src1 or src2, even if the value is
11126     // undefined, so make sure we don't violate this constraint.
11127     if (Src0.isMachineOpcode() &&
11128         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11129       if (Src1.isMachineOpcode() &&
11130           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11131         Src0 = Src1;
11132       else if (Src2.isMachineOpcode() &&
11133                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11134         Src0 = Src2;
11135       else {
11136         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11137         Src0 = UndefReg;
11138         Src1 = UndefReg;
11139       }
11140     } else
11141       break;
11142 
11143     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11144     Ops[1] = Src0;
11145     Ops[3] = Src1;
11146     Ops[5] = Src2;
11147     Ops.push_back(ImpDef.getValue(1));
11148     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11149   }
11150   default:
11151     break;
11152   }
11153 
11154   return Node;
11155 }
11156 
11157 /// Assign the register class depending on the number of
11158 /// bits set in the writemask
11159 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11160                                                      SDNode *Node) const {
11161   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11162 
11163   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11164 
11165   if (TII->isVOP3(MI.getOpcode())) {
11166     // Make sure constant bus requirements are respected.
11167     TII->legalizeOperandsVOP3(MRI, MI);
11168 
11169     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11170     // This saves a chain-copy of registers and better ballance register
11171     // use between vgpr and agpr as agpr tuples tend to be big.
11172     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11173       unsigned Opc = MI.getOpcode();
11174       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11175       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11176                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11177         if (I == -1)
11178           break;
11179         MachineOperand &Op = MI.getOperand(I);
11180         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11181              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11182             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11183           continue;
11184         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11185         if (!Src || !Src->isCopy() ||
11186             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11187           continue;
11188         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11189         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11190         // All uses of agpr64 and agpr32 can also accept vgpr except for
11191         // v_accvgpr_read, but we do not produce agpr reads during selection,
11192         // so no use checks are needed.
11193         MRI.setRegClass(Op.getReg(), NewRC);
11194       }
11195     }
11196 
11197     return;
11198   }
11199 
11200   // Replace unused atomics with the no return version.
11201   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11202   if (NoRetAtomicOp != -1) {
11203     if (!Node->hasAnyUseOfValue(0)) {
11204       int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11205                                                AMDGPU::OpName::glc1);
11206       if (Glc1Idx != -1)
11207         MI.RemoveOperand(Glc1Idx);
11208       MI.RemoveOperand(0);
11209       MI.setDesc(TII->get(NoRetAtomicOp));
11210       return;
11211     }
11212 
11213     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11214     // instruction, because the return type of these instructions is a vec2 of
11215     // the memory type, so it can be tied to the input operand.
11216     // This means these instructions always have a use, so we need to add a
11217     // special case to check if the atomic has only one extract_subreg use,
11218     // which itself has no uses.
11219     if ((Node->hasNUsesOfValue(1, 0) &&
11220          Node->use_begin()->isMachineOpcode() &&
11221          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11222          !Node->use_begin()->hasAnyUseOfValue(0))) {
11223       Register Def = MI.getOperand(0).getReg();
11224 
11225       // Change this into a noret atomic.
11226       MI.setDesc(TII->get(NoRetAtomicOp));
11227       MI.RemoveOperand(0);
11228 
11229       // If we only remove the def operand from the atomic instruction, the
11230       // extract_subreg will be left with a use of a vreg without a def.
11231       // So we need to insert an implicit_def to avoid machine verifier
11232       // errors.
11233       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11234               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11235     }
11236     return;
11237   }
11238 }
11239 
11240 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11241                               uint64_t Val) {
11242   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11243   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11244 }
11245 
11246 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11247                                                 const SDLoc &DL,
11248                                                 SDValue Ptr) const {
11249   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11250 
11251   // Build the half of the subregister with the constants before building the
11252   // full 128-bit register. If we are building multiple resource descriptors,
11253   // this will allow CSEing of the 2-component register.
11254   const SDValue Ops0[] = {
11255     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11256     buildSMovImm32(DAG, DL, 0),
11257     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11258     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11259     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11260   };
11261 
11262   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11263                                                 MVT::v2i32, Ops0), 0);
11264 
11265   // Combine the constants and the pointer.
11266   const SDValue Ops1[] = {
11267     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11268     Ptr,
11269     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11270     SubRegHi,
11271     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11272   };
11273 
11274   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11275 }
11276 
11277 /// Return a resource descriptor with the 'Add TID' bit enabled
11278 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11279 ///        of the resource descriptor) to create an offset, which is added to
11280 ///        the resource pointer.
11281 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11282                                            SDValue Ptr, uint32_t RsrcDword1,
11283                                            uint64_t RsrcDword2And3) const {
11284   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11285   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11286   if (RsrcDword1) {
11287     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11288                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11289                     0);
11290   }
11291 
11292   SDValue DataLo = buildSMovImm32(DAG, DL,
11293                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11294   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11295 
11296   const SDValue Ops[] = {
11297     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11298     PtrLo,
11299     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11300     PtrHi,
11301     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11302     DataLo,
11303     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11304     DataHi,
11305     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11306   };
11307 
11308   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11309 }
11310 
11311 //===----------------------------------------------------------------------===//
11312 //                         SI Inline Assembly Support
11313 //===----------------------------------------------------------------------===//
11314 
11315 std::pair<unsigned, const TargetRegisterClass *>
11316 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11317                                                StringRef Constraint,
11318                                                MVT VT) const {
11319   const TargetRegisterClass *RC = nullptr;
11320   if (Constraint.size() == 1) {
11321     const unsigned BitWidth = VT.getSizeInBits();
11322     switch (Constraint[0]) {
11323     default:
11324       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11325     case 's':
11326     case 'r':
11327       switch (BitWidth) {
11328       case 16:
11329         RC = &AMDGPU::SReg_32RegClass;
11330         break;
11331       case 64:
11332         RC = &AMDGPU::SGPR_64RegClass;
11333         break;
11334       default:
11335         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11336         if (!RC)
11337           return std::make_pair(0U, nullptr);
11338         break;
11339       }
11340       break;
11341     case 'v':
11342       switch (BitWidth) {
11343       case 16:
11344         RC = &AMDGPU::VGPR_32RegClass;
11345         break;
11346       default:
11347         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11348         if (!RC)
11349           return std::make_pair(0U, nullptr);
11350         break;
11351       }
11352       break;
11353     case 'a':
11354       if (!Subtarget->hasMAIInsts())
11355         break;
11356       switch (BitWidth) {
11357       case 16:
11358         RC = &AMDGPU::AGPR_32RegClass;
11359         break;
11360       default:
11361         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11362         if (!RC)
11363           return std::make_pair(0U, nullptr);
11364         break;
11365       }
11366       break;
11367     }
11368     // We actually support i128, i16 and f16 as inline parameters
11369     // even if they are not reported as legal
11370     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11371                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11372       return std::make_pair(0U, RC);
11373   }
11374 
11375   if (Constraint.size() > 1) {
11376     if (Constraint[1] == 'v') {
11377       RC = &AMDGPU::VGPR_32RegClass;
11378     } else if (Constraint[1] == 's') {
11379       RC = &AMDGPU::SGPR_32RegClass;
11380     } else if (Constraint[1] == 'a') {
11381       RC = &AMDGPU::AGPR_32RegClass;
11382     }
11383 
11384     if (RC) {
11385       uint32_t Idx;
11386       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11387       if (!Failed && Idx < RC->getNumRegs())
11388         return std::make_pair(RC->getRegister(Idx), RC);
11389     }
11390   }
11391 
11392   // FIXME: Returns VS_32 for physical SGPR constraints
11393   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11394 }
11395 
11396 static bool isImmConstraint(StringRef Constraint) {
11397   if (Constraint.size() == 1) {
11398     switch (Constraint[0]) {
11399     default: break;
11400     case 'I':
11401     case 'J':
11402     case 'A':
11403     case 'B':
11404     case 'C':
11405       return true;
11406     }
11407   } else if (Constraint == "DA" ||
11408              Constraint == "DB") {
11409     return true;
11410   }
11411   return false;
11412 }
11413 
11414 SITargetLowering::ConstraintType
11415 SITargetLowering::getConstraintType(StringRef Constraint) const {
11416   if (Constraint.size() == 1) {
11417     switch (Constraint[0]) {
11418     default: break;
11419     case 's':
11420     case 'v':
11421     case 'a':
11422       return C_RegisterClass;
11423     }
11424   }
11425   if (isImmConstraint(Constraint)) {
11426     return C_Other;
11427   }
11428   return TargetLowering::getConstraintType(Constraint);
11429 }
11430 
11431 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11432   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11433     Val = Val & maskTrailingOnes<uint64_t>(Size);
11434   }
11435   return Val;
11436 }
11437 
11438 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11439                                                     std::string &Constraint,
11440                                                     std::vector<SDValue> &Ops,
11441                                                     SelectionDAG &DAG) const {
11442   if (isImmConstraint(Constraint)) {
11443     uint64_t Val;
11444     if (getAsmOperandConstVal(Op, Val) &&
11445         checkAsmConstraintVal(Op, Constraint, Val)) {
11446       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11447       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11448     }
11449   } else {
11450     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11451   }
11452 }
11453 
11454 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11455   unsigned Size = Op.getScalarValueSizeInBits();
11456   if (Size > 64)
11457     return false;
11458 
11459   if (Size == 16 && !Subtarget->has16BitInsts())
11460     return false;
11461 
11462   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11463     Val = C->getSExtValue();
11464     return true;
11465   }
11466   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11467     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11468     return true;
11469   }
11470   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11471     if (Size != 16 || Op.getNumOperands() != 2)
11472       return false;
11473     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11474       return false;
11475     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11476       Val = C->getSExtValue();
11477       return true;
11478     }
11479     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11480       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11481       return true;
11482     }
11483   }
11484 
11485   return false;
11486 }
11487 
11488 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11489                                              const std::string &Constraint,
11490                                              uint64_t Val) const {
11491   if (Constraint.size() == 1) {
11492     switch (Constraint[0]) {
11493     case 'I':
11494       return AMDGPU::isInlinableIntLiteral(Val);
11495     case 'J':
11496       return isInt<16>(Val);
11497     case 'A':
11498       return checkAsmConstraintValA(Op, Val);
11499     case 'B':
11500       return isInt<32>(Val);
11501     case 'C':
11502       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11503              AMDGPU::isInlinableIntLiteral(Val);
11504     default:
11505       break;
11506     }
11507   } else if (Constraint.size() == 2) {
11508     if (Constraint == "DA") {
11509       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11510       int64_t LoBits = static_cast<int32_t>(Val);
11511       return checkAsmConstraintValA(Op, HiBits, 32) &&
11512              checkAsmConstraintValA(Op, LoBits, 32);
11513     }
11514     if (Constraint == "DB") {
11515       return true;
11516     }
11517   }
11518   llvm_unreachable("Invalid asm constraint");
11519 }
11520 
11521 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11522                                               uint64_t Val,
11523                                               unsigned MaxSize) const {
11524   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11525   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11526   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11527       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11528       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11529     return true;
11530   }
11531   return false;
11532 }
11533 
11534 // Figure out which registers should be reserved for stack access. Only after
11535 // the function is legalized do we know all of the non-spill stack objects or if
11536 // calls are present.
11537 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11538   MachineRegisterInfo &MRI = MF.getRegInfo();
11539   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11540   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11541   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11542 
11543   if (Info->isEntryFunction()) {
11544     // Callable functions have fixed registers used for stack access.
11545     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11546   }
11547 
11548   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11549                              Info->getStackPtrOffsetReg()));
11550   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11551     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11552 
11553   // We need to worry about replacing the default register with itself in case
11554   // of MIR testcases missing the MFI.
11555   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11556     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11557 
11558   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11559     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11560 
11561   Info->limitOccupancy(MF);
11562 
11563   if (ST.isWave32() && !MF.empty()) {
11564     // Add VCC_HI def because many instructions marked as imp-use VCC where
11565     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11566     // having a use of undef.
11567 
11568     const SIInstrInfo *TII = ST.getInstrInfo();
11569     DebugLoc DL;
11570 
11571     MachineBasicBlock &MBB = MF.front();
11572     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11573     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11574 
11575     for (auto &MBB : MF) {
11576       for (auto &MI : MBB) {
11577         TII->fixImplicitOperands(MI);
11578       }
11579     }
11580   }
11581 
11582   TargetLoweringBase::finalizeLowering(MF);
11583 
11584   // Allocate a VGPR for future SGPR Spill if
11585   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11586   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11587   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11588       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11589     Info->reserveVGPRforSGPRSpills(MF);
11590 }
11591 
11592 void SITargetLowering::computeKnownBitsForFrameIndex(
11593   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11594   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11595 
11596   // Set the high bits to zero based on the maximum allowed scratch size per
11597   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11598   // calculation won't overflow, so assume the sign bit is never set.
11599   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11600 }
11601 
11602 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11603                                    KnownBits &Known, unsigned Dim) {
11604   unsigned MaxValue =
11605       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11606   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11607 }
11608 
11609 void SITargetLowering::computeKnownBitsForTargetInstr(
11610     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11611     const MachineRegisterInfo &MRI, unsigned Depth) const {
11612   const MachineInstr *MI = MRI.getVRegDef(R);
11613   switch (MI->getOpcode()) {
11614   case AMDGPU::G_INTRINSIC: {
11615     switch (MI->getIntrinsicID()) {
11616     case Intrinsic::amdgcn_workitem_id_x:
11617       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11618       break;
11619     case Intrinsic::amdgcn_workitem_id_y:
11620       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11621       break;
11622     case Intrinsic::amdgcn_workitem_id_z:
11623       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11624       break;
11625     case Intrinsic::amdgcn_mbcnt_lo:
11626     case Intrinsic::amdgcn_mbcnt_hi: {
11627       // These return at most the wavefront size - 1.
11628       unsigned Size = MRI.getType(R).getSizeInBits();
11629       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11630       break;
11631     }
11632     case Intrinsic::amdgcn_groupstaticsize: {
11633       // We can report everything over the maximum size as 0. We can't report
11634       // based on the actual size because we don't know if it's accurate or not
11635       // at any given point.
11636       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11637       break;
11638     }
11639     }
11640     break;
11641   }
11642   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11643     Known.Zero.setHighBits(24);
11644     break;
11645   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11646     Known.Zero.setHighBits(16);
11647     break;
11648   }
11649 }
11650 
11651 Align SITargetLowering::computeKnownAlignForTargetInstr(
11652   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11653   unsigned Depth) const {
11654   const MachineInstr *MI = MRI.getVRegDef(R);
11655   switch (MI->getOpcode()) {
11656   case AMDGPU::G_INTRINSIC:
11657   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11658     // FIXME: Can this move to generic code? What about the case where the call
11659     // site specifies a lower alignment?
11660     Intrinsic::ID IID = MI->getIntrinsicID();
11661     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11662     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11663     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11664       return *RetAlign;
11665     return Align(1);
11666   }
11667   default:
11668     return Align(1);
11669   }
11670 }
11671 
11672 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11673   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11674   const Align CacheLineAlign = Align(64);
11675 
11676   // Pre-GFX10 target did not benefit from loop alignment
11677   if (!ML || DisableLoopAlignment ||
11678       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11679       getSubtarget()->hasInstFwdPrefetchBug())
11680     return PrefAlign;
11681 
11682   // On GFX10 I$ is 4 x 64 bytes cache lines.
11683   // By default prefetcher keeps one cache line behind and reads two ahead.
11684   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11685   // behind and one ahead.
11686   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11687   // If loop fits 64 bytes it always spans no more than two cache lines and
11688   // does not need an alignment.
11689   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11690   // Else if loop is less or equal 192 bytes we need two lines behind.
11691 
11692   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11693   const MachineBasicBlock *Header = ML->getHeader();
11694   if (Header->getAlignment() != PrefAlign)
11695     return Header->getAlignment(); // Already processed.
11696 
11697   unsigned LoopSize = 0;
11698   for (const MachineBasicBlock *MBB : ML->blocks()) {
11699     // If inner loop block is aligned assume in average half of the alignment
11700     // size to be added as nops.
11701     if (MBB != Header)
11702       LoopSize += MBB->getAlignment().value() / 2;
11703 
11704     for (const MachineInstr &MI : *MBB) {
11705       LoopSize += TII->getInstSizeInBytes(MI);
11706       if (LoopSize > 192)
11707         return PrefAlign;
11708     }
11709   }
11710 
11711   if (LoopSize <= 64)
11712     return PrefAlign;
11713 
11714   if (LoopSize <= 128)
11715     return CacheLineAlign;
11716 
11717   // If any of parent loops is surrounded by prefetch instructions do not
11718   // insert new for inner loop, which would reset parent's settings.
11719   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11720     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11721       auto I = Exit->getFirstNonDebugInstr();
11722       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11723         return CacheLineAlign;
11724     }
11725   }
11726 
11727   MachineBasicBlock *Pre = ML->getLoopPreheader();
11728   MachineBasicBlock *Exit = ML->getExitBlock();
11729 
11730   if (Pre && Exit) {
11731     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11732             TII->get(AMDGPU::S_INST_PREFETCH))
11733       .addImm(1); // prefetch 2 lines behind PC
11734 
11735     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11736             TII->get(AMDGPU::S_INST_PREFETCH))
11737       .addImm(2); // prefetch 1 line behind PC
11738   }
11739 
11740   return CacheLineAlign;
11741 }
11742 
11743 LLVM_ATTRIBUTE_UNUSED
11744 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11745   assert(N->getOpcode() == ISD::CopyFromReg);
11746   do {
11747     // Follow the chain until we find an INLINEASM node.
11748     N = N->getOperand(0).getNode();
11749     if (N->getOpcode() == ISD::INLINEASM ||
11750         N->getOpcode() == ISD::INLINEASM_BR)
11751       return true;
11752   } while (N->getOpcode() == ISD::CopyFromReg);
11753   return false;
11754 }
11755 
11756 bool SITargetLowering::isSDNodeSourceOfDivergence(
11757     const SDNode *N, FunctionLoweringInfo *FLI,
11758     LegacyDivergenceAnalysis *KDA) const {
11759   switch (N->getOpcode()) {
11760   case ISD::CopyFromReg: {
11761     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11762     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11763     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11764     Register Reg = R->getReg();
11765 
11766     // FIXME: Why does this need to consider isLiveIn?
11767     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11768       return !TRI->isSGPRReg(MRI, Reg);
11769 
11770     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11771       return KDA->isDivergent(V);
11772 
11773     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11774     return !TRI->isSGPRReg(MRI, Reg);
11775   }
11776   case ISD::LOAD: {
11777     const LoadSDNode *L = cast<LoadSDNode>(N);
11778     unsigned AS = L->getAddressSpace();
11779     // A flat load may access private memory.
11780     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11781   }
11782   case ISD::CALLSEQ_END:
11783     return true;
11784   case ISD::INTRINSIC_WO_CHAIN:
11785     return AMDGPU::isIntrinsicSourceOfDivergence(
11786         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11787   case ISD::INTRINSIC_W_CHAIN:
11788     return AMDGPU::isIntrinsicSourceOfDivergence(
11789         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11790   }
11791   return false;
11792 }
11793 
11794 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11795                                                EVT VT) const {
11796   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11797   case MVT::f32:
11798     return hasFP32Denormals(DAG.getMachineFunction());
11799   case MVT::f64:
11800   case MVT::f16:
11801     return hasFP64FP16Denormals(DAG.getMachineFunction());
11802   default:
11803     return false;
11804   }
11805 }
11806 
11807 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11808                                                     const SelectionDAG &DAG,
11809                                                     bool SNaN,
11810                                                     unsigned Depth) const {
11811   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11812     const MachineFunction &MF = DAG.getMachineFunction();
11813     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11814 
11815     if (Info->getMode().DX10Clamp)
11816       return true; // Clamped to 0.
11817     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11818   }
11819 
11820   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11821                                                             SNaN, Depth);
11822 }
11823 
11824 // Global FP atomic instructions have a hardcoded FP mode and do not support
11825 // FP32 denormals, and only support v2f16 denormals.
11826 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
11827   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
11828   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
11829   if (&Flt == &APFloat::IEEEsingle())
11830     return DenormMode == DenormalMode::getPreserveSign();
11831   return DenormMode == DenormalMode::getIEEE();
11832 }
11833 
11834 TargetLowering::AtomicExpansionKind
11835 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11836   switch (RMW->getOperation()) {
11837   case AtomicRMWInst::FAdd: {
11838     Type *Ty = RMW->getType();
11839 
11840     // We don't have a way to support 16-bit atomics now, so just leave them
11841     // as-is.
11842     if (Ty->isHalfTy())
11843       return AtomicExpansionKind::None;
11844 
11845     if (!Ty->isFloatTy())
11846       return AtomicExpansionKind::CmpXChg;
11847 
11848     // TODO: Do have these for flat. Older targets also had them for buffers.
11849     unsigned AS = RMW->getPointerAddressSpace();
11850 
11851     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11852       if (!fpModeMatchesGlobalFPAtomicMode(RMW))
11853         return AtomicExpansionKind::CmpXChg;
11854 
11855       return RMW->use_empty() ? AtomicExpansionKind::None :
11856                                 AtomicExpansionKind::CmpXChg;
11857     }
11858 
11859     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
11860     // to round-to-nearest-even.
11861     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11862       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11863   }
11864   default:
11865     break;
11866   }
11867 
11868   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11869 }
11870 
11871 const TargetRegisterClass *
11872 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11873   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11874   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11875   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11876     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11877                                                : &AMDGPU::SReg_32RegClass;
11878   if (!TRI->isSGPRClass(RC) && !isDivergent)
11879     return TRI->getEquivalentSGPRClass(RC);
11880   else if (TRI->isSGPRClass(RC) && isDivergent)
11881     return TRI->getEquivalentVGPRClass(RC);
11882 
11883   return RC;
11884 }
11885 
11886 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11887 // uniform values (as produced by the mask results of control flow intrinsics)
11888 // used outside of divergent blocks. The phi users need to also be treated as
11889 // always uniform.
11890 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11891                       unsigned WaveSize) {
11892   // FIXME: We asssume we never cast the mask results of a control flow
11893   // intrinsic.
11894   // Early exit if the type won't be consistent as a compile time hack.
11895   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11896   if (!IT || IT->getBitWidth() != WaveSize)
11897     return false;
11898 
11899   if (!isa<Instruction>(V))
11900     return false;
11901   if (!Visited.insert(V).second)
11902     return false;
11903   bool Result = false;
11904   for (auto U : V->users()) {
11905     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11906       if (V == U->getOperand(1)) {
11907         switch (Intrinsic->getIntrinsicID()) {
11908         default:
11909           Result = false;
11910           break;
11911         case Intrinsic::amdgcn_if_break:
11912         case Intrinsic::amdgcn_if:
11913         case Intrinsic::amdgcn_else:
11914           Result = true;
11915           break;
11916         }
11917       }
11918       if (V == U->getOperand(0)) {
11919         switch (Intrinsic->getIntrinsicID()) {
11920         default:
11921           Result = false;
11922           break;
11923         case Intrinsic::amdgcn_end_cf:
11924         case Intrinsic::amdgcn_loop:
11925           Result = true;
11926           break;
11927         }
11928       }
11929     } else {
11930       Result = hasCFUser(U, Visited, WaveSize);
11931     }
11932     if (Result)
11933       break;
11934   }
11935   return Result;
11936 }
11937 
11938 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11939                                                const Value *V) const {
11940   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11941     if (CI->isInlineAsm()) {
11942       // FIXME: This cannot give a correct answer. This should only trigger in
11943       // the case where inline asm returns mixed SGPR and VGPR results, used
11944       // outside the defining block. We don't have a specific result to
11945       // consider, so this assumes if any value is SGPR, the overall register
11946       // also needs to be SGPR.
11947       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11948       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11949           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11950       for (auto &TC : TargetConstraints) {
11951         if (TC.Type == InlineAsm::isOutput) {
11952           ComputeConstraintToUse(TC, SDValue());
11953           unsigned AssignedReg;
11954           const TargetRegisterClass *RC;
11955           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11956               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11957           if (RC) {
11958             MachineRegisterInfo &MRI = MF.getRegInfo();
11959             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11960               return true;
11961             else if (SIRI->isSGPRClass(RC))
11962               return true;
11963           }
11964         }
11965       }
11966     }
11967   }
11968   SmallPtrSet<const Value *, 16> Visited;
11969   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11970 }
11971 
11972 std::pair<int, MVT>
11973 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11974                                           Type *Ty) const {
11975   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11976   auto Size = DL.getTypeSizeInBits(Ty);
11977   // Maximum load or store can handle 8 dwords for scalar and 4 for
11978   // vector ALU. Let's assume anything above 8 dwords is expensive
11979   // even if legal.
11980   if (Size <= 256)
11981     return Cost;
11982 
11983   Cost.first = (Size + 255) / 256;
11984   return Cost;
11985 }
11986