1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #if defined(_MSC_VER) || defined(__MINGW32__)
15 // Provide M_PI.
16 #define _USE_MATH_DEFINES
17 #endif
18 
19 #include "SIISelLowering.h"
20 #include "AMDGPU.h"
21 #include "AMDGPUSubtarget.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
24 #include "SIDefines.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "Utils/AMDGPUBaseInfo.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/CallingConvLower.h"
41 #include "llvm/CodeGen/DAGCombine.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineLoopInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
93 static cl::opt<bool> DisableLoopAlignment(
94   "amdgpu-disable-loop-alignment",
95   cl::desc("Do not align and prefetch loops"),
96   cl::init(false));
97 
98 static cl::opt<bool> VGPRReserveforSGPRSpill(
99     "amdgpu-reserve-vgpr-for-sgpr-spill",
100     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
101 
102 static bool hasFP32Denormals(const MachineFunction &MF) {
103   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
104   return Info->getMode().allFP32Denormals();
105 }
106 
107 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
108   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
109   return Info->getMode().allFP64FP16Denormals();
110 }
111 
112 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
113   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
114   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
115     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
116       return AMDGPU::SGPR0 + Reg;
117     }
118   }
119   llvm_unreachable("Cannot allocate sgpr");
120 }
121 
122 SITargetLowering::SITargetLowering(const TargetMachine &TM,
123                                    const GCNSubtarget &STI)
124     : AMDGPUTargetLowering(TM, STI),
125       Subtarget(&STI) {
126   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
127   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
128 
129   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
130   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
131 
132   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
133   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
134   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
135 
136   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
137   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
138 
139   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
140   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
141 
142   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
143   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
144 
145   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
146   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
147 
148   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
149   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
150 
151   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
152   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
153 
154   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
155   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
156 
157   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
158   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
159 
160   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
161   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
162 
163   if (Subtarget->has16BitInsts()) {
164     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
165     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
166 
167     // Unless there are also VOP3P operations, not operations are really legal.
168     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
169     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
170     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
171     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
172   }
173 
174   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
175   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
176 
177   computeRegisterProperties(Subtarget->getRegisterInfo());
178 
179   // The boolean content concept here is too inflexible. Compares only ever
180   // really produce a 1-bit result. Any copy/extend from these will turn into a
181   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
182   // it's what most targets use.
183   setBooleanContents(ZeroOrOneBooleanContent);
184   setBooleanVectorContents(ZeroOrOneBooleanContent);
185 
186   // We need to custom lower vector stores from local memory
187   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
188   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
189   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
190   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::i1, Custom);
194   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
195 
196   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
197   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
198   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
199   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
202   setOperationAction(ISD::STORE, MVT::i1, Custom);
203   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
204 
205   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
206   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
207   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
208   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
209   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
210   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
211   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
212   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
213   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
214   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
215   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
216   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
217   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
218   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
219   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
220   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
221 
222   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
223   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
224 
225   setOperationAction(ISD::SELECT, MVT::i1, Promote);
226   setOperationAction(ISD::SELECT, MVT::i64, Custom);
227   setOperationAction(ISD::SELECT, MVT::f64, Promote);
228   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
229 
230   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
231   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
232   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
233   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
234   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
235 
236   setOperationAction(ISD::SETCC, MVT::i1, Promote);
237   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
238   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
239   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
240 
241   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
242   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
243   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
244   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
245   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
246   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
247   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
248   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
249 
250   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
251   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
252   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
253   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
254   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
255   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
256   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
257   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
258 
259   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
260   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
261   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
262   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
263   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
264   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
265 
266   setOperationAction(ISD::UADDO, MVT::i32, Legal);
267   setOperationAction(ISD::USUBO, MVT::i32, Legal);
268 
269   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
270   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
271 
272   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
273   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
274   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
275 
276 #if 0
277   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
278   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
279 #endif
280 
281   // We only support LOAD/STORE and vector manipulation ops for vectors
282   // with > 4 elements.
283   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
284                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
285                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
286                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
287     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
288       switch (Op) {
289       case ISD::LOAD:
290       case ISD::STORE:
291       case ISD::BUILD_VECTOR:
292       case ISD::BITCAST:
293       case ISD::EXTRACT_VECTOR_ELT:
294       case ISD::INSERT_VECTOR_ELT:
295       case ISD::INSERT_SUBVECTOR:
296       case ISD::EXTRACT_SUBVECTOR:
297       case ISD::SCALAR_TO_VECTOR:
298         break;
299       case ISD::CONCAT_VECTORS:
300         setOperationAction(Op, VT, Custom);
301         break;
302       default:
303         setOperationAction(Op, VT, Expand);
304         break;
305       }
306     }
307   }
308 
309   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
310 
311   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
312   // is expanded to avoid having two separate loops in case the index is a VGPR.
313 
314   // Most operations are naturally 32-bit vector operations. We only support
315   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
316   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
317     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
318     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
319 
320     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
321     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
322 
323     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
324     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
325 
326     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
327     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
328   }
329 
330   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
331     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
332     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
333 
334     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
335     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
336 
337     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
338     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
339 
340     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
341     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
342   }
343 
344   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
345     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
346     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
347 
348     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
349     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
350 
351     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
352     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
353 
354     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
355     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
356   }
357 
358   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
359     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
360     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
361 
362     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
363     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
364 
365     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
366     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
367 
368     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
369     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
370   }
371 
372   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
373   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
374   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
375   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
376 
377   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
378   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
379 
380   // Avoid stack access for these.
381   // TODO: Generalize to more vector types.
382   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
383   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
384   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
385   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
386 
387   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
388   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
389   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
390   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
391   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
392 
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
396 
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
399   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
401 
402   // Deal with vec3 vector operations when widened to vec4.
403   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
404   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
407 
408   // Deal with vec5 vector operations when widened to vec8.
409   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
413 
414   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
415   // and output demarshalling
416   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
417   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
418 
419   // We can't return success/failure, only the old value,
420   // let LLVM add the comparison
421   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
422   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
423 
424   if (Subtarget->hasFlatAddressSpace()) {
425     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
426     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
427   }
428 
429   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
430 
431   // FIXME: This should be narrowed to i32, but that only happens if i64 is
432   // illegal.
433   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
434   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
435   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
436 
437   // On SI this is s_memtime and s_memrealtime on VI.
438   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
439   setOperationAction(ISD::TRAP, MVT::Other, Custom);
440   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
441 
442   if (Subtarget->has16BitInsts()) {
443     setOperationAction(ISD::FPOW, MVT::f16, Promote);
444     setOperationAction(ISD::FLOG, MVT::f16, Custom);
445     setOperationAction(ISD::FEXP, MVT::f16, Custom);
446     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
447   }
448 
449   // v_mad_f32 does not support denormals. We report it as unconditionally
450   // legal, and the context where it is formed will disallow it when fp32
451   // denormals are enabled.
452   setOperationAction(ISD::FMAD, MVT::f32, Legal);
453 
454   if (!Subtarget->hasBFI()) {
455     // fcopysign can be done in a single instruction with BFI.
456     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
457     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
458   }
459 
460   if (!Subtarget->hasBCNT(32))
461     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
462 
463   if (!Subtarget->hasBCNT(64))
464     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
465 
466   if (Subtarget->hasFFBH())
467     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
468 
469   if (Subtarget->hasFFBL())
470     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
471 
472   // We only really have 32-bit BFE instructions (and 16-bit on VI).
473   //
474   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
475   // effort to match them now. We want this to be false for i64 cases when the
476   // extraction isn't restricted to the upper or lower half. Ideally we would
477   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
478   // span the midpoint are probably relatively rare, so don't worry about them
479   // for now.
480   if (Subtarget->hasBFE())
481     setHasExtractBitsInsn(true);
482 
483   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
484   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
485   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
486   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
487 
488 
489   // These are really only legal for ieee_mode functions. We should be avoiding
490   // them for functions that don't have ieee_mode enabled, so just say they are
491   // legal.
492   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
493   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
494   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
495   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
496 
497 
498   if (Subtarget->haveRoundOpsF64()) {
499     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
500     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
501     setOperationAction(ISD::FRINT, MVT::f64, Legal);
502   } else {
503     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
504     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
505     setOperationAction(ISD::FRINT, MVT::f64, Custom);
506     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
507   }
508 
509   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
510 
511   setOperationAction(ISD::FSIN, MVT::f32, Custom);
512   setOperationAction(ISD::FCOS, MVT::f32, Custom);
513   setOperationAction(ISD::FDIV, MVT::f32, Custom);
514   setOperationAction(ISD::FDIV, MVT::f64, Custom);
515 
516   if (Subtarget->has16BitInsts()) {
517     setOperationAction(ISD::Constant, MVT::i16, Legal);
518 
519     setOperationAction(ISD::SMIN, MVT::i16, Legal);
520     setOperationAction(ISD::SMAX, MVT::i16, Legal);
521 
522     setOperationAction(ISD::UMIN, MVT::i16, Legal);
523     setOperationAction(ISD::UMAX, MVT::i16, Legal);
524 
525     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
526     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
527 
528     setOperationAction(ISD::ROTR, MVT::i16, Promote);
529     setOperationAction(ISD::ROTL, MVT::i16, Promote);
530 
531     setOperationAction(ISD::SDIV, MVT::i16, Promote);
532     setOperationAction(ISD::UDIV, MVT::i16, Promote);
533     setOperationAction(ISD::SREM, MVT::i16, Promote);
534     setOperationAction(ISD::UREM, MVT::i16, Promote);
535 
536     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
537 
538     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
539     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
540     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
541     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
542     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
543 
544     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
545 
546     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
547 
548     setOperationAction(ISD::LOAD, MVT::i16, Custom);
549 
550     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
551 
552     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
553     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
554     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
555     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
556 
557     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
558     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
559 
560     // F16 - Constant Actions.
561     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
562 
563     // F16 - Load/Store Actions.
564     setOperationAction(ISD::LOAD, MVT::f16, Promote);
565     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
566     setOperationAction(ISD::STORE, MVT::f16, Promote);
567     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
568 
569     // F16 - VOP1 Actions.
570     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
571     setOperationAction(ISD::FCOS, MVT::f16, Custom);
572     setOperationAction(ISD::FSIN, MVT::f16, Custom);
573 
574     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
575     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
576 
577     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
578     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
579     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
580     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
581     setOperationAction(ISD::FROUND, MVT::f16, Custom);
582 
583     // F16 - VOP2 Actions.
584     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
585     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
586 
587     setOperationAction(ISD::FDIV, MVT::f16, Custom);
588 
589     // F16 - VOP3 Actions.
590     setOperationAction(ISD::FMA, MVT::f16, Legal);
591     if (STI.hasMadF16())
592       setOperationAction(ISD::FMAD, MVT::f16, Legal);
593 
594     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
595       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
596         switch (Op) {
597         case ISD::LOAD:
598         case ISD::STORE:
599         case ISD::BUILD_VECTOR:
600         case ISD::BITCAST:
601         case ISD::EXTRACT_VECTOR_ELT:
602         case ISD::INSERT_VECTOR_ELT:
603         case ISD::INSERT_SUBVECTOR:
604         case ISD::EXTRACT_SUBVECTOR:
605         case ISD::SCALAR_TO_VECTOR:
606           break;
607         case ISD::CONCAT_VECTORS:
608           setOperationAction(Op, VT, Custom);
609           break;
610         default:
611           setOperationAction(Op, VT, Expand);
612           break;
613         }
614       }
615     }
616 
617     // v_perm_b32 can handle either of these.
618     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
619     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
620     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
621 
622     // XXX - Do these do anything? Vector constants turn into build_vector.
623     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
624     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
625 
626     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
627     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
628 
629     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
630     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
631     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
632     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
633 
634     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
635     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
636     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
637     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
638 
639     setOperationAction(ISD::AND, MVT::v2i16, Promote);
640     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
641     setOperationAction(ISD::OR, MVT::v2i16, Promote);
642     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
643     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
644     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
645 
646     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
647     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
648     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
649     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
650 
651     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
652     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
653     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
655 
656     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
657     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
658     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
659     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
660 
661     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
662     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
663     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
664 
665     if (!Subtarget->hasVOP3PInsts()) {
666       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
667       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
668     }
669 
670     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
671     // This isn't really legal, but this avoids the legalizer unrolling it (and
672     // allows matching fneg (fabs x) patterns)
673     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
674 
675     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
676     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
677     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
678     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
679 
680     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
681     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
682 
683     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
684     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
685   }
686 
687   if (Subtarget->hasVOP3PInsts()) {
688     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
689     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
690     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
691     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
692     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
693     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
694     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
695     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
696     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
697     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
698 
699     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
700     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
701     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
702 
703     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
704     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
705 
706     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
707 
708     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
709     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
710 
711     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
712     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
713 
714     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
715     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
716     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
717     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
718     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
719     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
720 
721     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
722     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
723     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
724     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
725 
726     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
727     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
728     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
729 
730     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
731     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
732 
733     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
734     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
735     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
736 
737     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
738     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
739     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
740   }
741 
742   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
743   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
744 
745   if (Subtarget->has16BitInsts()) {
746     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
747     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
748     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
749     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
750   } else {
751     // Legalization hack.
752     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
753     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
754 
755     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
756     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
757   }
758 
759   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
760     setOperationAction(ISD::SELECT, VT, Custom);
761   }
762 
763   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
764   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
765   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
766   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
767   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
768   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
769   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
770 
771   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
772   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
773   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
774   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
775   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
776   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
777   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
778   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
779   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
780 
781   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
782   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
783   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
784   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
785   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
786   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
787   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
788   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
789 
790   setTargetDAGCombine(ISD::ADD);
791   setTargetDAGCombine(ISD::ADDCARRY);
792   setTargetDAGCombine(ISD::SUB);
793   setTargetDAGCombine(ISD::SUBCARRY);
794   setTargetDAGCombine(ISD::FADD);
795   setTargetDAGCombine(ISD::FSUB);
796   setTargetDAGCombine(ISD::FMINNUM);
797   setTargetDAGCombine(ISD::FMAXNUM);
798   setTargetDAGCombine(ISD::FMINNUM_IEEE);
799   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
800   setTargetDAGCombine(ISD::FMA);
801   setTargetDAGCombine(ISD::SMIN);
802   setTargetDAGCombine(ISD::SMAX);
803   setTargetDAGCombine(ISD::UMIN);
804   setTargetDAGCombine(ISD::UMAX);
805   setTargetDAGCombine(ISD::SETCC);
806   setTargetDAGCombine(ISD::AND);
807   setTargetDAGCombine(ISD::OR);
808   setTargetDAGCombine(ISD::XOR);
809   setTargetDAGCombine(ISD::SINT_TO_FP);
810   setTargetDAGCombine(ISD::UINT_TO_FP);
811   setTargetDAGCombine(ISD::FCANONICALIZE);
812   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
813   setTargetDAGCombine(ISD::ZERO_EXTEND);
814   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
815   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
816   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
817 
818   // All memory operations. Some folding on the pointer operand is done to help
819   // matching the constant offsets in the addressing modes.
820   setTargetDAGCombine(ISD::LOAD);
821   setTargetDAGCombine(ISD::STORE);
822   setTargetDAGCombine(ISD::ATOMIC_LOAD);
823   setTargetDAGCombine(ISD::ATOMIC_STORE);
824   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
825   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
826   setTargetDAGCombine(ISD::ATOMIC_SWAP);
827   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
828   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
829   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
830   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
831   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
832   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
833   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
834   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
835   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
836   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
838 
839   setSchedulingPreference(Sched::RegPressure);
840 }
841 
842 const GCNSubtarget *SITargetLowering::getSubtarget() const {
843   return Subtarget;
844 }
845 
846 //===----------------------------------------------------------------------===//
847 // TargetLowering queries
848 //===----------------------------------------------------------------------===//
849 
850 // v_mad_mix* support a conversion from f16 to f32.
851 //
852 // There is only one special case when denormals are enabled we don't currently,
853 // where this is OK to use.
854 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
855                                        EVT DestVT, EVT SrcVT) const {
856   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
857           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
858     DestVT.getScalarType() == MVT::f32 &&
859     SrcVT.getScalarType() == MVT::f16 &&
860     // TODO: This probably only requires no input flushing?
861     !hasFP32Denormals(DAG.getMachineFunction());
862 }
863 
864 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
865   // SI has some legal vector types, but no legal vector operations. Say no
866   // shuffles are legal in order to prefer scalarizing some vector operations.
867   return false;
868 }
869 
870 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
871                                                     CallingConv::ID CC,
872                                                     EVT VT) const {
873   if (CC == CallingConv::AMDGPU_KERNEL)
874     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
875 
876   if (VT.isVector()) {
877     EVT ScalarVT = VT.getScalarType();
878     unsigned Size = ScalarVT.getSizeInBits();
879     if (Size == 32)
880       return ScalarVT.getSimpleVT();
881 
882     if (Size > 32)
883       return MVT::i32;
884 
885     if (Size == 16 && Subtarget->has16BitInsts())
886       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
887   } else if (VT.getSizeInBits() > 32)
888     return MVT::i32;
889 
890   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
891 }
892 
893 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
894                                                          CallingConv::ID CC,
895                                                          EVT VT) const {
896   if (CC == CallingConv::AMDGPU_KERNEL)
897     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
898 
899   if (VT.isVector()) {
900     unsigned NumElts = VT.getVectorNumElements();
901     EVT ScalarVT = VT.getScalarType();
902     unsigned Size = ScalarVT.getSizeInBits();
903 
904     if (Size == 32)
905       return NumElts;
906 
907     if (Size > 32)
908       return NumElts * ((Size + 31) / 32);
909 
910     if (Size == 16 && Subtarget->has16BitInsts())
911       return (NumElts + 1) / 2;
912   } else if (VT.getSizeInBits() > 32)
913     return (VT.getSizeInBits() + 31) / 32;
914 
915   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
916 }
917 
918 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
919   LLVMContext &Context, CallingConv::ID CC,
920   EVT VT, EVT &IntermediateVT,
921   unsigned &NumIntermediates, MVT &RegisterVT) const {
922   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
923     unsigned NumElts = VT.getVectorNumElements();
924     EVT ScalarVT = VT.getScalarType();
925     unsigned Size = ScalarVT.getSizeInBits();
926     if (Size == 32) {
927       RegisterVT = ScalarVT.getSimpleVT();
928       IntermediateVT = RegisterVT;
929       NumIntermediates = NumElts;
930       return NumIntermediates;
931     }
932 
933     if (Size > 32) {
934       RegisterVT = MVT::i32;
935       IntermediateVT = RegisterVT;
936       NumIntermediates = NumElts * ((Size + 31) / 32);
937       return NumIntermediates;
938     }
939 
940     // FIXME: We should fix the ABI to be the same on targets without 16-bit
941     // support, but unless we can properly handle 3-vectors, it will be still be
942     // inconsistent.
943     if (Size == 16 && Subtarget->has16BitInsts()) {
944       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
945       IntermediateVT = RegisterVT;
946       NumIntermediates = (NumElts + 1) / 2;
947       return NumIntermediates;
948     }
949   }
950 
951   return TargetLowering::getVectorTypeBreakdownForCallingConv(
952     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
953 }
954 
955 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
956   assert(DMaskLanes != 0);
957 
958   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
959     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
960     return EVT::getVectorVT(Ty->getContext(),
961                             EVT::getEVT(VT->getElementType()),
962                             NumElts);
963   }
964 
965   return EVT::getEVT(Ty);
966 }
967 
968 // Peek through TFE struct returns to only use the data size.
969 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
970   auto *ST = dyn_cast<StructType>(Ty);
971   if (!ST)
972     return memVTFromImageData(Ty, DMaskLanes);
973 
974   // Some intrinsics return an aggregate type - special case to work out the
975   // correct memVT.
976   //
977   // Only limited forms of aggregate type currently expected.
978   if (ST->getNumContainedTypes() != 2 ||
979       !ST->getContainedType(1)->isIntegerTy(32))
980     return EVT();
981   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
982 }
983 
984 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
985                                           const CallInst &CI,
986                                           MachineFunction &MF,
987                                           unsigned IntrID) const {
988   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
989           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
990     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
991                                                   (Intrinsic::ID)IntrID);
992     if (Attr.hasFnAttribute(Attribute::ReadNone))
993       return false;
994 
995     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
996 
997     if (RsrcIntr->IsImage) {
998       Info.ptrVal = MFI->getImagePSV(
999         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1000         CI.getArgOperand(RsrcIntr->RsrcArg));
1001       Info.align.reset();
1002     } else {
1003       Info.ptrVal = MFI->getBufferPSV(
1004         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1005         CI.getArgOperand(RsrcIntr->RsrcArg));
1006     }
1007 
1008     Info.flags = MachineMemOperand::MODereferenceable;
1009     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1010       unsigned DMaskLanes = 4;
1011 
1012       if (RsrcIntr->IsImage) {
1013         const AMDGPU::ImageDimIntrinsicInfo *Intr
1014           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1015         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1016           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1017 
1018         if (!BaseOpcode->Gather4) {
1019           // If this isn't a gather, we may have excess loaded elements in the
1020           // IR type. Check the dmask for the real number of elements loaded.
1021           unsigned DMask
1022             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1023           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1024         }
1025 
1026         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1027       } else
1028         Info.memVT = EVT::getEVT(CI.getType());
1029 
1030       // FIXME: What does alignment mean for an image?
1031       Info.opc = ISD::INTRINSIC_W_CHAIN;
1032       Info.flags |= MachineMemOperand::MOLoad;
1033     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1034       Info.opc = ISD::INTRINSIC_VOID;
1035 
1036       Type *DataTy = CI.getArgOperand(0)->getType();
1037       if (RsrcIntr->IsImage) {
1038         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1039         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1040         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1041       } else
1042         Info.memVT = EVT::getEVT(DataTy);
1043 
1044       Info.flags |= MachineMemOperand::MOStore;
1045     } else {
1046       // Atomic
1047       Info.opc = ISD::INTRINSIC_W_CHAIN;
1048       Info.memVT = MVT::getVT(CI.getType());
1049       Info.flags = MachineMemOperand::MOLoad |
1050                    MachineMemOperand::MOStore |
1051                    MachineMemOperand::MODereferenceable;
1052 
1053       // XXX - Should this be volatile without known ordering?
1054       Info.flags |= MachineMemOperand::MOVolatile;
1055     }
1056     return true;
1057   }
1058 
1059   switch (IntrID) {
1060   case Intrinsic::amdgcn_atomic_inc:
1061   case Intrinsic::amdgcn_atomic_dec:
1062   case Intrinsic::amdgcn_ds_ordered_add:
1063   case Intrinsic::amdgcn_ds_ordered_swap:
1064   case Intrinsic::amdgcn_ds_fadd:
1065   case Intrinsic::amdgcn_ds_fmin:
1066   case Intrinsic::amdgcn_ds_fmax: {
1067     Info.opc = ISD::INTRINSIC_W_CHAIN;
1068     Info.memVT = MVT::getVT(CI.getType());
1069     Info.ptrVal = CI.getOperand(0);
1070     Info.align.reset();
1071     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1072 
1073     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1074     if (!Vol->isZero())
1075       Info.flags |= MachineMemOperand::MOVolatile;
1076 
1077     return true;
1078   }
1079   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1080     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1081 
1082     Info.opc = ISD::INTRINSIC_VOID;
1083     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1084     Info.ptrVal = MFI->getBufferPSV(
1085       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1086       CI.getArgOperand(1));
1087     Info.align.reset();
1088     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1089 
1090     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1091     if (!Vol || !Vol->isZero())
1092       Info.flags |= MachineMemOperand::MOVolatile;
1093 
1094     return true;
1095   }
1096   case Intrinsic::amdgcn_global_atomic_fadd: {
1097     Info.opc = ISD::INTRINSIC_VOID;
1098     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1099                             ->getPointerElementType());
1100     Info.ptrVal = CI.getOperand(0);
1101     Info.align.reset();
1102     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1103 
1104     return true;
1105   }
1106   case Intrinsic::amdgcn_ds_append:
1107   case Intrinsic::amdgcn_ds_consume: {
1108     Info.opc = ISD::INTRINSIC_W_CHAIN;
1109     Info.memVT = MVT::getVT(CI.getType());
1110     Info.ptrVal = CI.getOperand(0);
1111     Info.align.reset();
1112     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1113 
1114     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1115     if (!Vol->isZero())
1116       Info.flags |= MachineMemOperand::MOVolatile;
1117 
1118     return true;
1119   }
1120   case Intrinsic::amdgcn_ds_gws_init:
1121   case Intrinsic::amdgcn_ds_gws_barrier:
1122   case Intrinsic::amdgcn_ds_gws_sema_v:
1123   case Intrinsic::amdgcn_ds_gws_sema_br:
1124   case Intrinsic::amdgcn_ds_gws_sema_p:
1125   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1126     Info.opc = ISD::INTRINSIC_VOID;
1127 
1128     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1129     Info.ptrVal =
1130         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1131 
1132     // This is an abstract access, but we need to specify a type and size.
1133     Info.memVT = MVT::i32;
1134     Info.size = 4;
1135     Info.align = Align(4);
1136 
1137     Info.flags = MachineMemOperand::MOStore;
1138     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1139       Info.flags = MachineMemOperand::MOLoad;
1140     return true;
1141   }
1142   default:
1143     return false;
1144   }
1145 }
1146 
1147 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1148                                             SmallVectorImpl<Value*> &Ops,
1149                                             Type *&AccessTy) const {
1150   switch (II->getIntrinsicID()) {
1151   case Intrinsic::amdgcn_atomic_inc:
1152   case Intrinsic::amdgcn_atomic_dec:
1153   case Intrinsic::amdgcn_ds_ordered_add:
1154   case Intrinsic::amdgcn_ds_ordered_swap:
1155   case Intrinsic::amdgcn_ds_fadd:
1156   case Intrinsic::amdgcn_ds_fmin:
1157   case Intrinsic::amdgcn_ds_fmax: {
1158     Value *Ptr = II->getArgOperand(0);
1159     AccessTy = II->getType();
1160     Ops.push_back(Ptr);
1161     return true;
1162   }
1163   default:
1164     return false;
1165   }
1166 }
1167 
1168 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1169   if (!Subtarget->hasFlatInstOffsets()) {
1170     // Flat instructions do not have offsets, and only have the register
1171     // address.
1172     return AM.BaseOffs == 0 && AM.Scale == 0;
1173   }
1174 
1175   return AM.Scale == 0 &&
1176          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1177                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1178                                   /*Signed=*/false));
1179 }
1180 
1181 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1182   if (Subtarget->hasFlatGlobalInsts())
1183     return AM.Scale == 0 &&
1184            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1185                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1186                                     /*Signed=*/true));
1187 
1188   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1189       // Assume the we will use FLAT for all global memory accesses
1190       // on VI.
1191       // FIXME: This assumption is currently wrong.  On VI we still use
1192       // MUBUF instructions for the r + i addressing mode.  As currently
1193       // implemented, the MUBUF instructions only work on buffer < 4GB.
1194       // It may be possible to support > 4GB buffers with MUBUF instructions,
1195       // by setting the stride value in the resource descriptor which would
1196       // increase the size limit to (stride * 4GB).  However, this is risky,
1197       // because it has never been validated.
1198     return isLegalFlatAddressingMode(AM);
1199   }
1200 
1201   return isLegalMUBUFAddressingMode(AM);
1202 }
1203 
1204 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1205   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1206   // additionally can do r + r + i with addr64. 32-bit has more addressing
1207   // mode options. Depending on the resource constant, it can also do
1208   // (i64 r0) + (i32 r1) * (i14 i).
1209   //
1210   // Private arrays end up using a scratch buffer most of the time, so also
1211   // assume those use MUBUF instructions. Scratch loads / stores are currently
1212   // implemented as mubuf instructions with offen bit set, so slightly
1213   // different than the normal addr64.
1214   if (!isUInt<12>(AM.BaseOffs))
1215     return false;
1216 
1217   // FIXME: Since we can split immediate into soffset and immediate offset,
1218   // would it make sense to allow any immediate?
1219 
1220   switch (AM.Scale) {
1221   case 0: // r + i or just i, depending on HasBaseReg.
1222     return true;
1223   case 1:
1224     return true; // We have r + r or r + i.
1225   case 2:
1226     if (AM.HasBaseReg) {
1227       // Reject 2 * r + r.
1228       return false;
1229     }
1230 
1231     // Allow 2 * r as r + r
1232     // Or  2 * r + i is allowed as r + r + i.
1233     return true;
1234   default: // Don't allow n * r
1235     return false;
1236   }
1237 }
1238 
1239 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1240                                              const AddrMode &AM, Type *Ty,
1241                                              unsigned AS, Instruction *I) const {
1242   // No global is ever allowed as a base.
1243   if (AM.BaseGV)
1244     return false;
1245 
1246   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1247     return isLegalGlobalAddressingMode(AM);
1248 
1249   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1250       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1251       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1252     // If the offset isn't a multiple of 4, it probably isn't going to be
1253     // correctly aligned.
1254     // FIXME: Can we get the real alignment here?
1255     if (AM.BaseOffs % 4 != 0)
1256       return isLegalMUBUFAddressingMode(AM);
1257 
1258     // There are no SMRD extloads, so if we have to do a small type access we
1259     // will use a MUBUF load.
1260     // FIXME?: We also need to do this if unaligned, but we don't know the
1261     // alignment here.
1262     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1263       return isLegalGlobalAddressingMode(AM);
1264 
1265     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1266       // SMRD instructions have an 8-bit, dword offset on SI.
1267       if (!isUInt<8>(AM.BaseOffs / 4))
1268         return false;
1269     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1270       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1271       // in 8-bits, it can use a smaller encoding.
1272       if (!isUInt<32>(AM.BaseOffs / 4))
1273         return false;
1274     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1275       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1276       if (!isUInt<20>(AM.BaseOffs))
1277         return false;
1278     } else
1279       llvm_unreachable("unhandled generation");
1280 
1281     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1282       return true;
1283 
1284     if (AM.Scale == 1 && AM.HasBaseReg)
1285       return true;
1286 
1287     return false;
1288 
1289   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1290     return isLegalMUBUFAddressingMode(AM);
1291   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1292              AS == AMDGPUAS::REGION_ADDRESS) {
1293     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1294     // field.
1295     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1296     // an 8-bit dword offset but we don't know the alignment here.
1297     if (!isUInt<16>(AM.BaseOffs))
1298       return false;
1299 
1300     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1301       return true;
1302 
1303     if (AM.Scale == 1 && AM.HasBaseReg)
1304       return true;
1305 
1306     return false;
1307   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1308              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1309     // For an unknown address space, this usually means that this is for some
1310     // reason being used for pure arithmetic, and not based on some addressing
1311     // computation. We don't have instructions that compute pointers with any
1312     // addressing modes, so treat them as having no offset like flat
1313     // instructions.
1314     return isLegalFlatAddressingMode(AM);
1315   }
1316 
1317   // Assume a user alias of global for unknown address spaces.
1318   return isLegalGlobalAddressingMode(AM);
1319 }
1320 
1321 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1322                                         const SelectionDAG &DAG) const {
1323   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1324     return (MemVT.getSizeInBits() <= 4 * 32);
1325   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1326     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1327     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1328   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1329     return (MemVT.getSizeInBits() <= 2 * 32);
1330   }
1331   return true;
1332 }
1333 
1334 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1335     unsigned Size, unsigned AddrSpace, unsigned Align,
1336     MachineMemOperand::Flags Flags, bool *IsFast) const {
1337   if (IsFast)
1338     *IsFast = false;
1339 
1340   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1341       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1342     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1343     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1344     // with adjacent offsets.
1345     bool AlignedBy4 = (Align % 4 == 0);
1346     if (IsFast)
1347       *IsFast = AlignedBy4;
1348 
1349     return AlignedBy4;
1350   }
1351 
1352   // FIXME: We have to be conservative here and assume that flat operations
1353   // will access scratch.  If we had access to the IR function, then we
1354   // could determine if any private memory was used in the function.
1355   if (!Subtarget->hasUnalignedScratchAccess() &&
1356       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1357        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1358     bool AlignedBy4 = Align >= 4;
1359     if (IsFast)
1360       *IsFast = AlignedBy4;
1361 
1362     return AlignedBy4;
1363   }
1364 
1365   if (Subtarget->hasUnalignedBufferAccess()) {
1366     // If we have an uniform constant load, it still requires using a slow
1367     // buffer instruction if unaligned.
1368     if (IsFast) {
1369       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1370       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1371       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1372                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1373         Align >= 4 : Align != 2;
1374     }
1375 
1376     return true;
1377   }
1378 
1379   // Smaller than dword value must be aligned.
1380   if (Size < 32)
1381     return false;
1382 
1383   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1384   // byte-address are ignored, thus forcing Dword alignment.
1385   // This applies to private, global, and constant memory.
1386   if (IsFast)
1387     *IsFast = true;
1388 
1389   return Size >= 32 && Align >= 4;
1390 }
1391 
1392 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1393     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1394     bool *IsFast) const {
1395   if (IsFast)
1396     *IsFast = false;
1397 
1398   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1399   // which isn't a simple VT.
1400   // Until MVT is extended to handle this, simply check for the size and
1401   // rely on the condition below: allow accesses if the size is a multiple of 4.
1402   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1403                            VT.getStoreSize() > 16)) {
1404     return false;
1405   }
1406 
1407   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1408                                             Align, Flags, IsFast);
1409 }
1410 
1411 EVT SITargetLowering::getOptimalMemOpType(
1412     const MemOp &Op, const AttributeList &FuncAttributes) const {
1413   // FIXME: Should account for address space here.
1414 
1415   // The default fallback uses the private pointer size as a guess for a type to
1416   // use. Make sure we switch these to 64-bit accesses.
1417 
1418   if (Op.size() >= 16 &&
1419       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1420     return MVT::v4i32;
1421 
1422   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1423     return MVT::v2i32;
1424 
1425   // Use the default.
1426   return MVT::Other;
1427 }
1428 
1429 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1430                                            unsigned DestAS) const {
1431   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1432 }
1433 
1434 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1435   const MemSDNode *MemNode = cast<MemSDNode>(N);
1436   const Value *Ptr = MemNode->getMemOperand()->getValue();
1437   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1438   return I && I->getMetadata("amdgpu.noclobber");
1439 }
1440 
1441 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1442                                            unsigned DestAS) const {
1443   // Flat -> private/local is a simple truncate.
1444   // Flat -> global is no-op
1445   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1446     return true;
1447 
1448   return isNoopAddrSpaceCast(SrcAS, DestAS);
1449 }
1450 
1451 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1452   const MemSDNode *MemNode = cast<MemSDNode>(N);
1453 
1454   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1455 }
1456 
1457 TargetLoweringBase::LegalizeTypeAction
1458 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1459   int NumElts = VT.getVectorNumElements();
1460   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1461     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1462   return TargetLoweringBase::getPreferredVectorAction(VT);
1463 }
1464 
1465 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1466                                                          Type *Ty) const {
1467   // FIXME: Could be smarter if called for vector constants.
1468   return true;
1469 }
1470 
1471 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1472   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1473     switch (Op) {
1474     case ISD::LOAD:
1475     case ISD::STORE:
1476 
1477     // These operations are done with 32-bit instructions anyway.
1478     case ISD::AND:
1479     case ISD::OR:
1480     case ISD::XOR:
1481     case ISD::SELECT:
1482       // TODO: Extensions?
1483       return true;
1484     default:
1485       return false;
1486     }
1487   }
1488 
1489   // SimplifySetCC uses this function to determine whether or not it should
1490   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1491   if (VT == MVT::i1 && Op == ISD::SETCC)
1492     return false;
1493 
1494   return TargetLowering::isTypeDesirableForOp(Op, VT);
1495 }
1496 
1497 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1498                                                    const SDLoc &SL,
1499                                                    SDValue Chain,
1500                                                    uint64_t Offset) const {
1501   const DataLayout &DL = DAG.getDataLayout();
1502   MachineFunction &MF = DAG.getMachineFunction();
1503   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1504 
1505   const ArgDescriptor *InputPtrReg;
1506   const TargetRegisterClass *RC;
1507 
1508   std::tie(InputPtrReg, RC)
1509     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1510 
1511   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1512   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1513   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1514     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1515 
1516   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1517 }
1518 
1519 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1520                                             const SDLoc &SL) const {
1521   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1522                                                FIRST_IMPLICIT);
1523   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1524 }
1525 
1526 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1527                                          const SDLoc &SL, SDValue Val,
1528                                          bool Signed,
1529                                          const ISD::InputArg *Arg) const {
1530   // First, if it is a widened vector, narrow it.
1531   if (VT.isVector() &&
1532       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1533     EVT NarrowedVT =
1534         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1535                          VT.getVectorNumElements());
1536     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1537                       DAG.getConstant(0, SL, MVT::i32));
1538   }
1539 
1540   // Then convert the vector elements or scalar value.
1541   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1542       VT.bitsLT(MemVT)) {
1543     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1544     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1545   }
1546 
1547   if (MemVT.isFloatingPoint())
1548     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1549   else if (Signed)
1550     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1551   else
1552     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1553 
1554   return Val;
1555 }
1556 
1557 SDValue SITargetLowering::lowerKernargMemParameter(
1558   SelectionDAG &DAG, EVT VT, EVT MemVT,
1559   const SDLoc &SL, SDValue Chain,
1560   uint64_t Offset, unsigned Align, bool Signed,
1561   const ISD::InputArg *Arg) const {
1562   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1563 
1564   // Try to avoid using an extload by loading earlier than the argument address,
1565   // and extracting the relevant bits. The load should hopefully be merged with
1566   // the previous argument.
1567   if (MemVT.getStoreSize() < 4 && Align < 4) {
1568     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1569     int64_t AlignDownOffset = alignDown(Offset, 4);
1570     int64_t OffsetDiff = Offset - AlignDownOffset;
1571 
1572     EVT IntVT = MemVT.changeTypeToInteger();
1573 
1574     // TODO: If we passed in the base kernel offset we could have a better
1575     // alignment than 4, but we don't really need it.
1576     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1577     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1578                                MachineMemOperand::MODereferenceable |
1579                                MachineMemOperand::MOInvariant);
1580 
1581     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1582     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1583 
1584     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1585     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1586     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1587 
1588 
1589     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1590   }
1591 
1592   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1593   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1594                              MachineMemOperand::MODereferenceable |
1595                              MachineMemOperand::MOInvariant);
1596 
1597   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1598   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1599 }
1600 
1601 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1602                                               const SDLoc &SL, SDValue Chain,
1603                                               const ISD::InputArg &Arg) const {
1604   MachineFunction &MF = DAG.getMachineFunction();
1605   MachineFrameInfo &MFI = MF.getFrameInfo();
1606 
1607   if (Arg.Flags.isByVal()) {
1608     unsigned Size = Arg.Flags.getByValSize();
1609     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1610     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1611   }
1612 
1613   unsigned ArgOffset = VA.getLocMemOffset();
1614   unsigned ArgSize = VA.getValVT().getStoreSize();
1615 
1616   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1617 
1618   // Create load nodes to retrieve arguments from the stack.
1619   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1620   SDValue ArgValue;
1621 
1622   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1623   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1624   MVT MemVT = VA.getValVT();
1625 
1626   switch (VA.getLocInfo()) {
1627   default:
1628     break;
1629   case CCValAssign::BCvt:
1630     MemVT = VA.getLocVT();
1631     break;
1632   case CCValAssign::SExt:
1633     ExtType = ISD::SEXTLOAD;
1634     break;
1635   case CCValAssign::ZExt:
1636     ExtType = ISD::ZEXTLOAD;
1637     break;
1638   case CCValAssign::AExt:
1639     ExtType = ISD::EXTLOAD;
1640     break;
1641   }
1642 
1643   ArgValue = DAG.getExtLoad(
1644     ExtType, SL, VA.getLocVT(), Chain, FIN,
1645     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1646     MemVT);
1647   return ArgValue;
1648 }
1649 
1650 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1651   const SIMachineFunctionInfo &MFI,
1652   EVT VT,
1653   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1654   const ArgDescriptor *Reg;
1655   const TargetRegisterClass *RC;
1656 
1657   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1658   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1659 }
1660 
1661 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1662                                    CallingConv::ID CallConv,
1663                                    ArrayRef<ISD::InputArg> Ins,
1664                                    BitVector &Skipped,
1665                                    FunctionType *FType,
1666                                    SIMachineFunctionInfo *Info) {
1667   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1668     const ISD::InputArg *Arg = &Ins[I];
1669 
1670     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1671            "vector type argument should have been split");
1672 
1673     // First check if it's a PS input addr.
1674     if (CallConv == CallingConv::AMDGPU_PS &&
1675         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1676       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1677 
1678       // Inconveniently only the first part of the split is marked as isSplit,
1679       // so skip to the end. We only want to increment PSInputNum once for the
1680       // entire split argument.
1681       if (Arg->Flags.isSplit()) {
1682         while (!Arg->Flags.isSplitEnd()) {
1683           assert((!Arg->VT.isVector() ||
1684                   Arg->VT.getScalarSizeInBits() == 16) &&
1685                  "unexpected vector split in ps argument type");
1686           if (!SkipArg)
1687             Splits.push_back(*Arg);
1688           Arg = &Ins[++I];
1689         }
1690       }
1691 
1692       if (SkipArg) {
1693         // We can safely skip PS inputs.
1694         Skipped.set(Arg->getOrigArgIndex());
1695         ++PSInputNum;
1696         continue;
1697       }
1698 
1699       Info->markPSInputAllocated(PSInputNum);
1700       if (Arg->Used)
1701         Info->markPSInputEnabled(PSInputNum);
1702 
1703       ++PSInputNum;
1704     }
1705 
1706     Splits.push_back(*Arg);
1707   }
1708 }
1709 
1710 // Allocate special inputs passed in VGPRs.
1711 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1712                                                       MachineFunction &MF,
1713                                                       const SIRegisterInfo &TRI,
1714                                                       SIMachineFunctionInfo &Info) const {
1715   const LLT S32 = LLT::scalar(32);
1716   MachineRegisterInfo &MRI = MF.getRegInfo();
1717 
1718   if (Info.hasWorkItemIDX()) {
1719     Register Reg = AMDGPU::VGPR0;
1720     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1721 
1722     CCInfo.AllocateReg(Reg);
1723     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1724   }
1725 
1726   if (Info.hasWorkItemIDY()) {
1727     Register Reg = AMDGPU::VGPR1;
1728     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1729 
1730     CCInfo.AllocateReg(Reg);
1731     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1732   }
1733 
1734   if (Info.hasWorkItemIDZ()) {
1735     Register Reg = AMDGPU::VGPR2;
1736     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1737 
1738     CCInfo.AllocateReg(Reg);
1739     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1740   }
1741 }
1742 
1743 // Try to allocate a VGPR at the end of the argument list, or if no argument
1744 // VGPRs are left allocating a stack slot.
1745 // If \p Mask is is given it indicates bitfield position in the register.
1746 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1747 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1748                                          ArgDescriptor Arg = ArgDescriptor()) {
1749   if (Arg.isSet())
1750     return ArgDescriptor::createArg(Arg, Mask);
1751 
1752   ArrayRef<MCPhysReg> ArgVGPRs
1753     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1754   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1755   if (RegIdx == ArgVGPRs.size()) {
1756     // Spill to stack required.
1757     int64_t Offset = CCInfo.AllocateStack(4, 4);
1758 
1759     return ArgDescriptor::createStack(Offset, Mask);
1760   }
1761 
1762   unsigned Reg = ArgVGPRs[RegIdx];
1763   Reg = CCInfo.AllocateReg(Reg);
1764   assert(Reg != AMDGPU::NoRegister);
1765 
1766   MachineFunction &MF = CCInfo.getMachineFunction();
1767   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1768   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1769   return ArgDescriptor::createRegister(Reg, Mask);
1770 }
1771 
1772 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1773                                              const TargetRegisterClass *RC,
1774                                              unsigned NumArgRegs) {
1775   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1776   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1777   if (RegIdx == ArgSGPRs.size())
1778     report_fatal_error("ran out of SGPRs for arguments");
1779 
1780   unsigned Reg = ArgSGPRs[RegIdx];
1781   Reg = CCInfo.AllocateReg(Reg);
1782   assert(Reg != AMDGPU::NoRegister);
1783 
1784   MachineFunction &MF = CCInfo.getMachineFunction();
1785   MF.addLiveIn(Reg, RC);
1786   return ArgDescriptor::createRegister(Reg);
1787 }
1788 
1789 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1790   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1791 }
1792 
1793 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1794   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1795 }
1796 
1797 /// Allocate implicit function VGPR arguments at the end of allocated user
1798 /// arguments.
1799 void SITargetLowering::allocateSpecialInputVGPRs(
1800   CCState &CCInfo, MachineFunction &MF,
1801   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1802   const unsigned Mask = 0x3ff;
1803   ArgDescriptor Arg;
1804 
1805   if (Info.hasWorkItemIDX()) {
1806     Arg = allocateVGPR32Input(CCInfo, Mask);
1807     Info.setWorkItemIDX(Arg);
1808   }
1809 
1810   if (Info.hasWorkItemIDY()) {
1811     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1812     Info.setWorkItemIDY(Arg);
1813   }
1814 
1815   if (Info.hasWorkItemIDZ())
1816     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1817 }
1818 
1819 /// Allocate implicit function VGPR arguments in fixed registers.
1820 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1821   CCState &CCInfo, MachineFunction &MF,
1822   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1823   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1824   if (!Reg)
1825     report_fatal_error("failed to allocated VGPR for implicit arguments");
1826 
1827   const unsigned Mask = 0x3ff;
1828   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1829   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1830   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1831 }
1832 
1833 void SITargetLowering::allocateSpecialInputSGPRs(
1834   CCState &CCInfo,
1835   MachineFunction &MF,
1836   const SIRegisterInfo &TRI,
1837   SIMachineFunctionInfo &Info) const {
1838   auto &ArgInfo = Info.getArgInfo();
1839 
1840   // TODO: Unify handling with private memory pointers.
1841 
1842   if (Info.hasDispatchPtr())
1843     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1844 
1845   if (Info.hasQueuePtr())
1846     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1847 
1848   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1849   // constant offset from the kernarg segment.
1850   if (Info.hasImplicitArgPtr())
1851     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1852 
1853   if (Info.hasDispatchID())
1854     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1855 
1856   // flat_scratch_init is not applicable for non-kernel functions.
1857 
1858   if (Info.hasWorkGroupIDX())
1859     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1860 
1861   if (Info.hasWorkGroupIDY())
1862     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1863 
1864   if (Info.hasWorkGroupIDZ())
1865     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1866 }
1867 
1868 // Allocate special inputs passed in user SGPRs.
1869 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1870                                             MachineFunction &MF,
1871                                             const SIRegisterInfo &TRI,
1872                                             SIMachineFunctionInfo &Info) const {
1873   if (Info.hasImplicitBufferPtr()) {
1874     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1875     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1876     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1877   }
1878 
1879   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1880   if (Info.hasPrivateSegmentBuffer()) {
1881     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1882     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1883     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1884   }
1885 
1886   if (Info.hasDispatchPtr()) {
1887     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1888     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1889     CCInfo.AllocateReg(DispatchPtrReg);
1890   }
1891 
1892   if (Info.hasQueuePtr()) {
1893     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1894     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1895     CCInfo.AllocateReg(QueuePtrReg);
1896   }
1897 
1898   if (Info.hasKernargSegmentPtr()) {
1899     MachineRegisterInfo &MRI = MF.getRegInfo();
1900     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1901     CCInfo.AllocateReg(InputPtrReg);
1902 
1903     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1904     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1905   }
1906 
1907   if (Info.hasDispatchID()) {
1908     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1909     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1910     CCInfo.AllocateReg(DispatchIDReg);
1911   }
1912 
1913   if (Info.hasFlatScratchInit()) {
1914     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1915     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1916     CCInfo.AllocateReg(FlatScratchInitReg);
1917   }
1918 
1919   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1920   // these from the dispatch pointer.
1921 }
1922 
1923 // Allocate special input registers that are initialized per-wave.
1924 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1925                                            MachineFunction &MF,
1926                                            SIMachineFunctionInfo &Info,
1927                                            CallingConv::ID CallConv,
1928                                            bool IsShader) const {
1929   if (Info.hasWorkGroupIDX()) {
1930     unsigned Reg = Info.addWorkGroupIDX();
1931     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1932     CCInfo.AllocateReg(Reg);
1933   }
1934 
1935   if (Info.hasWorkGroupIDY()) {
1936     unsigned Reg = Info.addWorkGroupIDY();
1937     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1938     CCInfo.AllocateReg(Reg);
1939   }
1940 
1941   if (Info.hasWorkGroupIDZ()) {
1942     unsigned Reg = Info.addWorkGroupIDZ();
1943     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1944     CCInfo.AllocateReg(Reg);
1945   }
1946 
1947   if (Info.hasWorkGroupInfo()) {
1948     unsigned Reg = Info.addWorkGroupInfo();
1949     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1950     CCInfo.AllocateReg(Reg);
1951   }
1952 
1953   if (Info.hasPrivateSegmentWaveByteOffset()) {
1954     // Scratch wave offset passed in system SGPR.
1955     unsigned PrivateSegmentWaveByteOffsetReg;
1956 
1957     if (IsShader) {
1958       PrivateSegmentWaveByteOffsetReg =
1959         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1960 
1961       // This is true if the scratch wave byte offset doesn't have a fixed
1962       // location.
1963       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1964         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1965         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1966       }
1967     } else
1968       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1969 
1970     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1971     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1972   }
1973 }
1974 
1975 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1976                                      MachineFunction &MF,
1977                                      const SIRegisterInfo &TRI,
1978                                      SIMachineFunctionInfo &Info) {
1979   // Now that we've figured out where the scratch register inputs are, see if
1980   // should reserve the arguments and use them directly.
1981   MachineFrameInfo &MFI = MF.getFrameInfo();
1982   bool HasStackObjects = MFI.hasStackObjects();
1983   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1984 
1985   // Record that we know we have non-spill stack objects so we don't need to
1986   // check all stack objects later.
1987   if (HasStackObjects)
1988     Info.setHasNonSpillStackObjects(true);
1989 
1990   // Everything live out of a block is spilled with fast regalloc, so it's
1991   // almost certain that spilling will be required.
1992   if (TM.getOptLevel() == CodeGenOpt::None)
1993     HasStackObjects = true;
1994 
1995   // For now assume stack access is needed in any callee functions, so we need
1996   // the scratch registers to pass in.
1997   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1998 
1999   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2000     // If we have stack objects, we unquestionably need the private buffer
2001     // resource. For the Code Object V2 ABI, this will be the first 4 user
2002     // SGPR inputs. We can reserve those and use them directly.
2003 
2004     Register PrivateSegmentBufferReg =
2005         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2006     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2007   } else {
2008     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2009     // We tentatively reserve the last registers (skipping the last registers
2010     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2011     // we'll replace these with the ones immediately after those which were
2012     // really allocated. In the prologue copies will be inserted from the
2013     // argument to these reserved registers.
2014 
2015     // Without HSA, relocations are used for the scratch pointer and the
2016     // buffer resource setup is always inserted in the prologue. Scratch wave
2017     // offset is still in an input SGPR.
2018     Info.setScratchRSrcReg(ReservedBufferReg);
2019   }
2020 
2021   MachineRegisterInfo &MRI = MF.getRegInfo();
2022 
2023   // For entry functions we have to set up the stack pointer if we use it,
2024   // whereas non-entry functions get this "for free". This means there is no
2025   // intrinsic advantage to using S32 over S34 in cases where we do not have
2026   // calls but do need a frame pointer (i.e. if we are requested to have one
2027   // because frame pointer elimination is disabled). To keep things simple we
2028   // only ever use S32 as the call ABI stack pointer, and so using it does not
2029   // imply we need a separate frame pointer.
2030   //
2031   // Try to use s32 as the SP, but move it if it would interfere with input
2032   // arguments. This won't work with calls though.
2033   //
2034   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2035   // registers.
2036   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2037     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2038   } else {
2039     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2040 
2041     if (MFI.hasCalls())
2042       report_fatal_error("call in graphics shader with too many input SGPRs");
2043 
2044     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2045       if (!MRI.isLiveIn(Reg)) {
2046         Info.setStackPtrOffsetReg(Reg);
2047         break;
2048       }
2049     }
2050 
2051     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2052       report_fatal_error("failed to find register for SP");
2053   }
2054 
2055   // hasFP should be accurate for entry functions even before the frame is
2056   // finalized, because it does not rely on the known stack size, only
2057   // properties like whether variable sized objects are present.
2058   if (ST.getFrameLowering()->hasFP(MF)) {
2059     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2060   }
2061 }
2062 
2063 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2064   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2065   return !Info->isEntryFunction();
2066 }
2067 
2068 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2069 
2070 }
2071 
2072 void SITargetLowering::insertCopiesSplitCSR(
2073   MachineBasicBlock *Entry,
2074   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2075   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2076 
2077   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2078   if (!IStart)
2079     return;
2080 
2081   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2082   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2083   MachineBasicBlock::iterator MBBI = Entry->begin();
2084   for (const MCPhysReg *I = IStart; *I; ++I) {
2085     const TargetRegisterClass *RC = nullptr;
2086     if (AMDGPU::SReg_64RegClass.contains(*I))
2087       RC = &AMDGPU::SGPR_64RegClass;
2088     else if (AMDGPU::SReg_32RegClass.contains(*I))
2089       RC = &AMDGPU::SGPR_32RegClass;
2090     else
2091       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2092 
2093     Register NewVR = MRI->createVirtualRegister(RC);
2094     // Create copy from CSR to a virtual register.
2095     Entry->addLiveIn(*I);
2096     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2097       .addReg(*I);
2098 
2099     // Insert the copy-back instructions right before the terminator.
2100     for (auto *Exit : Exits)
2101       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2102               TII->get(TargetOpcode::COPY), *I)
2103         .addReg(NewVR);
2104   }
2105 }
2106 
2107 SDValue SITargetLowering::LowerFormalArguments(
2108     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2109     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2110     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2111   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2112 
2113   MachineFunction &MF = DAG.getMachineFunction();
2114   const Function &Fn = MF.getFunction();
2115   FunctionType *FType = MF.getFunction().getFunctionType();
2116   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2117 
2118   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2119     DiagnosticInfoUnsupported NoGraphicsHSA(
2120         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2121     DAG.getContext()->diagnose(NoGraphicsHSA);
2122     return DAG.getEntryNode();
2123   }
2124 
2125   SmallVector<ISD::InputArg, 16> Splits;
2126   SmallVector<CCValAssign, 16> ArgLocs;
2127   BitVector Skipped(Ins.size());
2128   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2129                  *DAG.getContext());
2130 
2131   bool IsShader = AMDGPU::isShader(CallConv);
2132   bool IsKernel = AMDGPU::isKernel(CallConv);
2133   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2134 
2135   if (IsShader) {
2136     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2137 
2138     // At least one interpolation mode must be enabled or else the GPU will
2139     // hang.
2140     //
2141     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2142     // set PSInputAddr, the user wants to enable some bits after the compilation
2143     // based on run-time states. Since we can't know what the final PSInputEna
2144     // will look like, so we shouldn't do anything here and the user should take
2145     // responsibility for the correct programming.
2146     //
2147     // Otherwise, the following restrictions apply:
2148     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2149     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2150     //   enabled too.
2151     if (CallConv == CallingConv::AMDGPU_PS) {
2152       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2153            ((Info->getPSInputAddr() & 0xF) == 0 &&
2154             Info->isPSInputAllocated(11))) {
2155         CCInfo.AllocateReg(AMDGPU::VGPR0);
2156         CCInfo.AllocateReg(AMDGPU::VGPR1);
2157         Info->markPSInputAllocated(0);
2158         Info->markPSInputEnabled(0);
2159       }
2160       if (Subtarget->isAmdPalOS()) {
2161         // For isAmdPalOS, the user does not enable some bits after compilation
2162         // based on run-time states; the register values being generated here are
2163         // the final ones set in hardware. Therefore we need to apply the
2164         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2165         // a bit is set in PSInputAddr but not PSInputEnable is where the
2166         // frontend set up an input arg for a particular interpolation mode, but
2167         // nothing uses that input arg. Really we should have an earlier pass
2168         // that removes such an arg.)
2169         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2170         if ((PsInputBits & 0x7F) == 0 ||
2171             ((PsInputBits & 0xF) == 0 &&
2172              (PsInputBits >> 11 & 1)))
2173           Info->markPSInputEnabled(
2174               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2175       }
2176     }
2177 
2178     assert(!Info->hasDispatchPtr() &&
2179            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2180            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2181            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2182            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2183            !Info->hasWorkItemIDZ());
2184   } else if (IsKernel) {
2185     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2186   } else {
2187     Splits.append(Ins.begin(), Ins.end());
2188   }
2189 
2190   if (IsEntryFunc) {
2191     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2192     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2193   } else {
2194     // For the fixed ABI, pass workitem IDs in the last argument register.
2195     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2196       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2197   }
2198 
2199   if (IsKernel) {
2200     analyzeFormalArgumentsCompute(CCInfo, Ins);
2201   } else {
2202     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2203     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2204   }
2205 
2206   SmallVector<SDValue, 16> Chains;
2207 
2208   // FIXME: This is the minimum kernel argument alignment. We should improve
2209   // this to the maximum alignment of the arguments.
2210   //
2211   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2212   // kern arg offset.
2213   const unsigned KernelArgBaseAlign = 16;
2214 
2215    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2216     const ISD::InputArg &Arg = Ins[i];
2217     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2218       InVals.push_back(DAG.getUNDEF(Arg.VT));
2219       continue;
2220     }
2221 
2222     CCValAssign &VA = ArgLocs[ArgIdx++];
2223     MVT VT = VA.getLocVT();
2224 
2225     if (IsEntryFunc && VA.isMemLoc()) {
2226       VT = Ins[i].VT;
2227       EVT MemVT = VA.getLocVT();
2228 
2229       const uint64_t Offset = VA.getLocMemOffset();
2230       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2231 
2232       SDValue Arg = lowerKernargMemParameter(
2233         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2234       Chains.push_back(Arg.getValue(1));
2235 
2236       auto *ParamTy =
2237         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2238       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2239           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2240                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2241         // On SI local pointers are just offsets into LDS, so they are always
2242         // less than 16-bits.  On CI and newer they could potentially be
2243         // real pointers, so we can't guarantee their size.
2244         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2245                           DAG.getValueType(MVT::i16));
2246       }
2247 
2248       InVals.push_back(Arg);
2249       continue;
2250     } else if (!IsEntryFunc && VA.isMemLoc()) {
2251       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2252       InVals.push_back(Val);
2253       if (!Arg.Flags.isByVal())
2254         Chains.push_back(Val.getValue(1));
2255       continue;
2256     }
2257 
2258     assert(VA.isRegLoc() && "Parameter must be in a register!");
2259 
2260     Register Reg = VA.getLocReg();
2261     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2262     EVT ValVT = VA.getValVT();
2263 
2264     Reg = MF.addLiveIn(Reg, RC);
2265     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2266 
2267     if (Arg.Flags.isSRet()) {
2268       // The return object should be reasonably addressable.
2269 
2270       // FIXME: This helps when the return is a real sret. If it is a
2271       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2272       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2273       unsigned NumBits
2274         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2275       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2276         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2277     }
2278 
2279     // If this is an 8 or 16-bit value, it is really passed promoted
2280     // to 32 bits. Insert an assert[sz]ext to capture this, then
2281     // truncate to the right size.
2282     switch (VA.getLocInfo()) {
2283     case CCValAssign::Full:
2284       break;
2285     case CCValAssign::BCvt:
2286       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2287       break;
2288     case CCValAssign::SExt:
2289       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2290                         DAG.getValueType(ValVT));
2291       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2292       break;
2293     case CCValAssign::ZExt:
2294       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2295                         DAG.getValueType(ValVT));
2296       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2297       break;
2298     case CCValAssign::AExt:
2299       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2300       break;
2301     default:
2302       llvm_unreachable("Unknown loc info!");
2303     }
2304 
2305     InVals.push_back(Val);
2306   }
2307 
2308   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2309     // Special inputs come after user arguments.
2310     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2311   }
2312 
2313   // Start adding system SGPRs.
2314   if (IsEntryFunc) {
2315     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2316   } else {
2317     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2318     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2319   }
2320 
2321   auto &ArgUsageInfo =
2322     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2323   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2324 
2325   unsigned StackArgSize = CCInfo.getNextStackOffset();
2326   Info->setBytesInStackArgArea(StackArgSize);
2327 
2328   return Chains.empty() ? Chain :
2329     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2330 }
2331 
2332 // TODO: If return values can't fit in registers, we should return as many as
2333 // possible in registers before passing on stack.
2334 bool SITargetLowering::CanLowerReturn(
2335   CallingConv::ID CallConv,
2336   MachineFunction &MF, bool IsVarArg,
2337   const SmallVectorImpl<ISD::OutputArg> &Outs,
2338   LLVMContext &Context) const {
2339   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2340   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2341   // for shaders. Vector types should be explicitly handled by CC.
2342   if (AMDGPU::isEntryFunctionCC(CallConv))
2343     return true;
2344 
2345   SmallVector<CCValAssign, 16> RVLocs;
2346   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2347   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2348 }
2349 
2350 SDValue
2351 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2352                               bool isVarArg,
2353                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2354                               const SmallVectorImpl<SDValue> &OutVals,
2355                               const SDLoc &DL, SelectionDAG &DAG) const {
2356   MachineFunction &MF = DAG.getMachineFunction();
2357   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2358 
2359   if (AMDGPU::isKernel(CallConv)) {
2360     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2361                                              OutVals, DL, DAG);
2362   }
2363 
2364   bool IsShader = AMDGPU::isShader(CallConv);
2365 
2366   Info->setIfReturnsVoid(Outs.empty());
2367   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2368 
2369   // CCValAssign - represent the assignment of the return value to a location.
2370   SmallVector<CCValAssign, 48> RVLocs;
2371   SmallVector<ISD::OutputArg, 48> Splits;
2372 
2373   // CCState - Info about the registers and stack slots.
2374   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2375                  *DAG.getContext());
2376 
2377   // Analyze outgoing return values.
2378   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2379 
2380   SDValue Flag;
2381   SmallVector<SDValue, 48> RetOps;
2382   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2383 
2384   // Add return address for callable functions.
2385   if (!Info->isEntryFunction()) {
2386     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2387     SDValue ReturnAddrReg = CreateLiveInRegister(
2388       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2389 
2390     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2391         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2392         MVT::i64);
2393     Chain =
2394         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2395     Flag = Chain.getValue(1);
2396     RetOps.push_back(ReturnAddrVirtualReg);
2397   }
2398 
2399   // Copy the result values into the output registers.
2400   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2401        ++I, ++RealRVLocIdx) {
2402     CCValAssign &VA = RVLocs[I];
2403     assert(VA.isRegLoc() && "Can only return in registers!");
2404     // TODO: Partially return in registers if return values don't fit.
2405     SDValue Arg = OutVals[RealRVLocIdx];
2406 
2407     // Copied from other backends.
2408     switch (VA.getLocInfo()) {
2409     case CCValAssign::Full:
2410       break;
2411     case CCValAssign::BCvt:
2412       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2413       break;
2414     case CCValAssign::SExt:
2415       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2416       break;
2417     case CCValAssign::ZExt:
2418       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2419       break;
2420     case CCValAssign::AExt:
2421       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2422       break;
2423     default:
2424       llvm_unreachable("Unknown loc info!");
2425     }
2426 
2427     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2428     Flag = Chain.getValue(1);
2429     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2430   }
2431 
2432   // FIXME: Does sret work properly?
2433   if (!Info->isEntryFunction()) {
2434     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2435     const MCPhysReg *I =
2436       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2437     if (I) {
2438       for (; *I; ++I) {
2439         if (AMDGPU::SReg_64RegClass.contains(*I))
2440           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2441         else if (AMDGPU::SReg_32RegClass.contains(*I))
2442           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2443         else
2444           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2445       }
2446     }
2447   }
2448 
2449   // Update chain and glue.
2450   RetOps[0] = Chain;
2451   if (Flag.getNode())
2452     RetOps.push_back(Flag);
2453 
2454   unsigned Opc = AMDGPUISD::ENDPGM;
2455   if (!IsWaveEnd)
2456     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2457   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2458 }
2459 
2460 SDValue SITargetLowering::LowerCallResult(
2461     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2462     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2463     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2464     SDValue ThisVal) const {
2465   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2466 
2467   // Assign locations to each value returned by this call.
2468   SmallVector<CCValAssign, 16> RVLocs;
2469   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2470                  *DAG.getContext());
2471   CCInfo.AnalyzeCallResult(Ins, RetCC);
2472 
2473   // Copy all of the result registers out of their specified physreg.
2474   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2475     CCValAssign VA = RVLocs[i];
2476     SDValue Val;
2477 
2478     if (VA.isRegLoc()) {
2479       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2480       Chain = Val.getValue(1);
2481       InFlag = Val.getValue(2);
2482     } else if (VA.isMemLoc()) {
2483       report_fatal_error("TODO: return values in memory");
2484     } else
2485       llvm_unreachable("unknown argument location type");
2486 
2487     switch (VA.getLocInfo()) {
2488     case CCValAssign::Full:
2489       break;
2490     case CCValAssign::BCvt:
2491       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2492       break;
2493     case CCValAssign::ZExt:
2494       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2495                         DAG.getValueType(VA.getValVT()));
2496       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2497       break;
2498     case CCValAssign::SExt:
2499       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2500                         DAG.getValueType(VA.getValVT()));
2501       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2502       break;
2503     case CCValAssign::AExt:
2504       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2505       break;
2506     default:
2507       llvm_unreachable("Unknown loc info!");
2508     }
2509 
2510     InVals.push_back(Val);
2511   }
2512 
2513   return Chain;
2514 }
2515 
2516 // Add code to pass special inputs required depending on used features separate
2517 // from the explicit user arguments present in the IR.
2518 void SITargetLowering::passSpecialInputs(
2519     CallLoweringInfo &CLI,
2520     CCState &CCInfo,
2521     const SIMachineFunctionInfo &Info,
2522     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2523     SmallVectorImpl<SDValue> &MemOpChains,
2524     SDValue Chain) const {
2525   // If we don't have a call site, this was a call inserted by
2526   // legalization. These can never use special inputs.
2527   if (!CLI.CB)
2528     return;
2529 
2530   SelectionDAG &DAG = CLI.DAG;
2531   const SDLoc &DL = CLI.DL;
2532 
2533   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2534   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2535 
2536   const AMDGPUFunctionArgInfo *CalleeArgInfo
2537     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2538   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2539     auto &ArgUsageInfo =
2540       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2541     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2542   }
2543 
2544   // TODO: Unify with private memory register handling. This is complicated by
2545   // the fact that at least in kernels, the input argument is not necessarily
2546   // in the same location as the input.
2547   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2548     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2549     AMDGPUFunctionArgInfo::QUEUE_PTR,
2550     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2551     AMDGPUFunctionArgInfo::DISPATCH_ID,
2552     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2553     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2554     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2555   };
2556 
2557   for (auto InputID : InputRegs) {
2558     const ArgDescriptor *OutgoingArg;
2559     const TargetRegisterClass *ArgRC;
2560 
2561     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2562     if (!OutgoingArg)
2563       continue;
2564 
2565     const ArgDescriptor *IncomingArg;
2566     const TargetRegisterClass *IncomingArgRC;
2567     std::tie(IncomingArg, IncomingArgRC)
2568       = CallerArgInfo.getPreloadedValue(InputID);
2569     assert(IncomingArgRC == ArgRC);
2570 
2571     // All special arguments are ints for now.
2572     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2573     SDValue InputReg;
2574 
2575     if (IncomingArg) {
2576       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2577     } else {
2578       // The implicit arg ptr is special because it doesn't have a corresponding
2579       // input for kernels, and is computed from the kernarg segment pointer.
2580       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2581       InputReg = getImplicitArgPtr(DAG, DL);
2582     }
2583 
2584     if (OutgoingArg->isRegister()) {
2585       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2586       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2587         report_fatal_error("failed to allocate implicit input argument");
2588     } else {
2589       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2590       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2591                                               SpecialArgOffset);
2592       MemOpChains.push_back(ArgStore);
2593     }
2594   }
2595 
2596   // Pack workitem IDs into a single register or pass it as is if already
2597   // packed.
2598   const ArgDescriptor *OutgoingArg;
2599   const TargetRegisterClass *ArgRC;
2600 
2601   std::tie(OutgoingArg, ArgRC) =
2602     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2603   if (!OutgoingArg)
2604     std::tie(OutgoingArg, ArgRC) =
2605       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2606   if (!OutgoingArg)
2607     std::tie(OutgoingArg, ArgRC) =
2608       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2609   if (!OutgoingArg)
2610     return;
2611 
2612   const ArgDescriptor *IncomingArgX
2613     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2614   const ArgDescriptor *IncomingArgY
2615     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2616   const ArgDescriptor *IncomingArgZ
2617     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2618 
2619   SDValue InputReg;
2620   SDLoc SL;
2621 
2622   // If incoming ids are not packed we need to pack them.
2623   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2624     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2625 
2626   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2627     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2628     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2629                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2630     InputReg = InputReg.getNode() ?
2631                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2632   }
2633 
2634   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2635     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2636     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2637                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2638     InputReg = InputReg.getNode() ?
2639                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2640   }
2641 
2642   if (!InputReg.getNode()) {
2643     // Workitem ids are already packed, any of present incoming arguments
2644     // will carry all required fields.
2645     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2646       IncomingArgX ? *IncomingArgX :
2647       IncomingArgY ? *IncomingArgY :
2648                      *IncomingArgZ, ~0u);
2649     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2650   }
2651 
2652   if (OutgoingArg->isRegister()) {
2653     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2654     CCInfo.AllocateReg(OutgoingArg->getRegister());
2655   } else {
2656     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2657     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2658                                             SpecialArgOffset);
2659     MemOpChains.push_back(ArgStore);
2660   }
2661 }
2662 
2663 static bool canGuaranteeTCO(CallingConv::ID CC) {
2664   return CC == CallingConv::Fast;
2665 }
2666 
2667 /// Return true if we might ever do TCO for calls with this calling convention.
2668 static bool mayTailCallThisCC(CallingConv::ID CC) {
2669   switch (CC) {
2670   case CallingConv::C:
2671     return true;
2672   default:
2673     return canGuaranteeTCO(CC);
2674   }
2675 }
2676 
2677 bool SITargetLowering::isEligibleForTailCallOptimization(
2678     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2679     const SmallVectorImpl<ISD::OutputArg> &Outs,
2680     const SmallVectorImpl<SDValue> &OutVals,
2681     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2682   if (!mayTailCallThisCC(CalleeCC))
2683     return false;
2684 
2685   MachineFunction &MF = DAG.getMachineFunction();
2686   const Function &CallerF = MF.getFunction();
2687   CallingConv::ID CallerCC = CallerF.getCallingConv();
2688   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2689   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2690 
2691   // Kernels aren't callable, and don't have a live in return address so it
2692   // doesn't make sense to do a tail call with entry functions.
2693   if (!CallerPreserved)
2694     return false;
2695 
2696   bool CCMatch = CallerCC == CalleeCC;
2697 
2698   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2699     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2700       return true;
2701     return false;
2702   }
2703 
2704   // TODO: Can we handle var args?
2705   if (IsVarArg)
2706     return false;
2707 
2708   for (const Argument &Arg : CallerF.args()) {
2709     if (Arg.hasByValAttr())
2710       return false;
2711   }
2712 
2713   LLVMContext &Ctx = *DAG.getContext();
2714 
2715   // Check that the call results are passed in the same way.
2716   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2717                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2718                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2719     return false;
2720 
2721   // The callee has to preserve all registers the caller needs to preserve.
2722   if (!CCMatch) {
2723     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2724     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2725       return false;
2726   }
2727 
2728   // Nothing more to check if the callee is taking no arguments.
2729   if (Outs.empty())
2730     return true;
2731 
2732   SmallVector<CCValAssign, 16> ArgLocs;
2733   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2734 
2735   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2736 
2737   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2738   // If the stack arguments for this call do not fit into our own save area then
2739   // the call cannot be made tail.
2740   // TODO: Is this really necessary?
2741   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2742     return false;
2743 
2744   const MachineRegisterInfo &MRI = MF.getRegInfo();
2745   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2746 }
2747 
2748 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2749   if (!CI->isTailCall())
2750     return false;
2751 
2752   const Function *ParentFn = CI->getParent()->getParent();
2753   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2754     return false;
2755   return true;
2756 }
2757 
2758 // The wave scratch offset register is used as the global base pointer.
2759 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2760                                     SmallVectorImpl<SDValue> &InVals) const {
2761   SelectionDAG &DAG = CLI.DAG;
2762   const SDLoc &DL = CLI.DL;
2763   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2764   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2765   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2766   SDValue Chain = CLI.Chain;
2767   SDValue Callee = CLI.Callee;
2768   bool &IsTailCall = CLI.IsTailCall;
2769   CallingConv::ID CallConv = CLI.CallConv;
2770   bool IsVarArg = CLI.IsVarArg;
2771   bool IsSibCall = false;
2772   bool IsThisReturn = false;
2773   MachineFunction &MF = DAG.getMachineFunction();
2774 
2775   if (Callee.isUndef() || isNullConstant(Callee)) {
2776     if (!CLI.IsTailCall) {
2777       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2778         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2779     }
2780 
2781     return Chain;
2782   }
2783 
2784   if (IsVarArg) {
2785     return lowerUnhandledCall(CLI, InVals,
2786                               "unsupported call to variadic function ");
2787   }
2788 
2789   if (!CLI.CB)
2790     report_fatal_error("unsupported libcall legalization");
2791 
2792   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2793       !CLI.CB->getCalledFunction()) {
2794     return lowerUnhandledCall(CLI, InVals,
2795                               "unsupported indirect call to function ");
2796   }
2797 
2798   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2799     return lowerUnhandledCall(CLI, InVals,
2800                               "unsupported required tail call to function ");
2801   }
2802 
2803   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2804     // Note the issue is with the CC of the calling function, not of the call
2805     // itself.
2806     return lowerUnhandledCall(CLI, InVals,
2807                           "unsupported call from graphics shader of function ");
2808   }
2809 
2810   if (IsTailCall) {
2811     IsTailCall = isEligibleForTailCallOptimization(
2812       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2813     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2814       report_fatal_error("failed to perform tail call elimination on a call "
2815                          "site marked musttail");
2816     }
2817 
2818     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2819 
2820     // A sibling call is one where we're under the usual C ABI and not planning
2821     // to change that but can still do a tail call:
2822     if (!TailCallOpt && IsTailCall)
2823       IsSibCall = true;
2824 
2825     if (IsTailCall)
2826       ++NumTailCalls;
2827   }
2828 
2829   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2830   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2831   SmallVector<SDValue, 8> MemOpChains;
2832 
2833   // Analyze operands of the call, assigning locations to each operand.
2834   SmallVector<CCValAssign, 16> ArgLocs;
2835   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2836   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2837 
2838   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2839     // With a fixed ABI, allocate fixed registers before user arguments.
2840     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2841   }
2842 
2843   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2844 
2845   // Get a count of how many bytes are to be pushed on the stack.
2846   unsigned NumBytes = CCInfo.getNextStackOffset();
2847 
2848   if (IsSibCall) {
2849     // Since we're not changing the ABI to make this a tail call, the memory
2850     // operands are already available in the caller's incoming argument space.
2851     NumBytes = 0;
2852   }
2853 
2854   // FPDiff is the byte offset of the call's argument area from the callee's.
2855   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2856   // by this amount for a tail call. In a sibling call it must be 0 because the
2857   // caller will deallocate the entire stack and the callee still expects its
2858   // arguments to begin at SP+0. Completely unused for non-tail calls.
2859   int32_t FPDiff = 0;
2860   MachineFrameInfo &MFI = MF.getFrameInfo();
2861 
2862   // Adjust the stack pointer for the new arguments...
2863   // These operations are automatically eliminated by the prolog/epilog pass
2864   if (!IsSibCall) {
2865     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2866 
2867     SmallVector<SDValue, 4> CopyFromChains;
2868 
2869     // In the HSA case, this should be an identity copy.
2870     SDValue ScratchRSrcReg
2871       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2872     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2873     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2874     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2875   }
2876 
2877   MVT PtrVT = MVT::i32;
2878 
2879   // Walk the register/memloc assignments, inserting copies/loads.
2880   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2881     CCValAssign &VA = ArgLocs[i];
2882     SDValue Arg = OutVals[i];
2883 
2884     // Promote the value if needed.
2885     switch (VA.getLocInfo()) {
2886     case CCValAssign::Full:
2887       break;
2888     case CCValAssign::BCvt:
2889       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2890       break;
2891     case CCValAssign::ZExt:
2892       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2893       break;
2894     case CCValAssign::SExt:
2895       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2896       break;
2897     case CCValAssign::AExt:
2898       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2899       break;
2900     case CCValAssign::FPExt:
2901       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2902       break;
2903     default:
2904       llvm_unreachable("Unknown loc info!");
2905     }
2906 
2907     if (VA.isRegLoc()) {
2908       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2909     } else {
2910       assert(VA.isMemLoc());
2911 
2912       SDValue DstAddr;
2913       MachinePointerInfo DstInfo;
2914 
2915       unsigned LocMemOffset = VA.getLocMemOffset();
2916       int32_t Offset = LocMemOffset;
2917 
2918       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2919       MaybeAlign Alignment;
2920 
2921       if (IsTailCall) {
2922         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2923         unsigned OpSize = Flags.isByVal() ?
2924           Flags.getByValSize() : VA.getValVT().getStoreSize();
2925 
2926         // FIXME: We can have better than the minimum byval required alignment.
2927         Alignment =
2928             Flags.isByVal()
2929                 ? Flags.getNonZeroByValAlign()
2930                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2931 
2932         Offset = Offset + FPDiff;
2933         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2934 
2935         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2936         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2937 
2938         // Make sure any stack arguments overlapping with where we're storing
2939         // are loaded before this eventual operation. Otherwise they'll be
2940         // clobbered.
2941 
2942         // FIXME: Why is this really necessary? This seems to just result in a
2943         // lot of code to copy the stack and write them back to the same
2944         // locations, which are supposed to be immutable?
2945         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2946       } else {
2947         DstAddr = PtrOff;
2948         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2949         Alignment =
2950             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2951       }
2952 
2953       if (Outs[i].Flags.isByVal()) {
2954         SDValue SizeNode =
2955             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2956         SDValue Cpy =
2957             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2958                           Outs[i].Flags.getNonZeroByValAlign(),
2959                           /*isVol = */ false, /*AlwaysInline = */ true,
2960                           /*isTailCall = */ false, DstInfo,
2961                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2962 
2963         MemOpChains.push_back(Cpy);
2964       } else {
2965         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2966                                      Alignment ? Alignment->value() : 0);
2967         MemOpChains.push_back(Store);
2968       }
2969     }
2970   }
2971 
2972   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2973     // Copy special input registers after user input arguments.
2974     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2975   }
2976 
2977   if (!MemOpChains.empty())
2978     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2979 
2980   // Build a sequence of copy-to-reg nodes chained together with token chain
2981   // and flag operands which copy the outgoing args into the appropriate regs.
2982   SDValue InFlag;
2983   for (auto &RegToPass : RegsToPass) {
2984     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2985                              RegToPass.second, InFlag);
2986     InFlag = Chain.getValue(1);
2987   }
2988 
2989 
2990   SDValue PhysReturnAddrReg;
2991   if (IsTailCall) {
2992     // Since the return is being combined with the call, we need to pass on the
2993     // return address.
2994 
2995     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2996     SDValue ReturnAddrReg = CreateLiveInRegister(
2997       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2998 
2999     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3000                                         MVT::i64);
3001     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3002     InFlag = Chain.getValue(1);
3003   }
3004 
3005   // We don't usually want to end the call-sequence here because we would tidy
3006   // the frame up *after* the call, however in the ABI-changing tail-call case
3007   // we've carefully laid out the parameters so that when sp is reset they'll be
3008   // in the correct location.
3009   if (IsTailCall && !IsSibCall) {
3010     Chain = DAG.getCALLSEQ_END(Chain,
3011                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3012                                DAG.getTargetConstant(0, DL, MVT::i32),
3013                                InFlag, DL);
3014     InFlag = Chain.getValue(1);
3015   }
3016 
3017   std::vector<SDValue> Ops;
3018   Ops.push_back(Chain);
3019   Ops.push_back(Callee);
3020   // Add a redundant copy of the callee global which will not be legalized, as
3021   // we need direct access to the callee later.
3022   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3023     const GlobalValue *GV = GSD->getGlobal();
3024     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3025   } else {
3026     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3027   }
3028 
3029   if (IsTailCall) {
3030     // Each tail call may have to adjust the stack by a different amount, so
3031     // this information must travel along with the operation for eventual
3032     // consumption by emitEpilogue.
3033     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3034 
3035     Ops.push_back(PhysReturnAddrReg);
3036   }
3037 
3038   // Add argument registers to the end of the list so that they are known live
3039   // into the call.
3040   for (auto &RegToPass : RegsToPass) {
3041     Ops.push_back(DAG.getRegister(RegToPass.first,
3042                                   RegToPass.second.getValueType()));
3043   }
3044 
3045   // Add a register mask operand representing the call-preserved registers.
3046 
3047   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3048   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3049   assert(Mask && "Missing call preserved mask for calling convention");
3050   Ops.push_back(DAG.getRegisterMask(Mask));
3051 
3052   if (InFlag.getNode())
3053     Ops.push_back(InFlag);
3054 
3055   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3056 
3057   // If we're doing a tall call, use a TC_RETURN here rather than an
3058   // actual call instruction.
3059   if (IsTailCall) {
3060     MFI.setHasTailCall();
3061     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3062   }
3063 
3064   // Returns a chain and a flag for retval copy to use.
3065   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3066   Chain = Call.getValue(0);
3067   InFlag = Call.getValue(1);
3068 
3069   uint64_t CalleePopBytes = NumBytes;
3070   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3071                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3072                              InFlag, DL);
3073   if (!Ins.empty())
3074     InFlag = Chain.getValue(1);
3075 
3076   // Handle result values, copying them out of physregs into vregs that we
3077   // return.
3078   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3079                          InVals, IsThisReturn,
3080                          IsThisReturn ? OutVals[0] : SDValue());
3081 }
3082 
3083 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3084                                              const MachineFunction &MF) const {
3085   Register Reg = StringSwitch<Register>(RegName)
3086     .Case("m0", AMDGPU::M0)
3087     .Case("exec", AMDGPU::EXEC)
3088     .Case("exec_lo", AMDGPU::EXEC_LO)
3089     .Case("exec_hi", AMDGPU::EXEC_HI)
3090     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3091     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3092     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3093     .Default(Register());
3094 
3095   if (Reg == AMDGPU::NoRegister) {
3096     report_fatal_error(Twine("invalid register name \""
3097                              + StringRef(RegName)  + "\"."));
3098 
3099   }
3100 
3101   if (!Subtarget->hasFlatScrRegister() &&
3102        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3103     report_fatal_error(Twine("invalid register \""
3104                              + StringRef(RegName)  + "\" for subtarget."));
3105   }
3106 
3107   switch (Reg) {
3108   case AMDGPU::M0:
3109   case AMDGPU::EXEC_LO:
3110   case AMDGPU::EXEC_HI:
3111   case AMDGPU::FLAT_SCR_LO:
3112   case AMDGPU::FLAT_SCR_HI:
3113     if (VT.getSizeInBits() == 32)
3114       return Reg;
3115     break;
3116   case AMDGPU::EXEC:
3117   case AMDGPU::FLAT_SCR:
3118     if (VT.getSizeInBits() == 64)
3119       return Reg;
3120     break;
3121   default:
3122     llvm_unreachable("missing register type checking");
3123   }
3124 
3125   report_fatal_error(Twine("invalid type for register \""
3126                            + StringRef(RegName) + "\"."));
3127 }
3128 
3129 // If kill is not the last instruction, split the block so kill is always a
3130 // proper terminator.
3131 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3132                                                     MachineBasicBlock *BB) const {
3133   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3134 
3135   MachineBasicBlock::iterator SplitPoint(&MI);
3136   ++SplitPoint;
3137 
3138   if (SplitPoint == BB->end()) {
3139     // Don't bother with a new block.
3140     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3141     return BB;
3142   }
3143 
3144   MachineFunction *MF = BB->getParent();
3145   MachineBasicBlock *SplitBB
3146     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3147 
3148   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3149   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3150 
3151   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3152   BB->addSuccessor(SplitBB);
3153 
3154   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3155   return SplitBB;
3156 }
3157 
3158 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3159 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3160 // be the first instruction in the remainder block.
3161 //
3162 /// \returns { LoopBody, Remainder }
3163 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3164 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3165   MachineFunction *MF = MBB.getParent();
3166   MachineBasicBlock::iterator I(&MI);
3167 
3168   // To insert the loop we need to split the block. Move everything after this
3169   // point to a new block, and insert a new empty block between the two.
3170   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3171   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3172   MachineFunction::iterator MBBI(MBB);
3173   ++MBBI;
3174 
3175   MF->insert(MBBI, LoopBB);
3176   MF->insert(MBBI, RemainderBB);
3177 
3178   LoopBB->addSuccessor(LoopBB);
3179   LoopBB->addSuccessor(RemainderBB);
3180 
3181   // Move the rest of the block into a new block.
3182   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3183 
3184   if (InstInLoop) {
3185     auto Next = std::next(I);
3186 
3187     // Move instruction to loop body.
3188     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3189 
3190     // Move the rest of the block.
3191     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3192   } else {
3193     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3194   }
3195 
3196   MBB.addSuccessor(LoopBB);
3197 
3198   return std::make_pair(LoopBB, RemainderBB);
3199 }
3200 
3201 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3202 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3203   MachineBasicBlock *MBB = MI.getParent();
3204   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3205   auto I = MI.getIterator();
3206   auto E = std::next(I);
3207 
3208   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3209     .addImm(0);
3210 
3211   MIBundleBuilder Bundler(*MBB, I, E);
3212   finalizeBundle(*MBB, Bundler.begin());
3213 }
3214 
3215 MachineBasicBlock *
3216 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3217                                          MachineBasicBlock *BB) const {
3218   const DebugLoc &DL = MI.getDebugLoc();
3219 
3220   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3221 
3222   MachineBasicBlock *LoopBB;
3223   MachineBasicBlock *RemainderBB;
3224   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3225 
3226   // Apparently kill flags are only valid if the def is in the same block?
3227   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3228     Src->setIsKill(false);
3229 
3230   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3231 
3232   MachineBasicBlock::iterator I = LoopBB->end();
3233 
3234   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3235     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3236 
3237   // Clear TRAP_STS.MEM_VIOL
3238   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3239     .addImm(0)
3240     .addImm(EncodedReg);
3241 
3242   bundleInstWithWaitcnt(MI);
3243 
3244   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3245 
3246   // Load and check TRAP_STS.MEM_VIOL
3247   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3248     .addImm(EncodedReg);
3249 
3250   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3251   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3252     .addReg(Reg, RegState::Kill)
3253     .addImm(0);
3254   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3255     .addMBB(LoopBB);
3256 
3257   return RemainderBB;
3258 }
3259 
3260 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3261 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3262 // will only do one iteration. In the worst case, this will loop 64 times.
3263 //
3264 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3265 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3266   const SIInstrInfo *TII,
3267   MachineRegisterInfo &MRI,
3268   MachineBasicBlock &OrigBB,
3269   MachineBasicBlock &LoopBB,
3270   const DebugLoc &DL,
3271   const MachineOperand &IdxReg,
3272   unsigned InitReg,
3273   unsigned ResultReg,
3274   unsigned PhiReg,
3275   unsigned InitSaveExecReg,
3276   int Offset,
3277   bool UseGPRIdxMode,
3278   bool IsIndirectSrc) {
3279   MachineFunction *MF = OrigBB.getParent();
3280   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3281   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3282   MachineBasicBlock::iterator I = LoopBB.begin();
3283 
3284   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3285   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3286   Register NewExec = MRI.createVirtualRegister(BoolRC);
3287   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3288   Register CondReg = MRI.createVirtualRegister(BoolRC);
3289 
3290   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3291     .addReg(InitReg)
3292     .addMBB(&OrigBB)
3293     .addReg(ResultReg)
3294     .addMBB(&LoopBB);
3295 
3296   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3297     .addReg(InitSaveExecReg)
3298     .addMBB(&OrigBB)
3299     .addReg(NewExec)
3300     .addMBB(&LoopBB);
3301 
3302   // Read the next variant <- also loop target.
3303   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3304     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3305 
3306   // Compare the just read M0 value to all possible Idx values.
3307   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3308     .addReg(CurrentIdxReg)
3309     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3310 
3311   // Update EXEC, save the original EXEC value to VCC.
3312   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3313                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3314           NewExec)
3315     .addReg(CondReg, RegState::Kill);
3316 
3317   MRI.setSimpleHint(NewExec, CondReg);
3318 
3319   if (UseGPRIdxMode) {
3320     unsigned IdxReg;
3321     if (Offset == 0) {
3322       IdxReg = CurrentIdxReg;
3323     } else {
3324       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3325       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3326         .addReg(CurrentIdxReg, RegState::Kill)
3327         .addImm(Offset);
3328     }
3329     unsigned IdxMode = IsIndirectSrc ?
3330       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3331     MachineInstr *SetOn =
3332       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3333       .addReg(IdxReg, RegState::Kill)
3334       .addImm(IdxMode);
3335     SetOn->getOperand(3).setIsUndef();
3336   } else {
3337     // Move index from VCC into M0
3338     if (Offset == 0) {
3339       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3340         .addReg(CurrentIdxReg, RegState::Kill);
3341     } else {
3342       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3343         .addReg(CurrentIdxReg, RegState::Kill)
3344         .addImm(Offset);
3345     }
3346   }
3347 
3348   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3349   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3350   MachineInstr *InsertPt =
3351     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3352                                                   : AMDGPU::S_XOR_B64_term), Exec)
3353       .addReg(Exec)
3354       .addReg(NewExec);
3355 
3356   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3357   // s_cbranch_scc0?
3358 
3359   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3360   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3361     .addMBB(&LoopBB);
3362 
3363   return InsertPt->getIterator();
3364 }
3365 
3366 // This has slightly sub-optimal regalloc when the source vector is killed by
3367 // the read. The register allocator does not understand that the kill is
3368 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3369 // subregister from it, using 1 more VGPR than necessary. This was saved when
3370 // this was expanded after register allocation.
3371 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3372                                                   MachineBasicBlock &MBB,
3373                                                   MachineInstr &MI,
3374                                                   unsigned InitResultReg,
3375                                                   unsigned PhiReg,
3376                                                   int Offset,
3377                                                   bool UseGPRIdxMode,
3378                                                   bool IsIndirectSrc) {
3379   MachineFunction *MF = MBB.getParent();
3380   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3381   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3382   MachineRegisterInfo &MRI = MF->getRegInfo();
3383   const DebugLoc &DL = MI.getDebugLoc();
3384   MachineBasicBlock::iterator I(&MI);
3385 
3386   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3387   Register DstReg = MI.getOperand(0).getReg();
3388   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3389   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3390   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3391   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3392 
3393   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3394 
3395   // Save the EXEC mask
3396   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3397     .addReg(Exec);
3398 
3399   MachineBasicBlock *LoopBB;
3400   MachineBasicBlock *RemainderBB;
3401   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3402 
3403   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3404 
3405   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3406                                       InitResultReg, DstReg, PhiReg, TmpExec,
3407                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3408   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3409   MachineFunction::iterator MBBI(LoopBB);
3410   ++MBBI;
3411   MF->insert(MBBI, LandingPad);
3412   LoopBB->removeSuccessor(RemainderBB);
3413   LandingPad->addSuccessor(RemainderBB);
3414   LoopBB->addSuccessor(LandingPad);
3415   MachineBasicBlock::iterator First = LandingPad->begin();
3416   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3417     .addReg(SaveExec);
3418 
3419   return InsPt;
3420 }
3421 
3422 // Returns subreg index, offset
3423 static std::pair<unsigned, int>
3424 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3425                             const TargetRegisterClass *SuperRC,
3426                             unsigned VecReg,
3427                             int Offset) {
3428   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3429 
3430   // Skip out of bounds offsets, or else we would end up using an undefined
3431   // register.
3432   if (Offset >= NumElts || Offset < 0)
3433     return std::make_pair(AMDGPU::sub0, Offset);
3434 
3435   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3436 }
3437 
3438 // Return true if the index is an SGPR and was set.
3439 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3440                                  MachineRegisterInfo &MRI,
3441                                  MachineInstr &MI,
3442                                  int Offset,
3443                                  bool UseGPRIdxMode,
3444                                  bool IsIndirectSrc) {
3445   MachineBasicBlock *MBB = MI.getParent();
3446   const DebugLoc &DL = MI.getDebugLoc();
3447   MachineBasicBlock::iterator I(&MI);
3448 
3449   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3450   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3451 
3452   assert(Idx->getReg() != AMDGPU::NoRegister);
3453 
3454   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3455     return false;
3456 
3457   if (UseGPRIdxMode) {
3458     unsigned IdxMode = IsIndirectSrc ?
3459       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3460     if (Offset == 0) {
3461       MachineInstr *SetOn =
3462           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3463               .add(*Idx)
3464               .addImm(IdxMode);
3465 
3466       SetOn->getOperand(3).setIsUndef();
3467     } else {
3468       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3469       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3470           .add(*Idx)
3471           .addImm(Offset);
3472       MachineInstr *SetOn =
3473         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3474         .addReg(Tmp, RegState::Kill)
3475         .addImm(IdxMode);
3476 
3477       SetOn->getOperand(3).setIsUndef();
3478     }
3479 
3480     return true;
3481   }
3482 
3483   if (Offset == 0) {
3484     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3485       .add(*Idx);
3486   } else {
3487     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3488       .add(*Idx)
3489       .addImm(Offset);
3490   }
3491 
3492   return true;
3493 }
3494 
3495 // Control flow needs to be inserted if indexing with a VGPR.
3496 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3497                                           MachineBasicBlock &MBB,
3498                                           const GCNSubtarget &ST) {
3499   const SIInstrInfo *TII = ST.getInstrInfo();
3500   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3501   MachineFunction *MF = MBB.getParent();
3502   MachineRegisterInfo &MRI = MF->getRegInfo();
3503 
3504   Register Dst = MI.getOperand(0).getReg();
3505   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3506   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3507 
3508   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3509 
3510   unsigned SubReg;
3511   std::tie(SubReg, Offset)
3512     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3513 
3514   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3515 
3516   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3517     MachineBasicBlock::iterator I(&MI);
3518     const DebugLoc &DL = MI.getDebugLoc();
3519 
3520     if (UseGPRIdxMode) {
3521       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3522       // to avoid interfering with other uses, so probably requires a new
3523       // optimization pass.
3524       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3525         .addReg(SrcReg, RegState::Undef, SubReg)
3526         .addReg(SrcReg, RegState::Implicit)
3527         .addReg(AMDGPU::M0, RegState::Implicit);
3528       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3529     } else {
3530       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3531         .addReg(SrcReg, RegState::Undef, SubReg)
3532         .addReg(SrcReg, RegState::Implicit);
3533     }
3534 
3535     MI.eraseFromParent();
3536 
3537     return &MBB;
3538   }
3539 
3540   const DebugLoc &DL = MI.getDebugLoc();
3541   MachineBasicBlock::iterator I(&MI);
3542 
3543   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3544   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3545 
3546   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3547 
3548   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3549                               Offset, UseGPRIdxMode, true);
3550   MachineBasicBlock *LoopBB = InsPt->getParent();
3551 
3552   if (UseGPRIdxMode) {
3553     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3554       .addReg(SrcReg, RegState::Undef, SubReg)
3555       .addReg(SrcReg, RegState::Implicit)
3556       .addReg(AMDGPU::M0, RegState::Implicit);
3557     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3558   } else {
3559     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3560       .addReg(SrcReg, RegState::Undef, SubReg)
3561       .addReg(SrcReg, RegState::Implicit);
3562   }
3563 
3564   MI.eraseFromParent();
3565 
3566   return LoopBB;
3567 }
3568 
3569 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3570                                           MachineBasicBlock &MBB,
3571                                           const GCNSubtarget &ST) {
3572   const SIInstrInfo *TII = ST.getInstrInfo();
3573   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3574   MachineFunction *MF = MBB.getParent();
3575   MachineRegisterInfo &MRI = MF->getRegInfo();
3576 
3577   Register Dst = MI.getOperand(0).getReg();
3578   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3579   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3580   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3581   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3582   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3583 
3584   // This can be an immediate, but will be folded later.
3585   assert(Val->getReg());
3586 
3587   unsigned SubReg;
3588   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3589                                                          SrcVec->getReg(),
3590                                                          Offset);
3591   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3592 
3593   if (Idx->getReg() == AMDGPU::NoRegister) {
3594     MachineBasicBlock::iterator I(&MI);
3595     const DebugLoc &DL = MI.getDebugLoc();
3596 
3597     assert(Offset == 0);
3598 
3599     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3600         .add(*SrcVec)
3601         .add(*Val)
3602         .addImm(SubReg);
3603 
3604     MI.eraseFromParent();
3605     return &MBB;
3606   }
3607 
3608   const MCInstrDesc &MovRelDesc
3609     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3610 
3611   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3612     MachineBasicBlock::iterator I(&MI);
3613     const DebugLoc &DL = MI.getDebugLoc();
3614     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3615       .addReg(SrcVec->getReg())
3616       .add(*Val)
3617       .addImm(SubReg);
3618     if (UseGPRIdxMode)
3619       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3620 
3621     MI.eraseFromParent();
3622     return &MBB;
3623   }
3624 
3625   if (Val->isReg())
3626     MRI.clearKillFlags(Val->getReg());
3627 
3628   const DebugLoc &DL = MI.getDebugLoc();
3629 
3630   Register PhiReg = MRI.createVirtualRegister(VecRC);
3631 
3632   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3633                               Offset, UseGPRIdxMode, false);
3634   MachineBasicBlock *LoopBB = InsPt->getParent();
3635 
3636   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3637     .addReg(PhiReg)
3638     .add(*Val)
3639     .addImm(AMDGPU::sub0);
3640   if (UseGPRIdxMode)
3641     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3642 
3643   MI.eraseFromParent();
3644   return LoopBB;
3645 }
3646 
3647 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3648   MachineInstr &MI, MachineBasicBlock *BB) const {
3649 
3650   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3651   MachineFunction *MF = BB->getParent();
3652   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3653 
3654   if (TII->isMIMG(MI)) {
3655     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3656       report_fatal_error("missing mem operand from MIMG instruction");
3657     }
3658     // Add a memoperand for mimg instructions so that they aren't assumed to
3659     // be ordered memory instuctions.
3660 
3661     return BB;
3662   }
3663 
3664   switch (MI.getOpcode()) {
3665   case AMDGPU::S_UADDO_PSEUDO:
3666   case AMDGPU::S_USUBO_PSEUDO: {
3667     const DebugLoc &DL = MI.getDebugLoc();
3668     MachineOperand &Dest0 = MI.getOperand(0);
3669     MachineOperand &Dest1 = MI.getOperand(1);
3670     MachineOperand &Src0 = MI.getOperand(2);
3671     MachineOperand &Src1 = MI.getOperand(3);
3672 
3673     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3674                        ? AMDGPU::S_ADD_I32
3675                        : AMDGPU::S_SUB_I32;
3676     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3677 
3678     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3679         .addImm(1)
3680         .addImm(0);
3681 
3682     MI.eraseFromParent();
3683     return BB;
3684   }
3685   case AMDGPU::S_ADD_U64_PSEUDO:
3686   case AMDGPU::S_SUB_U64_PSEUDO: {
3687     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3688     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3689     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3690     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3691     const DebugLoc &DL = MI.getDebugLoc();
3692 
3693     MachineOperand &Dest = MI.getOperand(0);
3694     MachineOperand &Src0 = MI.getOperand(1);
3695     MachineOperand &Src1 = MI.getOperand(2);
3696 
3697     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3698     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3699 
3700     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3701         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3702     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3703         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3704 
3705     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3706         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3707     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3708         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3709 
3710     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3711 
3712     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3713     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3714     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3715     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3716     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3717         .addReg(DestSub0)
3718         .addImm(AMDGPU::sub0)
3719         .addReg(DestSub1)
3720         .addImm(AMDGPU::sub1);
3721     MI.eraseFromParent();
3722     return BB;
3723   }
3724   case AMDGPU::V_ADD_U64_PSEUDO:
3725   case AMDGPU::V_SUB_U64_PSEUDO: {
3726     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3727     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3728     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3729     const DebugLoc &DL = MI.getDebugLoc();
3730 
3731     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3732 
3733     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3734 
3735     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3736     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3737 
3738     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3739     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3740 
3741     MachineOperand &Dest = MI.getOperand(0);
3742     MachineOperand &Src0 = MI.getOperand(1);
3743     MachineOperand &Src1 = MI.getOperand(2);
3744 
3745     const TargetRegisterClass *Src0RC = Src0.isReg()
3746                                             ? MRI.getRegClass(Src0.getReg())
3747                                             : &AMDGPU::VReg_64RegClass;
3748     const TargetRegisterClass *Src1RC = Src1.isReg()
3749                                             ? MRI.getRegClass(Src1.getReg())
3750                                             : &AMDGPU::VReg_64RegClass;
3751 
3752     const TargetRegisterClass *Src0SubRC =
3753         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3754     const TargetRegisterClass *Src1SubRC =
3755         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3756 
3757     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3758         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3759     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3760         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3761 
3762     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3763         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3764     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3765         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3766 
3767     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
3768     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3769                                .addReg(CarryReg, RegState::Define)
3770                                .add(SrcReg0Sub0)
3771                                .add(SrcReg1Sub0)
3772                                .addImm(0); // clamp bit
3773 
3774     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3775     MachineInstr *HiHalf =
3776         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3777             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3778             .add(SrcReg0Sub1)
3779             .add(SrcReg1Sub1)
3780             .addReg(CarryReg, RegState::Kill)
3781             .addImm(0); // clamp bit
3782 
3783     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3784         .addReg(DestSub0)
3785         .addImm(AMDGPU::sub0)
3786         .addReg(DestSub1)
3787         .addImm(AMDGPU::sub1);
3788     TII->legalizeOperands(*LoHalf);
3789     TII->legalizeOperands(*HiHalf);
3790     MI.eraseFromParent();
3791     return BB;
3792   }
3793   case AMDGPU::S_ADD_CO_PSEUDO:
3794   case AMDGPU::S_SUB_CO_PSEUDO: {
3795     // This pseudo has a chance to be selected
3796     // only from uniform add/subcarry node. All the VGPR operands
3797     // therefore assumed to be splat vectors.
3798     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3799     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3800     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3801     MachineBasicBlock::iterator MII = MI;
3802     const DebugLoc &DL = MI.getDebugLoc();
3803     MachineOperand &Dest = MI.getOperand(0);
3804     MachineOperand &Src0 = MI.getOperand(2);
3805     MachineOperand &Src1 = MI.getOperand(3);
3806     MachineOperand &Src2 = MI.getOperand(4);
3807     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3808                        ? AMDGPU::S_ADDC_U32
3809                        : AMDGPU::S_SUBB_U32;
3810     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3811       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3812       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3813           .addReg(Src0.getReg());
3814       Src0.setReg(RegOp0);
3815     }
3816     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3817       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3818       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3819           .addReg(Src1.getReg());
3820       Src1.setReg(RegOp1);
3821     }
3822     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3823     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3824       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3825           .addReg(Src2.getReg());
3826       Src2.setReg(RegOp2);
3827     }
3828 
3829     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3830       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3831           .addReg(Src2.getReg())
3832           .addImm(0);
3833     } else {
3834       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3835           .addReg(Src2.getReg())
3836           .addImm(0);
3837     }
3838 
3839     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3840     MI.eraseFromParent();
3841     return BB;
3842   }
3843   case AMDGPU::SI_INIT_M0: {
3844     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3845             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3846         .add(MI.getOperand(0));
3847     MI.eraseFromParent();
3848     return BB;
3849   }
3850   case AMDGPU::SI_INIT_EXEC:
3851     // This should be before all vector instructions.
3852     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3853             AMDGPU::EXEC)
3854         .addImm(MI.getOperand(0).getImm());
3855     MI.eraseFromParent();
3856     return BB;
3857 
3858   case AMDGPU::SI_INIT_EXEC_LO:
3859     // This should be before all vector instructions.
3860     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3861             AMDGPU::EXEC_LO)
3862         .addImm(MI.getOperand(0).getImm());
3863     MI.eraseFromParent();
3864     return BB;
3865 
3866   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3867     // Extract the thread count from an SGPR input and set EXEC accordingly.
3868     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3869     //
3870     // S_BFE_U32 count, input, {shift, 7}
3871     // S_BFM_B64 exec, count, 0
3872     // S_CMP_EQ_U32 count, 64
3873     // S_CMOV_B64 exec, -1
3874     MachineInstr *FirstMI = &*BB->begin();
3875     MachineRegisterInfo &MRI = MF->getRegInfo();
3876     Register InputReg = MI.getOperand(0).getReg();
3877     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3878     bool Found = false;
3879 
3880     // Move the COPY of the input reg to the beginning, so that we can use it.
3881     for (auto I = BB->begin(); I != &MI; I++) {
3882       if (I->getOpcode() != TargetOpcode::COPY ||
3883           I->getOperand(0).getReg() != InputReg)
3884         continue;
3885 
3886       if (I == FirstMI) {
3887         FirstMI = &*++BB->begin();
3888       } else {
3889         I->removeFromParent();
3890         BB->insert(FirstMI, &*I);
3891       }
3892       Found = true;
3893       break;
3894     }
3895     assert(Found);
3896     (void)Found;
3897 
3898     // This should be before all vector instructions.
3899     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3900     bool isWave32 = getSubtarget()->isWave32();
3901     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3902     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3903         .addReg(InputReg)
3904         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3905     BuildMI(*BB, FirstMI, DebugLoc(),
3906             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3907             Exec)
3908         .addReg(CountReg)
3909         .addImm(0);
3910     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3911         .addReg(CountReg, RegState::Kill)
3912         .addImm(getSubtarget()->getWavefrontSize());
3913     BuildMI(*BB, FirstMI, DebugLoc(),
3914             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3915             Exec)
3916         .addImm(-1);
3917     MI.eraseFromParent();
3918     return BB;
3919   }
3920 
3921   case AMDGPU::GET_GROUPSTATICSIZE: {
3922     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3923            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3924     DebugLoc DL = MI.getDebugLoc();
3925     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3926         .add(MI.getOperand(0))
3927         .addImm(MFI->getLDSSize());
3928     MI.eraseFromParent();
3929     return BB;
3930   }
3931   case AMDGPU::SI_INDIRECT_SRC_V1:
3932   case AMDGPU::SI_INDIRECT_SRC_V2:
3933   case AMDGPU::SI_INDIRECT_SRC_V4:
3934   case AMDGPU::SI_INDIRECT_SRC_V8:
3935   case AMDGPU::SI_INDIRECT_SRC_V16:
3936   case AMDGPU::SI_INDIRECT_SRC_V32:
3937     return emitIndirectSrc(MI, *BB, *getSubtarget());
3938   case AMDGPU::SI_INDIRECT_DST_V1:
3939   case AMDGPU::SI_INDIRECT_DST_V2:
3940   case AMDGPU::SI_INDIRECT_DST_V4:
3941   case AMDGPU::SI_INDIRECT_DST_V8:
3942   case AMDGPU::SI_INDIRECT_DST_V16:
3943   case AMDGPU::SI_INDIRECT_DST_V32:
3944     return emitIndirectDst(MI, *BB, *getSubtarget());
3945   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3946   case AMDGPU::SI_KILL_I1_PSEUDO:
3947     return splitKillBlock(MI, BB);
3948   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3949     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3950     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3951     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3952 
3953     Register Dst = MI.getOperand(0).getReg();
3954     Register Src0 = MI.getOperand(1).getReg();
3955     Register Src1 = MI.getOperand(2).getReg();
3956     const DebugLoc &DL = MI.getDebugLoc();
3957     Register SrcCond = MI.getOperand(3).getReg();
3958 
3959     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3960     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3961     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3962     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3963 
3964     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3965       .addReg(SrcCond);
3966     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3967       .addImm(0)
3968       .addReg(Src0, 0, AMDGPU::sub0)
3969       .addImm(0)
3970       .addReg(Src1, 0, AMDGPU::sub0)
3971       .addReg(SrcCondCopy);
3972     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3973       .addImm(0)
3974       .addReg(Src0, 0, AMDGPU::sub1)
3975       .addImm(0)
3976       .addReg(Src1, 0, AMDGPU::sub1)
3977       .addReg(SrcCondCopy);
3978 
3979     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3980       .addReg(DstLo)
3981       .addImm(AMDGPU::sub0)
3982       .addReg(DstHi)
3983       .addImm(AMDGPU::sub1);
3984     MI.eraseFromParent();
3985     return BB;
3986   }
3987   case AMDGPU::SI_BR_UNDEF: {
3988     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3989     const DebugLoc &DL = MI.getDebugLoc();
3990     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3991                            .add(MI.getOperand(0));
3992     Br->getOperand(1).setIsUndef(true); // read undef SCC
3993     MI.eraseFromParent();
3994     return BB;
3995   }
3996   case AMDGPU::ADJCALLSTACKUP:
3997   case AMDGPU::ADJCALLSTACKDOWN: {
3998     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3999     MachineInstrBuilder MIB(*MF, &MI);
4000 
4001     // Add an implicit use of the frame offset reg to prevent the restore copy
4002     // inserted after the call from being reorderd after stack operations in the
4003     // the caller's frame.
4004     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4005         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4006         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4007     return BB;
4008   }
4009   case AMDGPU::SI_CALL_ISEL: {
4010     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4011     const DebugLoc &DL = MI.getDebugLoc();
4012 
4013     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4014 
4015     MachineInstrBuilder MIB;
4016     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4017 
4018     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4019       MIB.add(MI.getOperand(I));
4020 
4021     MIB.cloneMemRefs(MI);
4022     MI.eraseFromParent();
4023     return BB;
4024   }
4025   case AMDGPU::V_ADD_I32_e32:
4026   case AMDGPU::V_SUB_I32_e32:
4027   case AMDGPU::V_SUBREV_I32_e32: {
4028     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4029     const DebugLoc &DL = MI.getDebugLoc();
4030     unsigned Opc = MI.getOpcode();
4031 
4032     bool NeedClampOperand = false;
4033     if (TII->pseudoToMCOpcode(Opc) == -1) {
4034       Opc = AMDGPU::getVOPe64(Opc);
4035       NeedClampOperand = true;
4036     }
4037 
4038     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4039     if (TII->isVOP3(*I)) {
4040       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4041       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4042       I.addReg(TRI->getVCC(), RegState::Define);
4043     }
4044     I.add(MI.getOperand(1))
4045      .add(MI.getOperand(2));
4046     if (NeedClampOperand)
4047       I.addImm(0); // clamp bit for e64 encoding
4048 
4049     TII->legalizeOperands(*I);
4050 
4051     MI.eraseFromParent();
4052     return BB;
4053   }
4054   case AMDGPU::DS_GWS_INIT:
4055   case AMDGPU::DS_GWS_SEMA_V:
4056   case AMDGPU::DS_GWS_SEMA_BR:
4057   case AMDGPU::DS_GWS_SEMA_P:
4058   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4059   case AMDGPU::DS_GWS_BARRIER:
4060     // A s_waitcnt 0 is required to be the instruction immediately following.
4061     if (getSubtarget()->hasGWSAutoReplay()) {
4062       bundleInstWithWaitcnt(MI);
4063       return BB;
4064     }
4065 
4066     return emitGWSMemViolTestLoop(MI, BB);
4067   default:
4068     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4069   }
4070 }
4071 
4072 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4073   return isTypeLegal(VT.getScalarType());
4074 }
4075 
4076 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4077   // This currently forces unfolding various combinations of fsub into fma with
4078   // free fneg'd operands. As long as we have fast FMA (controlled by
4079   // isFMAFasterThanFMulAndFAdd), we should perform these.
4080 
4081   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4082   // most of these combines appear to be cycle neutral but save on instruction
4083   // count / code size.
4084   return true;
4085 }
4086 
4087 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4088                                          EVT VT) const {
4089   if (!VT.isVector()) {
4090     return MVT::i1;
4091   }
4092   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4093 }
4094 
4095 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4096   // TODO: Should i16 be used always if legal? For now it would force VALU
4097   // shifts.
4098   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4099 }
4100 
4101 // Answering this is somewhat tricky and depends on the specific device which
4102 // have different rates for fma or all f64 operations.
4103 //
4104 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4105 // regardless of which device (although the number of cycles differs between
4106 // devices), so it is always profitable for f64.
4107 //
4108 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4109 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4110 // which we can always do even without fused FP ops since it returns the same
4111 // result as the separate operations and since it is always full
4112 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4113 // however does not support denormals, so we do report fma as faster if we have
4114 // a fast fma device and require denormals.
4115 //
4116 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4117                                                   EVT VT) const {
4118   VT = VT.getScalarType();
4119 
4120   switch (VT.getSimpleVT().SimpleTy) {
4121   case MVT::f32: {
4122     // This is as fast on some subtargets. However, we always have full rate f32
4123     // mad available which returns the same result as the separate operations
4124     // which we should prefer over fma. We can't use this if we want to support
4125     // denormals, so only report this in these cases.
4126     if (hasFP32Denormals(MF))
4127       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4128 
4129     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4130     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4131   }
4132   case MVT::f64:
4133     return true;
4134   case MVT::f16:
4135     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4136   default:
4137     break;
4138   }
4139 
4140   return false;
4141 }
4142 
4143 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4144                                    const SDNode *N) const {
4145   // TODO: Check future ftz flag
4146   // v_mad_f32/v_mac_f32 do not support denormals.
4147   EVT VT = N->getValueType(0);
4148   if (VT == MVT::f32)
4149     return !hasFP32Denormals(DAG.getMachineFunction());
4150   if (VT == MVT::f16) {
4151     return Subtarget->hasMadF16() &&
4152            !hasFP64FP16Denormals(DAG.getMachineFunction());
4153   }
4154 
4155   return false;
4156 }
4157 
4158 //===----------------------------------------------------------------------===//
4159 // Custom DAG Lowering Operations
4160 //===----------------------------------------------------------------------===//
4161 
4162 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4163 // wider vector type is legal.
4164 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4165                                              SelectionDAG &DAG) const {
4166   unsigned Opc = Op.getOpcode();
4167   EVT VT = Op.getValueType();
4168   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4169 
4170   SDValue Lo, Hi;
4171   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4172 
4173   SDLoc SL(Op);
4174   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4175                              Op->getFlags());
4176   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4177                              Op->getFlags());
4178 
4179   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4180 }
4181 
4182 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4183 // wider vector type is legal.
4184 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4185                                               SelectionDAG &DAG) const {
4186   unsigned Opc = Op.getOpcode();
4187   EVT VT = Op.getValueType();
4188   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4189 
4190   SDValue Lo0, Hi0;
4191   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4192   SDValue Lo1, Hi1;
4193   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4194 
4195   SDLoc SL(Op);
4196 
4197   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4198                              Op->getFlags());
4199   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4200                              Op->getFlags());
4201 
4202   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4203 }
4204 
4205 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4206                                               SelectionDAG &DAG) const {
4207   unsigned Opc = Op.getOpcode();
4208   EVT VT = Op.getValueType();
4209   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4210 
4211   SDValue Lo0, Hi0;
4212   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4213   SDValue Lo1, Hi1;
4214   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4215   SDValue Lo2, Hi2;
4216   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4217 
4218   SDLoc SL(Op);
4219 
4220   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4221                              Op->getFlags());
4222   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4223                              Op->getFlags());
4224 
4225   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4226 }
4227 
4228 
4229 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4230   switch (Op.getOpcode()) {
4231   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4232   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4233   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4234   case ISD::LOAD: {
4235     SDValue Result = LowerLOAD(Op, DAG);
4236     assert((!Result.getNode() ||
4237             Result.getNode()->getNumValues() == 2) &&
4238            "Load should return a value and a chain");
4239     return Result;
4240   }
4241 
4242   case ISD::FSIN:
4243   case ISD::FCOS:
4244     return LowerTrig(Op, DAG);
4245   case ISD::SELECT: return LowerSELECT(Op, DAG);
4246   case ISD::FDIV: return LowerFDIV(Op, DAG);
4247   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4248   case ISD::STORE: return LowerSTORE(Op, DAG);
4249   case ISD::GlobalAddress: {
4250     MachineFunction &MF = DAG.getMachineFunction();
4251     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4252     return LowerGlobalAddress(MFI, Op, DAG);
4253   }
4254   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4255   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4256   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4257   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4258   case ISD::INSERT_SUBVECTOR:
4259     return lowerINSERT_SUBVECTOR(Op, DAG);
4260   case ISD::INSERT_VECTOR_ELT:
4261     return lowerINSERT_VECTOR_ELT(Op, DAG);
4262   case ISD::EXTRACT_VECTOR_ELT:
4263     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4264   case ISD::VECTOR_SHUFFLE:
4265     return lowerVECTOR_SHUFFLE(Op, DAG);
4266   case ISD::BUILD_VECTOR:
4267     return lowerBUILD_VECTOR(Op, DAG);
4268   case ISD::FP_ROUND:
4269     return lowerFP_ROUND(Op, DAG);
4270   case ISD::TRAP:
4271     return lowerTRAP(Op, DAG);
4272   case ISD::DEBUGTRAP:
4273     return lowerDEBUGTRAP(Op, DAG);
4274   case ISD::FABS:
4275   case ISD::FNEG:
4276   case ISD::FCANONICALIZE:
4277   case ISD::BSWAP:
4278     return splitUnaryVectorOp(Op, DAG);
4279   case ISD::FMINNUM:
4280   case ISD::FMAXNUM:
4281     return lowerFMINNUM_FMAXNUM(Op, DAG);
4282   case ISD::FMA:
4283     return splitTernaryVectorOp(Op, DAG);
4284   case ISD::SHL:
4285   case ISD::SRA:
4286   case ISD::SRL:
4287   case ISD::ADD:
4288   case ISD::SUB:
4289   case ISD::MUL:
4290   case ISD::SMIN:
4291   case ISD::SMAX:
4292   case ISD::UMIN:
4293   case ISD::UMAX:
4294   case ISD::FADD:
4295   case ISD::FMUL:
4296   case ISD::FMINNUM_IEEE:
4297   case ISD::FMAXNUM_IEEE:
4298     return splitBinaryVectorOp(Op, DAG);
4299   }
4300   return SDValue();
4301 }
4302 
4303 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4304                                        const SDLoc &DL,
4305                                        SelectionDAG &DAG, bool Unpacked) {
4306   if (!LoadVT.isVector())
4307     return Result;
4308 
4309   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4310     // Truncate to v2i16/v4i16.
4311     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4312 
4313     // Workaround legalizer not scalarizing truncate after vector op
4314     // legalization byt not creating intermediate vector trunc.
4315     SmallVector<SDValue, 4> Elts;
4316     DAG.ExtractVectorElements(Result, Elts);
4317     for (SDValue &Elt : Elts)
4318       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4319 
4320     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4321 
4322     // Bitcast to original type (v2f16/v4f16).
4323     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4324   }
4325 
4326   // Cast back to the original packed type.
4327   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4328 }
4329 
4330 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4331                                               MemSDNode *M,
4332                                               SelectionDAG &DAG,
4333                                               ArrayRef<SDValue> Ops,
4334                                               bool IsIntrinsic) const {
4335   SDLoc DL(M);
4336 
4337   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4338   EVT LoadVT = M->getValueType(0);
4339 
4340   EVT EquivLoadVT = LoadVT;
4341   if (Unpacked && LoadVT.isVector()) {
4342     EquivLoadVT = LoadVT.isVector() ?
4343       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4344                        LoadVT.getVectorNumElements()) : LoadVT;
4345   }
4346 
4347   // Change from v4f16/v2f16 to EquivLoadVT.
4348   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4349 
4350   SDValue Load
4351     = DAG.getMemIntrinsicNode(
4352       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4353       VTList, Ops, M->getMemoryVT(),
4354       M->getMemOperand());
4355   if (!Unpacked) // Just adjusted the opcode.
4356     return Load;
4357 
4358   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4359 
4360   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4361 }
4362 
4363 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4364                                              SelectionDAG &DAG,
4365                                              ArrayRef<SDValue> Ops) const {
4366   SDLoc DL(M);
4367   EVT LoadVT = M->getValueType(0);
4368   EVT EltType = LoadVT.getScalarType();
4369   EVT IntVT = LoadVT.changeTypeToInteger();
4370 
4371   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4372 
4373   unsigned Opc =
4374       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4375 
4376   if (IsD16) {
4377     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4378   }
4379 
4380   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4381   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4382     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4383 
4384   if (isTypeLegal(LoadVT)) {
4385     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4386                                M->getMemOperand(), DAG);
4387   }
4388 
4389   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4390   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4391   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4392                                         M->getMemOperand(), DAG);
4393   return DAG.getMergeValues(
4394       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4395       DL);
4396 }
4397 
4398 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4399                                   SDNode *N, SelectionDAG &DAG) {
4400   EVT VT = N->getValueType(0);
4401   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4402   int CondCode = CD->getSExtValue();
4403   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4404       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4405     return DAG.getUNDEF(VT);
4406 
4407   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4408 
4409   SDValue LHS = N->getOperand(1);
4410   SDValue RHS = N->getOperand(2);
4411 
4412   SDLoc DL(N);
4413 
4414   EVT CmpVT = LHS.getValueType();
4415   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4416     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4417       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4418     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4419     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4420   }
4421 
4422   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4423 
4424   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4425   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4426 
4427   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4428                               DAG.getCondCode(CCOpcode));
4429   if (VT.bitsEq(CCVT))
4430     return SetCC;
4431   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4432 }
4433 
4434 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4435                                   SDNode *N, SelectionDAG &DAG) {
4436   EVT VT = N->getValueType(0);
4437   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4438 
4439   int CondCode = CD->getSExtValue();
4440   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4441       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4442     return DAG.getUNDEF(VT);
4443   }
4444 
4445   SDValue Src0 = N->getOperand(1);
4446   SDValue Src1 = N->getOperand(2);
4447   EVT CmpVT = Src0.getValueType();
4448   SDLoc SL(N);
4449 
4450   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4451     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4452     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4453   }
4454 
4455   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4456   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4457   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4458   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4459   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4460                               Src1, DAG.getCondCode(CCOpcode));
4461   if (VT.bitsEq(CCVT))
4462     return SetCC;
4463   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4464 }
4465 
4466 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4467                                     SelectionDAG &DAG) {
4468   EVT VT = N->getValueType(0);
4469   SDValue Src = N->getOperand(1);
4470   SDLoc SL(N);
4471 
4472   if (Src.getOpcode() == ISD::SETCC) {
4473     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4474     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4475                        Src.getOperand(1), Src.getOperand(2));
4476   }
4477   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4478     // (ballot 0) -> 0
4479     if (Arg->isNullValue())
4480       return DAG.getConstant(0, SL, VT);
4481 
4482     // (ballot 1) -> EXEC/EXEC_LO
4483     if (Arg->isOne()) {
4484       Register Exec;
4485       if (VT.getScalarSizeInBits() == 32)
4486         Exec = AMDGPU::EXEC_LO;
4487       else if (VT.getScalarSizeInBits() == 64)
4488         Exec = AMDGPU::EXEC;
4489       else
4490         return SDValue();
4491 
4492       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4493     }
4494   }
4495 
4496   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4497   // ISD::SETNE)
4498   return DAG.getNode(
4499       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4500       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4501 }
4502 
4503 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4504                                           SmallVectorImpl<SDValue> &Results,
4505                                           SelectionDAG &DAG) const {
4506   switch (N->getOpcode()) {
4507   case ISD::INSERT_VECTOR_ELT: {
4508     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4509       Results.push_back(Res);
4510     return;
4511   }
4512   case ISD::EXTRACT_VECTOR_ELT: {
4513     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4514       Results.push_back(Res);
4515     return;
4516   }
4517   case ISD::INTRINSIC_WO_CHAIN: {
4518     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4519     switch (IID) {
4520     case Intrinsic::amdgcn_cvt_pkrtz: {
4521       SDValue Src0 = N->getOperand(1);
4522       SDValue Src1 = N->getOperand(2);
4523       SDLoc SL(N);
4524       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4525                                 Src0, Src1);
4526       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4527       return;
4528     }
4529     case Intrinsic::amdgcn_cvt_pknorm_i16:
4530     case Intrinsic::amdgcn_cvt_pknorm_u16:
4531     case Intrinsic::amdgcn_cvt_pk_i16:
4532     case Intrinsic::amdgcn_cvt_pk_u16: {
4533       SDValue Src0 = N->getOperand(1);
4534       SDValue Src1 = N->getOperand(2);
4535       SDLoc SL(N);
4536       unsigned Opcode;
4537 
4538       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4539         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4540       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4541         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4542       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4543         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4544       else
4545         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4546 
4547       EVT VT = N->getValueType(0);
4548       if (isTypeLegal(VT))
4549         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4550       else {
4551         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4552         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4553       }
4554       return;
4555     }
4556     }
4557     break;
4558   }
4559   case ISD::INTRINSIC_W_CHAIN: {
4560     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4561       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4562         // FIXME: Hacky
4563         Results.push_back(Res.getOperand(0));
4564         Results.push_back(Res.getOperand(1));
4565       } else {
4566         Results.push_back(Res);
4567         Results.push_back(Res.getValue(1));
4568       }
4569       return;
4570     }
4571 
4572     break;
4573   }
4574   case ISD::SELECT: {
4575     SDLoc SL(N);
4576     EVT VT = N->getValueType(0);
4577     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4578     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4579     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4580 
4581     EVT SelectVT = NewVT;
4582     if (NewVT.bitsLT(MVT::i32)) {
4583       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4584       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4585       SelectVT = MVT::i32;
4586     }
4587 
4588     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4589                                     N->getOperand(0), LHS, RHS);
4590 
4591     if (NewVT != SelectVT)
4592       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4593     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4594     return;
4595   }
4596   case ISD::FNEG: {
4597     if (N->getValueType(0) != MVT::v2f16)
4598       break;
4599 
4600     SDLoc SL(N);
4601     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4602 
4603     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4604                              BC,
4605                              DAG.getConstant(0x80008000, SL, MVT::i32));
4606     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4607     return;
4608   }
4609   case ISD::FABS: {
4610     if (N->getValueType(0) != MVT::v2f16)
4611       break;
4612 
4613     SDLoc SL(N);
4614     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4615 
4616     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4617                              BC,
4618                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4619     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4620     return;
4621   }
4622   default:
4623     break;
4624   }
4625 }
4626 
4627 /// Helper function for LowerBRCOND
4628 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4629 
4630   SDNode *Parent = Value.getNode();
4631   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4632        I != E; ++I) {
4633 
4634     if (I.getUse().get() != Value)
4635       continue;
4636 
4637     if (I->getOpcode() == Opcode)
4638       return *I;
4639   }
4640   return nullptr;
4641 }
4642 
4643 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4644   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4645     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4646     case Intrinsic::amdgcn_if:
4647       return AMDGPUISD::IF;
4648     case Intrinsic::amdgcn_else:
4649       return AMDGPUISD::ELSE;
4650     case Intrinsic::amdgcn_loop:
4651       return AMDGPUISD::LOOP;
4652     case Intrinsic::amdgcn_end_cf:
4653       llvm_unreachable("should not occur");
4654     default:
4655       return 0;
4656     }
4657   }
4658 
4659   // break, if_break, else_break are all only used as inputs to loop, not
4660   // directly as branch conditions.
4661   return 0;
4662 }
4663 
4664 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4665   const Triple &TT = getTargetMachine().getTargetTriple();
4666   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4667           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4668          AMDGPU::shouldEmitConstantsToTextSection(TT);
4669 }
4670 
4671 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4672   // FIXME: Either avoid relying on address space here or change the default
4673   // address space for functions to avoid the explicit check.
4674   return (GV->getValueType()->isFunctionTy() ||
4675           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4676          !shouldEmitFixup(GV) &&
4677          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4678 }
4679 
4680 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4681   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4682 }
4683 
4684 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4685   if (!GV->hasExternalLinkage())
4686     return true;
4687 
4688   const auto OS = getTargetMachine().getTargetTriple().getOS();
4689   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4690 }
4691 
4692 /// This transforms the control flow intrinsics to get the branch destination as
4693 /// last parameter, also switches branch target with BR if the need arise
4694 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4695                                       SelectionDAG &DAG) const {
4696   SDLoc DL(BRCOND);
4697 
4698   SDNode *Intr = BRCOND.getOperand(1).getNode();
4699   SDValue Target = BRCOND.getOperand(2);
4700   SDNode *BR = nullptr;
4701   SDNode *SetCC = nullptr;
4702 
4703   if (Intr->getOpcode() == ISD::SETCC) {
4704     // As long as we negate the condition everything is fine
4705     SetCC = Intr;
4706     Intr = SetCC->getOperand(0).getNode();
4707 
4708   } else {
4709     // Get the target from BR if we don't negate the condition
4710     BR = findUser(BRCOND, ISD::BR);
4711     Target = BR->getOperand(1);
4712   }
4713 
4714   // FIXME: This changes the types of the intrinsics instead of introducing new
4715   // nodes with the correct types.
4716   // e.g. llvm.amdgcn.loop
4717 
4718   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4719   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4720 
4721   unsigned CFNode = isCFIntrinsic(Intr);
4722   if (CFNode == 0) {
4723     // This is a uniform branch so we don't need to legalize.
4724     return BRCOND;
4725   }
4726 
4727   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4728                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4729 
4730   assert(!SetCC ||
4731         (SetCC->getConstantOperandVal(1) == 1 &&
4732          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4733                                                              ISD::SETNE));
4734 
4735   // operands of the new intrinsic call
4736   SmallVector<SDValue, 4> Ops;
4737   if (HaveChain)
4738     Ops.push_back(BRCOND.getOperand(0));
4739 
4740   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4741   Ops.push_back(Target);
4742 
4743   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4744 
4745   // build the new intrinsic call
4746   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4747 
4748   if (!HaveChain) {
4749     SDValue Ops[] =  {
4750       SDValue(Result, 0),
4751       BRCOND.getOperand(0)
4752     };
4753 
4754     Result = DAG.getMergeValues(Ops, DL).getNode();
4755   }
4756 
4757   if (BR) {
4758     // Give the branch instruction our target
4759     SDValue Ops[] = {
4760       BR->getOperand(0),
4761       BRCOND.getOperand(2)
4762     };
4763     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4764     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4765   }
4766 
4767   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4768 
4769   // Copy the intrinsic results to registers
4770   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4771     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4772     if (!CopyToReg)
4773       continue;
4774 
4775     Chain = DAG.getCopyToReg(
4776       Chain, DL,
4777       CopyToReg->getOperand(1),
4778       SDValue(Result, i - 1),
4779       SDValue());
4780 
4781     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4782   }
4783 
4784   // Remove the old intrinsic from the chain
4785   DAG.ReplaceAllUsesOfValueWith(
4786     SDValue(Intr, Intr->getNumValues() - 1),
4787     Intr->getOperand(0));
4788 
4789   return Chain;
4790 }
4791 
4792 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4793                                           SelectionDAG &DAG) const {
4794   MVT VT = Op.getSimpleValueType();
4795   SDLoc DL(Op);
4796   // Checking the depth
4797   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4798     return DAG.getConstant(0, DL, VT);
4799 
4800   MachineFunction &MF = DAG.getMachineFunction();
4801   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4802   // Check for kernel and shader functions
4803   if (Info->isEntryFunction())
4804     return DAG.getConstant(0, DL, VT);
4805 
4806   MachineFrameInfo &MFI = MF.getFrameInfo();
4807   // There is a call to @llvm.returnaddress in this function
4808   MFI.setReturnAddressIsTaken(true);
4809 
4810   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4811   // Get the return address reg and mark it as an implicit live-in
4812   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4813 
4814   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4815 }
4816 
4817 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4818                                             SDValue Op,
4819                                             const SDLoc &DL,
4820                                             EVT VT) const {
4821   return Op.getValueType().bitsLE(VT) ?
4822       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4823     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4824                 DAG.getTargetConstant(0, DL, MVT::i32));
4825 }
4826 
4827 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4828   assert(Op.getValueType() == MVT::f16 &&
4829          "Do not know how to custom lower FP_ROUND for non-f16 type");
4830 
4831   SDValue Src = Op.getOperand(0);
4832   EVT SrcVT = Src.getValueType();
4833   if (SrcVT != MVT::f64)
4834     return Op;
4835 
4836   SDLoc DL(Op);
4837 
4838   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4839   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4840   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4841 }
4842 
4843 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4844                                                SelectionDAG &DAG) const {
4845   EVT VT = Op.getValueType();
4846   const MachineFunction &MF = DAG.getMachineFunction();
4847   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4848   bool IsIEEEMode = Info->getMode().IEEE;
4849 
4850   // FIXME: Assert during selection that this is only selected for
4851   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4852   // mode functions, but this happens to be OK since it's only done in cases
4853   // where there is known no sNaN.
4854   if (IsIEEEMode)
4855     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4856 
4857   if (VT == MVT::v4f16)
4858     return splitBinaryVectorOp(Op, DAG);
4859   return Op;
4860 }
4861 
4862 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4863   SDLoc SL(Op);
4864   SDValue Chain = Op.getOperand(0);
4865 
4866   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4867       !Subtarget->isTrapHandlerEnabled())
4868     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4869 
4870   MachineFunction &MF = DAG.getMachineFunction();
4871   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4872   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4873   assert(UserSGPR != AMDGPU::NoRegister);
4874   SDValue QueuePtr = CreateLiveInRegister(
4875     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4876   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4877   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4878                                    QueuePtr, SDValue());
4879   SDValue Ops[] = {
4880     ToReg,
4881     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4882     SGPR01,
4883     ToReg.getValue(1)
4884   };
4885   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4886 }
4887 
4888 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4889   SDLoc SL(Op);
4890   SDValue Chain = Op.getOperand(0);
4891   MachineFunction &MF = DAG.getMachineFunction();
4892 
4893   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4894       !Subtarget->isTrapHandlerEnabled()) {
4895     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4896                                      "debugtrap handler not supported",
4897                                      Op.getDebugLoc(),
4898                                      DS_Warning);
4899     LLVMContext &Ctx = MF.getFunction().getContext();
4900     Ctx.diagnose(NoTrap);
4901     return Chain;
4902   }
4903 
4904   SDValue Ops[] = {
4905     Chain,
4906     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4907   };
4908   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4909 }
4910 
4911 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4912                                              SelectionDAG &DAG) const {
4913   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4914   if (Subtarget->hasApertureRegs()) {
4915     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4916         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4917         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4918     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4919         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4920         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4921     unsigned Encoding =
4922         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4923         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4924         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4925 
4926     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4927     SDValue ApertureReg = SDValue(
4928         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4929     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4930     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4931   }
4932 
4933   MachineFunction &MF = DAG.getMachineFunction();
4934   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4935   Register UserSGPR = Info->getQueuePtrUserSGPR();
4936   assert(UserSGPR != AMDGPU::NoRegister);
4937 
4938   SDValue QueuePtr = CreateLiveInRegister(
4939     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4940 
4941   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4942   // private_segment_aperture_base_hi.
4943   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4944 
4945   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4946 
4947   // TODO: Use custom target PseudoSourceValue.
4948   // TODO: We should use the value from the IR intrinsic call, but it might not
4949   // be available and how do we get it?
4950   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4951   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4952                      MinAlign(64, StructOffset),
4953                      MachineMemOperand::MODereferenceable |
4954                          MachineMemOperand::MOInvariant);
4955 }
4956 
4957 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4958                                              SelectionDAG &DAG) const {
4959   SDLoc SL(Op);
4960   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4961 
4962   SDValue Src = ASC->getOperand(0);
4963   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4964 
4965   const AMDGPUTargetMachine &TM =
4966     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4967 
4968   // flat -> local/private
4969   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4970     unsigned DestAS = ASC->getDestAddressSpace();
4971 
4972     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4973         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4974       unsigned NullVal = TM.getNullPointerValue(DestAS);
4975       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4976       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4977       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4978 
4979       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4980                          NonNull, Ptr, SegmentNullPtr);
4981     }
4982   }
4983 
4984   // local/private -> flat
4985   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4986     unsigned SrcAS = ASC->getSrcAddressSpace();
4987 
4988     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4989         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4990       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4991       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4992 
4993       SDValue NonNull
4994         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4995 
4996       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4997       SDValue CvtPtr
4998         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4999 
5000       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5001                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5002                          FlatNullPtr);
5003     }
5004   }
5005 
5006   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5007       Src.getValueType() == MVT::i64)
5008     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5009 
5010   // global <-> flat are no-ops and never emitted.
5011 
5012   const MachineFunction &MF = DAG.getMachineFunction();
5013   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5014     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5015   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5016 
5017   return DAG.getUNDEF(ASC->getValueType(0));
5018 }
5019 
5020 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5021 // the small vector and inserting them into the big vector. That is better than
5022 // the default expansion of doing it via a stack slot. Even though the use of
5023 // the stack slot would be optimized away afterwards, the stack slot itself
5024 // remains.
5025 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5026                                                 SelectionDAG &DAG) const {
5027   SDValue Vec = Op.getOperand(0);
5028   SDValue Ins = Op.getOperand(1);
5029   SDValue Idx = Op.getOperand(2);
5030   EVT VecVT = Vec.getValueType();
5031   EVT InsVT = Ins.getValueType();
5032   EVT EltVT = VecVT.getVectorElementType();
5033   unsigned InsNumElts = InsVT.getVectorNumElements();
5034   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5035   SDLoc SL(Op);
5036 
5037   for (unsigned I = 0; I != InsNumElts; ++I) {
5038     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5039                               DAG.getConstant(I, SL, MVT::i32));
5040     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5041                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5042   }
5043   return Vec;
5044 }
5045 
5046 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5047                                                  SelectionDAG &DAG) const {
5048   SDValue Vec = Op.getOperand(0);
5049   SDValue InsVal = Op.getOperand(1);
5050   SDValue Idx = Op.getOperand(2);
5051   EVT VecVT = Vec.getValueType();
5052   EVT EltVT = VecVT.getVectorElementType();
5053   unsigned VecSize = VecVT.getSizeInBits();
5054   unsigned EltSize = EltVT.getSizeInBits();
5055 
5056 
5057   assert(VecSize <= 64);
5058 
5059   unsigned NumElts = VecVT.getVectorNumElements();
5060   SDLoc SL(Op);
5061   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5062 
5063   if (NumElts == 4 && EltSize == 16 && KIdx) {
5064     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5065 
5066     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5067                                  DAG.getConstant(0, SL, MVT::i32));
5068     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5069                                  DAG.getConstant(1, SL, MVT::i32));
5070 
5071     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5072     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5073 
5074     unsigned Idx = KIdx->getZExtValue();
5075     bool InsertLo = Idx < 2;
5076     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5077       InsertLo ? LoVec : HiVec,
5078       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5079       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5080 
5081     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5082 
5083     SDValue Concat = InsertLo ?
5084       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5085       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5086 
5087     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5088   }
5089 
5090   if (isa<ConstantSDNode>(Idx))
5091     return SDValue();
5092 
5093   MVT IntVT = MVT::getIntegerVT(VecSize);
5094 
5095   // Avoid stack access for dynamic indexing.
5096   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5097 
5098   // Create a congruent vector with the target value in each element so that
5099   // the required element can be masked and ORed into the target vector.
5100   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5101                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5102 
5103   assert(isPowerOf2_32(EltSize));
5104   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5105 
5106   // Convert vector index to bit-index.
5107   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5108 
5109   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5110   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5111                             DAG.getConstant(0xffff, SL, IntVT),
5112                             ScaledIdx);
5113 
5114   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5115   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5116                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5117 
5118   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5119   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5120 }
5121 
5122 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5123                                                   SelectionDAG &DAG) const {
5124   SDLoc SL(Op);
5125 
5126   EVT ResultVT = Op.getValueType();
5127   SDValue Vec = Op.getOperand(0);
5128   SDValue Idx = Op.getOperand(1);
5129   EVT VecVT = Vec.getValueType();
5130   unsigned VecSize = VecVT.getSizeInBits();
5131   EVT EltVT = VecVT.getVectorElementType();
5132   assert(VecSize <= 64);
5133 
5134   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5135 
5136   // Make sure we do any optimizations that will make it easier to fold
5137   // source modifiers before obscuring it with bit operations.
5138 
5139   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5140   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5141     return Combined;
5142 
5143   unsigned EltSize = EltVT.getSizeInBits();
5144   assert(isPowerOf2_32(EltSize));
5145 
5146   MVT IntVT = MVT::getIntegerVT(VecSize);
5147   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5148 
5149   // Convert vector index to bit-index (* EltSize)
5150   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5151 
5152   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5153   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5154 
5155   if (ResultVT == MVT::f16) {
5156     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5157     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5158   }
5159 
5160   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5161 }
5162 
5163 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5164   assert(Elt % 2 == 0);
5165   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5166 }
5167 
5168 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5169                                               SelectionDAG &DAG) const {
5170   SDLoc SL(Op);
5171   EVT ResultVT = Op.getValueType();
5172   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5173 
5174   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5175   EVT EltVT = PackVT.getVectorElementType();
5176   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5177 
5178   // vector_shuffle <0,1,6,7> lhs, rhs
5179   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5180   //
5181   // vector_shuffle <6,7,2,3> lhs, rhs
5182   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5183   //
5184   // vector_shuffle <6,7,0,1> lhs, rhs
5185   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5186 
5187   // Avoid scalarizing when both halves are reading from consecutive elements.
5188   SmallVector<SDValue, 4> Pieces;
5189   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5190     if (elementPairIsContiguous(SVN->getMask(), I)) {
5191       const int Idx = SVN->getMaskElt(I);
5192       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5193       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5194       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5195                                     PackVT, SVN->getOperand(VecIdx),
5196                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5197       Pieces.push_back(SubVec);
5198     } else {
5199       const int Idx0 = SVN->getMaskElt(I);
5200       const int Idx1 = SVN->getMaskElt(I + 1);
5201       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5202       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5203       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5204       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5205 
5206       SDValue Vec0 = SVN->getOperand(VecIdx0);
5207       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5208                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5209 
5210       SDValue Vec1 = SVN->getOperand(VecIdx1);
5211       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5212                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5213       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5214     }
5215   }
5216 
5217   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5218 }
5219 
5220 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5221                                             SelectionDAG &DAG) const {
5222   SDLoc SL(Op);
5223   EVT VT = Op.getValueType();
5224 
5225   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5226     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5227 
5228     // Turn into pair of packed build_vectors.
5229     // TODO: Special case for constants that can be materialized with s_mov_b64.
5230     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5231                                     { Op.getOperand(0), Op.getOperand(1) });
5232     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5233                                     { Op.getOperand(2), Op.getOperand(3) });
5234 
5235     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5236     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5237 
5238     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5239     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5240   }
5241 
5242   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5243   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5244 
5245   SDValue Lo = Op.getOperand(0);
5246   SDValue Hi = Op.getOperand(1);
5247 
5248   // Avoid adding defined bits with the zero_extend.
5249   if (Hi.isUndef()) {
5250     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5251     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5252     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5253   }
5254 
5255   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5256   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5257 
5258   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5259                               DAG.getConstant(16, SL, MVT::i32));
5260   if (Lo.isUndef())
5261     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5262 
5263   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5264   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5265 
5266   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5267   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5268 }
5269 
5270 bool
5271 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5272   // We can fold offsets for anything that doesn't require a GOT relocation.
5273   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5274           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5275           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5276          !shouldEmitGOTReloc(GA->getGlobal());
5277 }
5278 
5279 static SDValue
5280 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5281                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5282                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5283   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5284   // lowered to the following code sequence:
5285   //
5286   // For constant address space:
5287   //   s_getpc_b64 s[0:1]
5288   //   s_add_u32 s0, s0, $symbol
5289   //   s_addc_u32 s1, s1, 0
5290   //
5291   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5292   //   a fixup or relocation is emitted to replace $symbol with a literal
5293   //   constant, which is a pc-relative offset from the encoding of the $symbol
5294   //   operand to the global variable.
5295   //
5296   // For global address space:
5297   //   s_getpc_b64 s[0:1]
5298   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5299   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5300   //
5301   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5302   //   fixups or relocations are emitted to replace $symbol@*@lo and
5303   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5304   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5305   //   operand to the global variable.
5306   //
5307   // What we want here is an offset from the value returned by s_getpc
5308   // (which is the address of the s_add_u32 instruction) to the global
5309   // variable, but since the encoding of $symbol starts 4 bytes after the start
5310   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5311   // small. This requires us to add 4 to the global variable offset in order to
5312   // compute the correct address.
5313   SDValue PtrLo =
5314       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5315   SDValue PtrHi;
5316   if (GAFlags == SIInstrInfo::MO_NONE) {
5317     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5318   } else {
5319     PtrHi =
5320         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5321   }
5322   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5323 }
5324 
5325 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5326                                              SDValue Op,
5327                                              SelectionDAG &DAG) const {
5328   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5329   const GlobalValue *GV = GSD->getGlobal();
5330   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5331        shouldUseLDSConstAddress(GV)) ||
5332       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5333       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5334     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5335 
5336   SDLoc DL(GSD);
5337   EVT PtrVT = Op.getValueType();
5338 
5339   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5340     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5341                                             SIInstrInfo::MO_ABS32_LO);
5342     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5343   }
5344 
5345   if (shouldEmitFixup(GV))
5346     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5347   else if (shouldEmitPCReloc(GV))
5348     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5349                                    SIInstrInfo::MO_REL32);
5350 
5351   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5352                                             SIInstrInfo::MO_GOTPCREL32);
5353 
5354   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5355   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5356   const DataLayout &DataLayout = DAG.getDataLayout();
5357   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5358   MachinePointerInfo PtrInfo
5359     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5360 
5361   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5362                      MachineMemOperand::MODereferenceable |
5363                          MachineMemOperand::MOInvariant);
5364 }
5365 
5366 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5367                                    const SDLoc &DL, SDValue V) const {
5368   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5369   // the destination register.
5370   //
5371   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5372   // so we will end up with redundant moves to m0.
5373   //
5374   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5375 
5376   // A Null SDValue creates a glue result.
5377   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5378                                   V, Chain);
5379   return SDValue(M0, 0);
5380 }
5381 
5382 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5383                                                  SDValue Op,
5384                                                  MVT VT,
5385                                                  unsigned Offset) const {
5386   SDLoc SL(Op);
5387   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5388                                            DAG.getEntryNode(), Offset, 4, false);
5389   // The local size values will have the hi 16-bits as zero.
5390   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5391                      DAG.getValueType(VT));
5392 }
5393 
5394 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5395                                         EVT VT) {
5396   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5397                                       "non-hsa intrinsic with hsa target",
5398                                       DL.getDebugLoc());
5399   DAG.getContext()->diagnose(BadIntrin);
5400   return DAG.getUNDEF(VT);
5401 }
5402 
5403 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5404                                          EVT VT) {
5405   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5406                                       "intrinsic not supported on subtarget",
5407                                       DL.getDebugLoc());
5408   DAG.getContext()->diagnose(BadIntrin);
5409   return DAG.getUNDEF(VT);
5410 }
5411 
5412 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5413                                     ArrayRef<SDValue> Elts) {
5414   assert(!Elts.empty());
5415   MVT Type;
5416   unsigned NumElts;
5417 
5418   if (Elts.size() == 1) {
5419     Type = MVT::f32;
5420     NumElts = 1;
5421   } else if (Elts.size() == 2) {
5422     Type = MVT::v2f32;
5423     NumElts = 2;
5424   } else if (Elts.size() == 3) {
5425     Type = MVT::v3f32;
5426     NumElts = 3;
5427   } else if (Elts.size() <= 4) {
5428     Type = MVT::v4f32;
5429     NumElts = 4;
5430   } else if (Elts.size() <= 8) {
5431     Type = MVT::v8f32;
5432     NumElts = 8;
5433   } else {
5434     assert(Elts.size() <= 16);
5435     Type = MVT::v16f32;
5436     NumElts = 16;
5437   }
5438 
5439   SmallVector<SDValue, 16> VecElts(NumElts);
5440   for (unsigned i = 0; i < Elts.size(); ++i) {
5441     SDValue Elt = Elts[i];
5442     if (Elt.getValueType() != MVT::f32)
5443       Elt = DAG.getBitcast(MVT::f32, Elt);
5444     VecElts[i] = Elt;
5445   }
5446   for (unsigned i = Elts.size(); i < NumElts; ++i)
5447     VecElts[i] = DAG.getUNDEF(MVT::f32);
5448 
5449   if (NumElts == 1)
5450     return VecElts[0];
5451   return DAG.getBuildVector(Type, DL, VecElts);
5452 }
5453 
5454 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5455                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5456   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5457 
5458   uint64_t Value = CachePolicyConst->getZExtValue();
5459   SDLoc DL(CachePolicy);
5460   if (GLC) {
5461     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5462     Value &= ~(uint64_t)0x1;
5463   }
5464   if (SLC) {
5465     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5466     Value &= ~(uint64_t)0x2;
5467   }
5468   if (DLC) {
5469     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5470     Value &= ~(uint64_t)0x4;
5471   }
5472 
5473   return Value == 0;
5474 }
5475 
5476 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5477                               SDValue Src, int ExtraElts) {
5478   EVT SrcVT = Src.getValueType();
5479 
5480   SmallVector<SDValue, 8> Elts;
5481 
5482   if (SrcVT.isVector())
5483     DAG.ExtractVectorElements(Src, Elts);
5484   else
5485     Elts.push_back(Src);
5486 
5487   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5488   while (ExtraElts--)
5489     Elts.push_back(Undef);
5490 
5491   return DAG.getBuildVector(CastVT, DL, Elts);
5492 }
5493 
5494 // Re-construct the required return value for a image load intrinsic.
5495 // This is more complicated due to the optional use TexFailCtrl which means the required
5496 // return type is an aggregate
5497 static SDValue constructRetValue(SelectionDAG &DAG,
5498                                  MachineSDNode *Result,
5499                                  ArrayRef<EVT> ResultTypes,
5500                                  bool IsTexFail, bool Unpacked, bool IsD16,
5501                                  int DMaskPop, int NumVDataDwords,
5502                                  const SDLoc &DL, LLVMContext &Context) {
5503   // Determine the required return type. This is the same regardless of IsTexFail flag
5504   EVT ReqRetVT = ResultTypes[0];
5505   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5506   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5507     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5508 
5509   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5510     DMaskPop : (DMaskPop + 1) / 2;
5511 
5512   MVT DataDwordVT = NumDataDwords == 1 ?
5513     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5514 
5515   MVT MaskPopVT = MaskPopDwords == 1 ?
5516     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5517 
5518   SDValue Data(Result, 0);
5519   SDValue TexFail;
5520 
5521   if (IsTexFail) {
5522     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5523     if (MaskPopVT.isVector()) {
5524       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5525                          SDValue(Result, 0), ZeroIdx);
5526     } else {
5527       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5528                          SDValue(Result, 0), ZeroIdx);
5529     }
5530 
5531     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5532                           SDValue(Result, 0),
5533                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5534   }
5535 
5536   if (DataDwordVT.isVector())
5537     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5538                           NumDataDwords - MaskPopDwords);
5539 
5540   if (IsD16)
5541     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5542 
5543   if (!ReqRetVT.isVector())
5544     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5545 
5546   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5547 
5548   if (TexFail)
5549     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5550 
5551   if (Result->getNumValues() == 1)
5552     return Data;
5553 
5554   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5555 }
5556 
5557 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5558                          SDValue *LWE, bool &IsTexFail) {
5559   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5560 
5561   uint64_t Value = TexFailCtrlConst->getZExtValue();
5562   if (Value) {
5563     IsTexFail = true;
5564   }
5565 
5566   SDLoc DL(TexFailCtrlConst);
5567   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5568   Value &= ~(uint64_t)0x1;
5569   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5570   Value &= ~(uint64_t)0x2;
5571 
5572   return Value == 0;
5573 }
5574 
5575 SDValue SITargetLowering::lowerImage(SDValue Op,
5576                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5577                                      SelectionDAG &DAG) const {
5578   SDLoc DL(Op);
5579   MachineFunction &MF = DAG.getMachineFunction();
5580   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5581   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5582       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5583   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5584   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5585       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5586   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5587       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5588   unsigned IntrOpcode = Intr->BaseOpcode;
5589   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5590 
5591   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5592   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5593   bool IsD16 = false;
5594   bool IsA16 = false;
5595   SDValue VData;
5596   int NumVDataDwords;
5597   bool AdjustRetType = false;
5598 
5599   unsigned AddrIdx; // Index of first address argument
5600   unsigned DMask;
5601   unsigned DMaskLanes = 0;
5602 
5603   if (BaseOpcode->Atomic) {
5604     VData = Op.getOperand(2);
5605 
5606     bool Is64Bit = VData.getValueType() == MVT::i64;
5607     if (BaseOpcode->AtomicX2) {
5608       SDValue VData2 = Op.getOperand(3);
5609       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5610                                  {VData, VData2});
5611       if (Is64Bit)
5612         VData = DAG.getBitcast(MVT::v4i32, VData);
5613 
5614       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5615       DMask = Is64Bit ? 0xf : 0x3;
5616       NumVDataDwords = Is64Bit ? 4 : 2;
5617       AddrIdx = 4;
5618     } else {
5619       DMask = Is64Bit ? 0x3 : 0x1;
5620       NumVDataDwords = Is64Bit ? 2 : 1;
5621       AddrIdx = 3;
5622     }
5623   } else {
5624     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5625     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5626     DMask = DMaskConst->getZExtValue();
5627     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5628 
5629     if (BaseOpcode->Store) {
5630       VData = Op.getOperand(2);
5631 
5632       MVT StoreVT = VData.getSimpleValueType();
5633       if (StoreVT.getScalarType() == MVT::f16) {
5634         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5635           return Op; // D16 is unsupported for this instruction
5636 
5637         IsD16 = true;
5638         VData = handleD16VData(VData, DAG);
5639       }
5640 
5641       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5642     } else {
5643       // Work out the num dwords based on the dmask popcount and underlying type
5644       // and whether packing is supported.
5645       MVT LoadVT = ResultTypes[0].getSimpleVT();
5646       if (LoadVT.getScalarType() == MVT::f16) {
5647         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5648           return Op; // D16 is unsupported for this instruction
5649 
5650         IsD16 = true;
5651       }
5652 
5653       // Confirm that the return type is large enough for the dmask specified
5654       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5655           (!LoadVT.isVector() && DMaskLanes > 1))
5656           return Op;
5657 
5658       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5659         NumVDataDwords = (DMaskLanes + 1) / 2;
5660       else
5661         NumVDataDwords = DMaskLanes;
5662 
5663       AdjustRetType = true;
5664     }
5665 
5666     AddrIdx = DMaskIdx + 1;
5667   }
5668 
5669   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5670   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5671   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5672   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5673                        NumCoords + NumLCM;
5674   unsigned NumMIVAddrs = NumVAddrs;
5675 
5676   SmallVector<SDValue, 4> VAddrs;
5677 
5678   // Optimize _L to _LZ when _L is zero
5679   if (LZMappingInfo) {
5680     if (auto ConstantLod =
5681          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5682       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5683         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5684         NumMIVAddrs--;               // remove 'lod'
5685       }
5686     }
5687   }
5688 
5689   // Optimize _mip away, when 'lod' is zero
5690   if (MIPMappingInfo) {
5691     if (auto ConstantLod =
5692          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5693       if (ConstantLod->isNullValue()) {
5694         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5695         NumMIVAddrs--;               // remove 'lod'
5696       }
5697     }
5698   }
5699 
5700   // Check for 16 bit addresses and pack if true.
5701   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5702   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5703   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5704   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5705     // Illegal to use a16 images
5706     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5707       return Op;
5708 
5709     IsA16 = true;
5710     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5711     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5712       SDValue AddrLo;
5713       // Push back extra arguments.
5714       if (i < DimIdx) {
5715         AddrLo = Op.getOperand(i);
5716       } else {
5717         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5718         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5719         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5720             ((NumGradients / 2) % 2 == 1 &&
5721             (i == DimIdx + (NumGradients / 2) - 1 ||
5722              i == DimIdx + NumGradients - 1))) {
5723           AddrLo = Op.getOperand(i);
5724           if (AddrLo.getValueType() != MVT::i16)
5725             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5726           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5727         } else {
5728           AddrLo = DAG.getBuildVector(VectorVT, DL,
5729                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5730           i++;
5731         }
5732         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5733       }
5734       VAddrs.push_back(AddrLo);
5735     }
5736   } else {
5737     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5738       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5739   }
5740 
5741   // If the register allocator cannot place the address registers contiguously
5742   // without introducing moves, then using the non-sequential address encoding
5743   // is always preferable, since it saves VALU instructions and is usually a
5744   // wash in terms of code size or even better.
5745   //
5746   // However, we currently have no way of hinting to the register allocator that
5747   // MIMG addresses should be placed contiguously when it is possible to do so,
5748   // so force non-NSA for the common 2-address case as a heuristic.
5749   //
5750   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5751   // allocation when possible.
5752   bool UseNSA =
5753       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5754   SDValue VAddr;
5755   if (!UseNSA)
5756     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5757 
5758   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5759   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5760   unsigned CtrlIdx; // Index of texfailctrl argument
5761   SDValue Unorm;
5762   if (!BaseOpcode->Sampler) {
5763     Unorm = True;
5764     CtrlIdx = AddrIdx + NumVAddrs + 1;
5765   } else {
5766     auto UnormConst =
5767         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5768 
5769     Unorm = UnormConst->getZExtValue() ? True : False;
5770     CtrlIdx = AddrIdx + NumVAddrs + 3;
5771   }
5772 
5773   SDValue TFE;
5774   SDValue LWE;
5775   SDValue TexFail = Op.getOperand(CtrlIdx);
5776   bool IsTexFail = false;
5777   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5778     return Op;
5779 
5780   if (IsTexFail) {
5781     if (!DMaskLanes) {
5782       // Expecting to get an error flag since TFC is on - and dmask is 0
5783       // Force dmask to be at least 1 otherwise the instruction will fail
5784       DMask = 0x1;
5785       DMaskLanes = 1;
5786       NumVDataDwords = 1;
5787     }
5788     NumVDataDwords += 1;
5789     AdjustRetType = true;
5790   }
5791 
5792   // Has something earlier tagged that the return type needs adjusting
5793   // This happens if the instruction is a load or has set TexFailCtrl flags
5794   if (AdjustRetType) {
5795     // NumVDataDwords reflects the true number of dwords required in the return type
5796     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5797       // This is a no-op load. This can be eliminated
5798       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5799       if (isa<MemSDNode>(Op))
5800         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5801       return Undef;
5802     }
5803 
5804     EVT NewVT = NumVDataDwords > 1 ?
5805                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5806                 : MVT::i32;
5807 
5808     ResultTypes[0] = NewVT;
5809     if (ResultTypes.size() == 3) {
5810       // Original result was aggregate type used for TexFailCtrl results
5811       // The actual instruction returns as a vector type which has now been
5812       // created. Remove the aggregate result.
5813       ResultTypes.erase(&ResultTypes[1]);
5814     }
5815   }
5816 
5817   SDValue GLC;
5818   SDValue SLC;
5819   SDValue DLC;
5820   if (BaseOpcode->Atomic) {
5821     GLC = True; // TODO no-return optimization
5822     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5823                           IsGFX10 ? &DLC : nullptr))
5824       return Op;
5825   } else {
5826     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5827                           IsGFX10 ? &DLC : nullptr))
5828       return Op;
5829   }
5830 
5831   SmallVector<SDValue, 26> Ops;
5832   if (BaseOpcode->Store || BaseOpcode->Atomic)
5833     Ops.push_back(VData); // vdata
5834   if (UseNSA) {
5835     for (const SDValue &Addr : VAddrs)
5836       Ops.push_back(Addr);
5837   } else {
5838     Ops.push_back(VAddr);
5839   }
5840   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5841   if (BaseOpcode->Sampler)
5842     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5843   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5844   if (IsGFX10)
5845     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5846   Ops.push_back(Unorm);
5847   if (IsGFX10)
5848     Ops.push_back(DLC);
5849   Ops.push_back(GLC);
5850   Ops.push_back(SLC);
5851   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5852                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5853   if (IsGFX10)
5854     Ops.push_back(IsA16 ? True : False);
5855   Ops.push_back(TFE);
5856   Ops.push_back(LWE);
5857   if (!IsGFX10)
5858     Ops.push_back(DimInfo->DA ? True : False);
5859   if (BaseOpcode->HasD16)
5860     Ops.push_back(IsD16 ? True : False);
5861   if (isa<MemSDNode>(Op))
5862     Ops.push_back(Op.getOperand(0)); // chain
5863 
5864   int NumVAddrDwords =
5865       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5866   int Opcode = -1;
5867 
5868   if (IsGFX10) {
5869     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5870                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5871                                           : AMDGPU::MIMGEncGfx10Default,
5872                                    NumVDataDwords, NumVAddrDwords);
5873   } else {
5874     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5875       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5876                                      NumVDataDwords, NumVAddrDwords);
5877     if (Opcode == -1)
5878       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5879                                      NumVDataDwords, NumVAddrDwords);
5880   }
5881   assert(Opcode != -1);
5882 
5883   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5884   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5885     MachineMemOperand *MemRef = MemOp->getMemOperand();
5886     DAG.setNodeMemRefs(NewNode, {MemRef});
5887   }
5888 
5889   if (BaseOpcode->AtomicX2) {
5890     SmallVector<SDValue, 1> Elt;
5891     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5892     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5893   } else if (!BaseOpcode->Store) {
5894     return constructRetValue(DAG, NewNode,
5895                              OrigResultTypes, IsTexFail,
5896                              Subtarget->hasUnpackedD16VMem(), IsD16,
5897                              DMaskLanes, NumVDataDwords, DL,
5898                              *DAG.getContext());
5899   }
5900 
5901   return SDValue(NewNode, 0);
5902 }
5903 
5904 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5905                                        SDValue Offset, SDValue CachePolicy,
5906                                        SelectionDAG &DAG) const {
5907   MachineFunction &MF = DAG.getMachineFunction();
5908 
5909   const DataLayout &DataLayout = DAG.getDataLayout();
5910   Align Alignment =
5911       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
5912 
5913   MachineMemOperand *MMO = MF.getMachineMemOperand(
5914       MachinePointerInfo(),
5915       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5916           MachineMemOperand::MOInvariant,
5917       VT.getStoreSize(), Alignment);
5918 
5919   if (!Offset->isDivergent()) {
5920     SDValue Ops[] = {
5921         Rsrc,
5922         Offset, // Offset
5923         CachePolicy
5924     };
5925 
5926     // Widen vec3 load to vec4.
5927     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5928       EVT WidenedVT =
5929           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5930       auto WidenedOp = DAG.getMemIntrinsicNode(
5931           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5932           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5933       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5934                                    DAG.getVectorIdxConstant(0, DL));
5935       return Subvector;
5936     }
5937 
5938     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5939                                    DAG.getVTList(VT), Ops, VT, MMO);
5940   }
5941 
5942   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5943   // assume that the buffer is unswizzled.
5944   SmallVector<SDValue, 4> Loads;
5945   unsigned NumLoads = 1;
5946   MVT LoadVT = VT.getSimpleVT();
5947   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5948   assert((LoadVT.getScalarType() == MVT::i32 ||
5949           LoadVT.getScalarType() == MVT::f32));
5950 
5951   if (NumElts == 8 || NumElts == 16) {
5952     NumLoads = NumElts / 4;
5953     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5954   }
5955 
5956   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5957   SDValue Ops[] = {
5958       DAG.getEntryNode(),                               // Chain
5959       Rsrc,                                             // rsrc
5960       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5961       {},                                               // voffset
5962       {},                                               // soffset
5963       {},                                               // offset
5964       CachePolicy,                                      // cachepolicy
5965       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5966   };
5967 
5968   // Use the alignment to ensure that the required offsets will fit into the
5969   // immediate offsets.
5970   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5971 
5972   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5973   for (unsigned i = 0; i < NumLoads; ++i) {
5974     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5975     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5976                                         LoadVT, MMO, DAG));
5977   }
5978 
5979   if (NumElts == 8 || NumElts == 16)
5980     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5981 
5982   return Loads[0];
5983 }
5984 
5985 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5986                                                   SelectionDAG &DAG) const {
5987   MachineFunction &MF = DAG.getMachineFunction();
5988   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5989 
5990   EVT VT = Op.getValueType();
5991   SDLoc DL(Op);
5992   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5993 
5994   // TODO: Should this propagate fast-math-flags?
5995 
5996   switch (IntrinsicID) {
5997   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5998     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5999       return emitNonHSAIntrinsicError(DAG, DL, VT);
6000     return getPreloadedValue(DAG, *MFI, VT,
6001                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6002   }
6003   case Intrinsic::amdgcn_dispatch_ptr:
6004   case Intrinsic::amdgcn_queue_ptr: {
6005     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6006       DiagnosticInfoUnsupported BadIntrin(
6007           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6008           DL.getDebugLoc());
6009       DAG.getContext()->diagnose(BadIntrin);
6010       return DAG.getUNDEF(VT);
6011     }
6012 
6013     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6014       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6015     return getPreloadedValue(DAG, *MFI, VT, RegID);
6016   }
6017   case Intrinsic::amdgcn_implicitarg_ptr: {
6018     if (MFI->isEntryFunction())
6019       return getImplicitArgPtr(DAG, DL);
6020     return getPreloadedValue(DAG, *MFI, VT,
6021                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6022   }
6023   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6024     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6025       // This only makes sense to call in a kernel, so just lower to null.
6026       return DAG.getConstant(0, DL, VT);
6027     }
6028 
6029     return getPreloadedValue(DAG, *MFI, VT,
6030                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6031   }
6032   case Intrinsic::amdgcn_dispatch_id: {
6033     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6034   }
6035   case Intrinsic::amdgcn_rcp:
6036     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6037   case Intrinsic::amdgcn_rsq:
6038     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6039   case Intrinsic::amdgcn_rsq_legacy:
6040     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6041       return emitRemovedIntrinsicError(DAG, DL, VT);
6042     return SDValue();
6043   case Intrinsic::amdgcn_rcp_legacy:
6044     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6045       return emitRemovedIntrinsicError(DAG, DL, VT);
6046     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6047   case Intrinsic::amdgcn_rsq_clamp: {
6048     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6049       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6050 
6051     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6052     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6053     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6054 
6055     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6056     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6057                               DAG.getConstantFP(Max, DL, VT));
6058     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6059                        DAG.getConstantFP(Min, DL, VT));
6060   }
6061   case Intrinsic::r600_read_ngroups_x:
6062     if (Subtarget->isAmdHsaOS())
6063       return emitNonHSAIntrinsicError(DAG, DL, VT);
6064 
6065     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6066                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6067   case Intrinsic::r600_read_ngroups_y:
6068     if (Subtarget->isAmdHsaOS())
6069       return emitNonHSAIntrinsicError(DAG, DL, VT);
6070 
6071     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6072                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6073   case Intrinsic::r600_read_ngroups_z:
6074     if (Subtarget->isAmdHsaOS())
6075       return emitNonHSAIntrinsicError(DAG, DL, VT);
6076 
6077     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6078                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6079   case Intrinsic::r600_read_global_size_x:
6080     if (Subtarget->isAmdHsaOS())
6081       return emitNonHSAIntrinsicError(DAG, DL, VT);
6082 
6083     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6084                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6085   case Intrinsic::r600_read_global_size_y:
6086     if (Subtarget->isAmdHsaOS())
6087       return emitNonHSAIntrinsicError(DAG, DL, VT);
6088 
6089     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6090                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6091   case Intrinsic::r600_read_global_size_z:
6092     if (Subtarget->isAmdHsaOS())
6093       return emitNonHSAIntrinsicError(DAG, DL, VT);
6094 
6095     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6096                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6097   case Intrinsic::r600_read_local_size_x:
6098     if (Subtarget->isAmdHsaOS())
6099       return emitNonHSAIntrinsicError(DAG, DL, VT);
6100 
6101     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6102                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6103   case Intrinsic::r600_read_local_size_y:
6104     if (Subtarget->isAmdHsaOS())
6105       return emitNonHSAIntrinsicError(DAG, DL, VT);
6106 
6107     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6108                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6109   case Intrinsic::r600_read_local_size_z:
6110     if (Subtarget->isAmdHsaOS())
6111       return emitNonHSAIntrinsicError(DAG, DL, VT);
6112 
6113     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6114                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6115   case Intrinsic::amdgcn_workgroup_id_x:
6116     return getPreloadedValue(DAG, *MFI, VT,
6117                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6118   case Intrinsic::amdgcn_workgroup_id_y:
6119     return getPreloadedValue(DAG, *MFI, VT,
6120                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6121   case Intrinsic::amdgcn_workgroup_id_z:
6122     return getPreloadedValue(DAG, *MFI, VT,
6123                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6124   case Intrinsic::amdgcn_workitem_id_x:
6125     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6126                           SDLoc(DAG.getEntryNode()),
6127                           MFI->getArgInfo().WorkItemIDX);
6128   case Intrinsic::amdgcn_workitem_id_y:
6129     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6130                           SDLoc(DAG.getEntryNode()),
6131                           MFI->getArgInfo().WorkItemIDY);
6132   case Intrinsic::amdgcn_workitem_id_z:
6133     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6134                           SDLoc(DAG.getEntryNode()),
6135                           MFI->getArgInfo().WorkItemIDZ);
6136   case Intrinsic::amdgcn_wavefrontsize:
6137     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6138                            SDLoc(Op), MVT::i32);
6139   case Intrinsic::amdgcn_s_buffer_load: {
6140     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6141     SDValue GLC;
6142     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6143     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6144                           IsGFX10 ? &DLC : nullptr))
6145       return Op;
6146     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6147                         DAG);
6148   }
6149   case Intrinsic::amdgcn_fdiv_fast:
6150     return lowerFDIV_FAST(Op, DAG);
6151   case Intrinsic::amdgcn_sin:
6152     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6153 
6154   case Intrinsic::amdgcn_cos:
6155     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6156 
6157   case Intrinsic::amdgcn_mul_u24:
6158     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6159   case Intrinsic::amdgcn_mul_i24:
6160     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6161 
6162   case Intrinsic::amdgcn_log_clamp: {
6163     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6164       return SDValue();
6165 
6166     DiagnosticInfoUnsupported BadIntrin(
6167       MF.getFunction(), "intrinsic not supported on subtarget",
6168       DL.getDebugLoc());
6169       DAG.getContext()->diagnose(BadIntrin);
6170       return DAG.getUNDEF(VT);
6171   }
6172   case Intrinsic::amdgcn_ldexp:
6173     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6174                        Op.getOperand(1), Op.getOperand(2));
6175 
6176   case Intrinsic::amdgcn_fract:
6177     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6178 
6179   case Intrinsic::amdgcn_class:
6180     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6181                        Op.getOperand(1), Op.getOperand(2));
6182   case Intrinsic::amdgcn_div_fmas:
6183     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6184                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6185                        Op.getOperand(4));
6186 
6187   case Intrinsic::amdgcn_div_fixup:
6188     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6189                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6190 
6191   case Intrinsic::amdgcn_trig_preop:
6192     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
6193                        Op.getOperand(1), Op.getOperand(2));
6194   case Intrinsic::amdgcn_div_scale: {
6195     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6196 
6197     // Translate to the operands expected by the machine instruction. The
6198     // first parameter must be the same as the first instruction.
6199     SDValue Numerator = Op.getOperand(1);
6200     SDValue Denominator = Op.getOperand(2);
6201 
6202     // Note this order is opposite of the machine instruction's operations,
6203     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6204     // intrinsic has the numerator as the first operand to match a normal
6205     // division operation.
6206 
6207     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6208 
6209     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6210                        Denominator, Numerator);
6211   }
6212   case Intrinsic::amdgcn_icmp: {
6213     // There is a Pat that handles this variant, so return it as-is.
6214     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6215         Op.getConstantOperandVal(2) == 0 &&
6216         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6217       return Op;
6218     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6219   }
6220   case Intrinsic::amdgcn_fcmp: {
6221     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6222   }
6223   case Intrinsic::amdgcn_ballot:
6224     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6225   case Intrinsic::amdgcn_fmed3:
6226     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6227                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6228   case Intrinsic::amdgcn_fdot2:
6229     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6230                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6231                        Op.getOperand(4));
6232   case Intrinsic::amdgcn_fmul_legacy:
6233     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6234                        Op.getOperand(1), Op.getOperand(2));
6235   case Intrinsic::amdgcn_sffbh:
6236     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6237   case Intrinsic::amdgcn_sbfe:
6238     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6239                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6240   case Intrinsic::amdgcn_ubfe:
6241     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6242                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6243   case Intrinsic::amdgcn_cvt_pkrtz:
6244   case Intrinsic::amdgcn_cvt_pknorm_i16:
6245   case Intrinsic::amdgcn_cvt_pknorm_u16:
6246   case Intrinsic::amdgcn_cvt_pk_i16:
6247   case Intrinsic::amdgcn_cvt_pk_u16: {
6248     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6249     EVT VT = Op.getValueType();
6250     unsigned Opcode;
6251 
6252     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6253       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6254     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6255       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6256     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6257       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6258     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6259       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6260     else
6261       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6262 
6263     if (isTypeLegal(VT))
6264       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6265 
6266     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6267                                Op.getOperand(1), Op.getOperand(2));
6268     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6269   }
6270   case Intrinsic::amdgcn_fmad_ftz:
6271     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6272                        Op.getOperand(2), Op.getOperand(3));
6273 
6274   case Intrinsic::amdgcn_if_break:
6275     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6276                                       Op->getOperand(1), Op->getOperand(2)), 0);
6277 
6278   case Intrinsic::amdgcn_groupstaticsize: {
6279     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6280     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6281       return Op;
6282 
6283     const Module *M = MF.getFunction().getParent();
6284     const GlobalValue *GV =
6285         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6286     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6287                                             SIInstrInfo::MO_ABS32_LO);
6288     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6289   }
6290   case Intrinsic::amdgcn_is_shared:
6291   case Intrinsic::amdgcn_is_private: {
6292     SDLoc SL(Op);
6293     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6294       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6295     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6296     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6297                                  Op.getOperand(1));
6298 
6299     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6300                                 DAG.getConstant(1, SL, MVT::i32));
6301     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6302   }
6303   case Intrinsic::amdgcn_alignbit:
6304     return DAG.getNode(ISD::FSHR, DL, VT,
6305                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6306   case Intrinsic::amdgcn_reloc_constant: {
6307     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6308     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6309     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6310     auto RelocSymbol = cast<GlobalVariable>(
6311         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6312     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6313                                             SIInstrInfo::MO_ABS32_LO);
6314     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6315   }
6316   default:
6317     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6318             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6319       return lowerImage(Op, ImageDimIntr, DAG);
6320 
6321     return Op;
6322   }
6323 }
6324 
6325 // This function computes an appropriate offset to pass to
6326 // MachineMemOperand::setOffset() based on the offset inputs to
6327 // an intrinsic.  If any of the offsets are non-contstant or
6328 // if VIndex is non-zero then this function returns 0.  Otherwise,
6329 // it returns the sum of VOffset, SOffset, and Offset.
6330 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6331                                       SDValue SOffset,
6332                                       SDValue Offset,
6333                                       SDValue VIndex = SDValue()) {
6334 
6335   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6336       !isa<ConstantSDNode>(Offset))
6337     return 0;
6338 
6339   if (VIndex) {
6340     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6341       return 0;
6342   }
6343 
6344   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6345          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6346          cast<ConstantSDNode>(Offset)->getSExtValue();
6347 }
6348 
6349 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6350   switch (MF.getFunction().getCallingConv()) {
6351   case CallingConv::AMDGPU_PS:
6352     return 1;
6353   case CallingConv::AMDGPU_VS:
6354     return 2;
6355   case CallingConv::AMDGPU_GS:
6356     return 3;
6357   case CallingConv::AMDGPU_HS:
6358   case CallingConv::AMDGPU_LS:
6359   case CallingConv::AMDGPU_ES:
6360     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6361   case CallingConv::AMDGPU_CS:
6362   case CallingConv::AMDGPU_KERNEL:
6363   case CallingConv::C:
6364   case CallingConv::Fast:
6365   default:
6366     // Assume other calling conventions are various compute callable functions
6367     return 0;
6368   }
6369 }
6370 
6371 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6372                                                  SelectionDAG &DAG) const {
6373   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6374   SDLoc DL(Op);
6375 
6376   switch (IntrID) {
6377   case Intrinsic::amdgcn_ds_ordered_add:
6378   case Intrinsic::amdgcn_ds_ordered_swap: {
6379     MemSDNode *M = cast<MemSDNode>(Op);
6380     SDValue Chain = M->getOperand(0);
6381     SDValue M0 = M->getOperand(2);
6382     SDValue Value = M->getOperand(3);
6383     unsigned IndexOperand = M->getConstantOperandVal(7);
6384     unsigned WaveRelease = M->getConstantOperandVal(8);
6385     unsigned WaveDone = M->getConstantOperandVal(9);
6386 
6387     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6388     IndexOperand &= ~0x3f;
6389     unsigned CountDw = 0;
6390 
6391     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6392       CountDw = (IndexOperand >> 24) & 0xf;
6393       IndexOperand &= ~(0xf << 24);
6394 
6395       if (CountDw < 1 || CountDw > 4) {
6396         report_fatal_error(
6397             "ds_ordered_count: dword count must be between 1 and 4");
6398       }
6399     }
6400 
6401     if (IndexOperand)
6402       report_fatal_error("ds_ordered_count: bad index operand");
6403 
6404     if (WaveDone && !WaveRelease)
6405       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6406 
6407     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6408     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6409     unsigned Offset0 = OrderedCountIndex << 2;
6410     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6411                        (Instruction << 4);
6412 
6413     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6414       Offset1 |= (CountDw - 1) << 6;
6415 
6416     unsigned Offset = Offset0 | (Offset1 << 8);
6417 
6418     SDValue Ops[] = {
6419       Chain,
6420       Value,
6421       DAG.getTargetConstant(Offset, DL, MVT::i16),
6422       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6423     };
6424     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6425                                    M->getVTList(), Ops, M->getMemoryVT(),
6426                                    M->getMemOperand());
6427   }
6428   case Intrinsic::amdgcn_ds_fadd: {
6429     MemSDNode *M = cast<MemSDNode>(Op);
6430     unsigned Opc;
6431     switch (IntrID) {
6432     case Intrinsic::amdgcn_ds_fadd:
6433       Opc = ISD::ATOMIC_LOAD_FADD;
6434       break;
6435     }
6436 
6437     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6438                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6439                          M->getMemOperand());
6440   }
6441   case Intrinsic::amdgcn_atomic_inc:
6442   case Intrinsic::amdgcn_atomic_dec:
6443   case Intrinsic::amdgcn_ds_fmin:
6444   case Intrinsic::amdgcn_ds_fmax: {
6445     MemSDNode *M = cast<MemSDNode>(Op);
6446     unsigned Opc;
6447     switch (IntrID) {
6448     case Intrinsic::amdgcn_atomic_inc:
6449       Opc = AMDGPUISD::ATOMIC_INC;
6450       break;
6451     case Intrinsic::amdgcn_atomic_dec:
6452       Opc = AMDGPUISD::ATOMIC_DEC;
6453       break;
6454     case Intrinsic::amdgcn_ds_fmin:
6455       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6456       break;
6457     case Intrinsic::amdgcn_ds_fmax:
6458       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6459       break;
6460     default:
6461       llvm_unreachable("Unknown intrinsic!");
6462     }
6463     SDValue Ops[] = {
6464       M->getOperand(0), // Chain
6465       M->getOperand(2), // Ptr
6466       M->getOperand(3)  // Value
6467     };
6468 
6469     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6470                                    M->getMemoryVT(), M->getMemOperand());
6471   }
6472   case Intrinsic::amdgcn_buffer_load:
6473   case Intrinsic::amdgcn_buffer_load_format: {
6474     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6475     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6476     unsigned IdxEn = 1;
6477     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6478       IdxEn = Idx->getZExtValue() != 0;
6479     SDValue Ops[] = {
6480       Op.getOperand(0), // Chain
6481       Op.getOperand(2), // rsrc
6482       Op.getOperand(3), // vindex
6483       SDValue(),        // voffset -- will be set by setBufferOffsets
6484       SDValue(),        // soffset -- will be set by setBufferOffsets
6485       SDValue(),        // offset -- will be set by setBufferOffsets
6486       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6487       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6488     };
6489 
6490     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6491     // We don't know the offset if vindex is non-zero, so clear it.
6492     if (IdxEn)
6493       Offset = 0;
6494 
6495     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6496         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6497 
6498     EVT VT = Op.getValueType();
6499     EVT IntVT = VT.changeTypeToInteger();
6500     auto *M = cast<MemSDNode>(Op);
6501     M->getMemOperand()->setOffset(Offset);
6502     EVT LoadVT = Op.getValueType();
6503 
6504     if (LoadVT.getScalarType() == MVT::f16)
6505       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6506                                  M, DAG, Ops);
6507 
6508     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6509     if (LoadVT.getScalarType() == MVT::i8 ||
6510         LoadVT.getScalarType() == MVT::i16)
6511       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6512 
6513     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6514                                M->getMemOperand(), DAG);
6515   }
6516   case Intrinsic::amdgcn_raw_buffer_load:
6517   case Intrinsic::amdgcn_raw_buffer_load_format: {
6518     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6519 
6520     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6521     SDValue Ops[] = {
6522       Op.getOperand(0), // Chain
6523       Op.getOperand(2), // rsrc
6524       DAG.getConstant(0, DL, MVT::i32), // vindex
6525       Offsets.first,    // voffset
6526       Op.getOperand(4), // soffset
6527       Offsets.second,   // offset
6528       Op.getOperand(5), // cachepolicy, swizzled buffer
6529       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6530     };
6531 
6532     auto *M = cast<MemSDNode>(Op);
6533     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6534     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6535   }
6536   case Intrinsic::amdgcn_struct_buffer_load:
6537   case Intrinsic::amdgcn_struct_buffer_load_format: {
6538     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6539 
6540     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6541     SDValue Ops[] = {
6542       Op.getOperand(0), // Chain
6543       Op.getOperand(2), // rsrc
6544       Op.getOperand(3), // vindex
6545       Offsets.first,    // voffset
6546       Op.getOperand(5), // soffset
6547       Offsets.second,   // offset
6548       Op.getOperand(6), // cachepolicy, swizzled buffer
6549       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6550     };
6551 
6552     auto *M = cast<MemSDNode>(Op);
6553     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6554                                                         Ops[2]));
6555     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6556   }
6557   case Intrinsic::amdgcn_tbuffer_load: {
6558     MemSDNode *M = cast<MemSDNode>(Op);
6559     EVT LoadVT = Op.getValueType();
6560 
6561     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6562     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6563     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6564     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6565     unsigned IdxEn = 1;
6566     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6567       IdxEn = Idx->getZExtValue() != 0;
6568     SDValue Ops[] = {
6569       Op.getOperand(0),  // Chain
6570       Op.getOperand(2),  // rsrc
6571       Op.getOperand(3),  // vindex
6572       Op.getOperand(4),  // voffset
6573       Op.getOperand(5),  // soffset
6574       Op.getOperand(6),  // offset
6575       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6576       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6577       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6578     };
6579 
6580     if (LoadVT.getScalarType() == MVT::f16)
6581       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6582                                  M, DAG, Ops);
6583     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6584                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6585                                DAG);
6586   }
6587   case Intrinsic::amdgcn_raw_tbuffer_load: {
6588     MemSDNode *M = cast<MemSDNode>(Op);
6589     EVT LoadVT = Op.getValueType();
6590     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6591 
6592     SDValue Ops[] = {
6593       Op.getOperand(0),  // Chain
6594       Op.getOperand(2),  // rsrc
6595       DAG.getConstant(0, DL, MVT::i32), // vindex
6596       Offsets.first,     // voffset
6597       Op.getOperand(4),  // soffset
6598       Offsets.second,    // offset
6599       Op.getOperand(5),  // format
6600       Op.getOperand(6),  // cachepolicy, swizzled buffer
6601       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6602     };
6603 
6604     if (LoadVT.getScalarType() == MVT::f16)
6605       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6606                                  M, DAG, Ops);
6607     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6608                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6609                                DAG);
6610   }
6611   case Intrinsic::amdgcn_struct_tbuffer_load: {
6612     MemSDNode *M = cast<MemSDNode>(Op);
6613     EVT LoadVT = Op.getValueType();
6614     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6615 
6616     SDValue Ops[] = {
6617       Op.getOperand(0),  // Chain
6618       Op.getOperand(2),  // rsrc
6619       Op.getOperand(3),  // vindex
6620       Offsets.first,     // voffset
6621       Op.getOperand(5),  // soffset
6622       Offsets.second,    // offset
6623       Op.getOperand(6),  // format
6624       Op.getOperand(7),  // cachepolicy, swizzled buffer
6625       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6626     };
6627 
6628     if (LoadVT.getScalarType() == MVT::f16)
6629       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6630                                  M, DAG, Ops);
6631     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6632                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6633                                DAG);
6634   }
6635   case Intrinsic::amdgcn_buffer_atomic_swap:
6636   case Intrinsic::amdgcn_buffer_atomic_add:
6637   case Intrinsic::amdgcn_buffer_atomic_sub:
6638   case Intrinsic::amdgcn_buffer_atomic_smin:
6639   case Intrinsic::amdgcn_buffer_atomic_umin:
6640   case Intrinsic::amdgcn_buffer_atomic_smax:
6641   case Intrinsic::amdgcn_buffer_atomic_umax:
6642   case Intrinsic::amdgcn_buffer_atomic_and:
6643   case Intrinsic::amdgcn_buffer_atomic_or:
6644   case Intrinsic::amdgcn_buffer_atomic_xor: {
6645     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6646     unsigned IdxEn = 1;
6647     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6648       IdxEn = Idx->getZExtValue() != 0;
6649     SDValue Ops[] = {
6650       Op.getOperand(0), // Chain
6651       Op.getOperand(2), // vdata
6652       Op.getOperand(3), // rsrc
6653       Op.getOperand(4), // vindex
6654       SDValue(),        // voffset -- will be set by setBufferOffsets
6655       SDValue(),        // soffset -- will be set by setBufferOffsets
6656       SDValue(),        // offset -- will be set by setBufferOffsets
6657       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6658       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6659     };
6660     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6661     // We don't know the offset if vindex is non-zero, so clear it.
6662     if (IdxEn)
6663       Offset = 0;
6664     EVT VT = Op.getValueType();
6665 
6666     auto *M = cast<MemSDNode>(Op);
6667     M->getMemOperand()->setOffset(Offset);
6668     unsigned Opcode = 0;
6669 
6670     switch (IntrID) {
6671     case Intrinsic::amdgcn_buffer_atomic_swap:
6672       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6673       break;
6674     case Intrinsic::amdgcn_buffer_atomic_add:
6675       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6676       break;
6677     case Intrinsic::amdgcn_buffer_atomic_sub:
6678       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6679       break;
6680     case Intrinsic::amdgcn_buffer_atomic_smin:
6681       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6682       break;
6683     case Intrinsic::amdgcn_buffer_atomic_umin:
6684       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6685       break;
6686     case Intrinsic::amdgcn_buffer_atomic_smax:
6687       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6688       break;
6689     case Intrinsic::amdgcn_buffer_atomic_umax:
6690       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6691       break;
6692     case Intrinsic::amdgcn_buffer_atomic_and:
6693       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6694       break;
6695     case Intrinsic::amdgcn_buffer_atomic_or:
6696       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6697       break;
6698     case Intrinsic::amdgcn_buffer_atomic_xor:
6699       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6700       break;
6701     default:
6702       llvm_unreachable("unhandled atomic opcode");
6703     }
6704 
6705     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6706                                    M->getMemOperand());
6707   }
6708   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6709   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6710   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6711   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6712   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6713   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6714   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6715   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6716   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6717   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6718   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6719   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6720     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6721     SDValue Ops[] = {
6722       Op.getOperand(0), // Chain
6723       Op.getOperand(2), // vdata
6724       Op.getOperand(3), // rsrc
6725       DAG.getConstant(0, DL, MVT::i32), // vindex
6726       Offsets.first,    // voffset
6727       Op.getOperand(5), // soffset
6728       Offsets.second,   // offset
6729       Op.getOperand(6), // cachepolicy
6730       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6731     };
6732     EVT VT = Op.getValueType();
6733 
6734     auto *M = cast<MemSDNode>(Op);
6735     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6736     unsigned Opcode = 0;
6737 
6738     switch (IntrID) {
6739     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6740       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6741       break;
6742     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6743       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6744       break;
6745     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6746       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6747       break;
6748     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6749       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6750       break;
6751     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6752       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6753       break;
6754     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6755       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6756       break;
6757     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6758       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6759       break;
6760     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6761       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6762       break;
6763     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6764       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6765       break;
6766     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6767       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6768       break;
6769     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6770       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6771       break;
6772     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6773       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6774       break;
6775     default:
6776       llvm_unreachable("unhandled atomic opcode");
6777     }
6778 
6779     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6780                                    M->getMemOperand());
6781   }
6782   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6783   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6784   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6785   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6786   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6787   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6788   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6789   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6790   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6791   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6792   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6793   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6794     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6795     SDValue Ops[] = {
6796       Op.getOperand(0), // Chain
6797       Op.getOperand(2), // vdata
6798       Op.getOperand(3), // rsrc
6799       Op.getOperand(4), // vindex
6800       Offsets.first,    // voffset
6801       Op.getOperand(6), // soffset
6802       Offsets.second,   // offset
6803       Op.getOperand(7), // cachepolicy
6804       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6805     };
6806     EVT VT = Op.getValueType();
6807 
6808     auto *M = cast<MemSDNode>(Op);
6809     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6810                                                         Ops[3]));
6811     unsigned Opcode = 0;
6812 
6813     switch (IntrID) {
6814     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6815       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6816       break;
6817     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6818       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6819       break;
6820     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6821       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6822       break;
6823     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6824       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6825       break;
6826     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6827       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6828       break;
6829     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6830       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6831       break;
6832     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6833       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6834       break;
6835     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6836       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6837       break;
6838     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6839       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6840       break;
6841     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6842       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6843       break;
6844     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6845       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6846       break;
6847     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6848       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6849       break;
6850     default:
6851       llvm_unreachable("unhandled atomic opcode");
6852     }
6853 
6854     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6855                                    M->getMemOperand());
6856   }
6857   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6858     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6859     unsigned IdxEn = 1;
6860     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6861       IdxEn = Idx->getZExtValue() != 0;
6862     SDValue Ops[] = {
6863       Op.getOperand(0), // Chain
6864       Op.getOperand(2), // src
6865       Op.getOperand(3), // cmp
6866       Op.getOperand(4), // rsrc
6867       Op.getOperand(5), // vindex
6868       SDValue(),        // voffset -- will be set by setBufferOffsets
6869       SDValue(),        // soffset -- will be set by setBufferOffsets
6870       SDValue(),        // offset -- will be set by setBufferOffsets
6871       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6872       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6873     };
6874     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6875     // We don't know the offset if vindex is non-zero, so clear it.
6876     if (IdxEn)
6877       Offset = 0;
6878     EVT VT = Op.getValueType();
6879     auto *M = cast<MemSDNode>(Op);
6880     M->getMemOperand()->setOffset(Offset);
6881 
6882     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6883                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6884   }
6885   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6886     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6887     SDValue Ops[] = {
6888       Op.getOperand(0), // Chain
6889       Op.getOperand(2), // src
6890       Op.getOperand(3), // cmp
6891       Op.getOperand(4), // rsrc
6892       DAG.getConstant(0, DL, MVT::i32), // vindex
6893       Offsets.first,    // voffset
6894       Op.getOperand(6), // soffset
6895       Offsets.second,   // offset
6896       Op.getOperand(7), // cachepolicy
6897       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6898     };
6899     EVT VT = Op.getValueType();
6900     auto *M = cast<MemSDNode>(Op);
6901     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6902 
6903     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6904                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6905   }
6906   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6907     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6908     SDValue Ops[] = {
6909       Op.getOperand(0), // Chain
6910       Op.getOperand(2), // src
6911       Op.getOperand(3), // cmp
6912       Op.getOperand(4), // rsrc
6913       Op.getOperand(5), // vindex
6914       Offsets.first,    // voffset
6915       Op.getOperand(7), // soffset
6916       Offsets.second,   // offset
6917       Op.getOperand(8), // cachepolicy
6918       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6919     };
6920     EVT VT = Op.getValueType();
6921     auto *M = cast<MemSDNode>(Op);
6922     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6923                                                         Ops[4]));
6924 
6925     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6926                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6927   }
6928 
6929   default:
6930     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6931             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6932       return lowerImage(Op, ImageDimIntr, DAG);
6933 
6934     return SDValue();
6935   }
6936 }
6937 
6938 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6939 // dwordx4 if on SI.
6940 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6941                                               SDVTList VTList,
6942                                               ArrayRef<SDValue> Ops, EVT MemVT,
6943                                               MachineMemOperand *MMO,
6944                                               SelectionDAG &DAG) const {
6945   EVT VT = VTList.VTs[0];
6946   EVT WidenedVT = VT;
6947   EVT WidenedMemVT = MemVT;
6948   if (!Subtarget->hasDwordx3LoadStores() &&
6949       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6950     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6951                                  WidenedVT.getVectorElementType(), 4);
6952     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6953                                     WidenedMemVT.getVectorElementType(), 4);
6954     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6955   }
6956 
6957   assert(VTList.NumVTs == 2);
6958   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6959 
6960   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6961                                        WidenedMemVT, MMO);
6962   if (WidenedVT != VT) {
6963     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6964                                DAG.getVectorIdxConstant(0, DL));
6965     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6966   }
6967   return NewOp;
6968 }
6969 
6970 SDValue SITargetLowering::handleD16VData(SDValue VData,
6971                                          SelectionDAG &DAG) const {
6972   EVT StoreVT = VData.getValueType();
6973 
6974   // No change for f16 and legal vector D16 types.
6975   if (!StoreVT.isVector())
6976     return VData;
6977 
6978   SDLoc DL(VData);
6979   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6980 
6981   if (Subtarget->hasUnpackedD16VMem()) {
6982     // We need to unpack the packed data to store.
6983     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6984     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6985 
6986     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6987                                         StoreVT.getVectorNumElements());
6988     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6989     return DAG.UnrollVectorOp(ZExt.getNode());
6990   }
6991 
6992   assert(isTypeLegal(StoreVT));
6993   return VData;
6994 }
6995 
6996 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6997                                               SelectionDAG &DAG) const {
6998   SDLoc DL(Op);
6999   SDValue Chain = Op.getOperand(0);
7000   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7001   MachineFunction &MF = DAG.getMachineFunction();
7002 
7003   switch (IntrinsicID) {
7004   case Intrinsic::amdgcn_exp_compr: {
7005     SDValue Src0 = Op.getOperand(4);
7006     SDValue Src1 = Op.getOperand(5);
7007     // Hack around illegal type on SI by directly selecting it.
7008     if (isTypeLegal(Src0.getValueType()))
7009       return SDValue();
7010 
7011     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7012     SDValue Undef = DAG.getUNDEF(MVT::f32);
7013     const SDValue Ops[] = {
7014       Op.getOperand(2), // tgt
7015       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7016       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7017       Undef, // src2
7018       Undef, // src3
7019       Op.getOperand(7), // vm
7020       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7021       Op.getOperand(3), // en
7022       Op.getOperand(0) // Chain
7023     };
7024 
7025     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7026     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7027   }
7028   case Intrinsic::amdgcn_s_barrier: {
7029     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7030       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7031       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7032       if (WGSize <= ST.getWavefrontSize())
7033         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7034                                           Op.getOperand(0)), 0);
7035     }
7036     return SDValue();
7037   };
7038   case Intrinsic::amdgcn_tbuffer_store: {
7039     SDValue VData = Op.getOperand(2);
7040     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7041     if (IsD16)
7042       VData = handleD16VData(VData, DAG);
7043     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7044     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7045     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7046     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7047     unsigned IdxEn = 1;
7048     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7049       IdxEn = Idx->getZExtValue() != 0;
7050     SDValue Ops[] = {
7051       Chain,
7052       VData,             // vdata
7053       Op.getOperand(3),  // rsrc
7054       Op.getOperand(4),  // vindex
7055       Op.getOperand(5),  // voffset
7056       Op.getOperand(6),  // soffset
7057       Op.getOperand(7),  // offset
7058       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7059       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7060       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7061     };
7062     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7063                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7064     MemSDNode *M = cast<MemSDNode>(Op);
7065     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7066                                    M->getMemoryVT(), M->getMemOperand());
7067   }
7068 
7069   case Intrinsic::amdgcn_struct_tbuffer_store: {
7070     SDValue VData = Op.getOperand(2);
7071     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7072     if (IsD16)
7073       VData = handleD16VData(VData, DAG);
7074     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7075     SDValue Ops[] = {
7076       Chain,
7077       VData,             // vdata
7078       Op.getOperand(3),  // rsrc
7079       Op.getOperand(4),  // vindex
7080       Offsets.first,     // voffset
7081       Op.getOperand(6),  // soffset
7082       Offsets.second,    // offset
7083       Op.getOperand(7),  // format
7084       Op.getOperand(8),  // cachepolicy, swizzled buffer
7085       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7086     };
7087     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7088                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7089     MemSDNode *M = cast<MemSDNode>(Op);
7090     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7091                                    M->getMemoryVT(), M->getMemOperand());
7092   }
7093 
7094   case Intrinsic::amdgcn_raw_tbuffer_store: {
7095     SDValue VData = Op.getOperand(2);
7096     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7097     if (IsD16)
7098       VData = handleD16VData(VData, DAG);
7099     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7100     SDValue Ops[] = {
7101       Chain,
7102       VData,             // vdata
7103       Op.getOperand(3),  // rsrc
7104       DAG.getConstant(0, DL, MVT::i32), // vindex
7105       Offsets.first,     // voffset
7106       Op.getOperand(5),  // soffset
7107       Offsets.second,    // offset
7108       Op.getOperand(6),  // format
7109       Op.getOperand(7),  // cachepolicy, swizzled buffer
7110       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7111     };
7112     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7113                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7114     MemSDNode *M = cast<MemSDNode>(Op);
7115     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7116                                    M->getMemoryVT(), M->getMemOperand());
7117   }
7118 
7119   case Intrinsic::amdgcn_buffer_store:
7120   case Intrinsic::amdgcn_buffer_store_format: {
7121     SDValue VData = Op.getOperand(2);
7122     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7123     if (IsD16)
7124       VData = handleD16VData(VData, DAG);
7125     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7126     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7127     unsigned IdxEn = 1;
7128     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7129       IdxEn = Idx->getZExtValue() != 0;
7130     SDValue Ops[] = {
7131       Chain,
7132       VData,
7133       Op.getOperand(3), // rsrc
7134       Op.getOperand(4), // vindex
7135       SDValue(), // voffset -- will be set by setBufferOffsets
7136       SDValue(), // soffset -- will be set by setBufferOffsets
7137       SDValue(), // offset -- will be set by setBufferOffsets
7138       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7139       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7140     };
7141     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7142     // We don't know the offset if vindex is non-zero, so clear it.
7143     if (IdxEn)
7144       Offset = 0;
7145     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7146                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7147     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7148     MemSDNode *M = cast<MemSDNode>(Op);
7149     M->getMemOperand()->setOffset(Offset);
7150 
7151     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7152     EVT VDataType = VData.getValueType().getScalarType();
7153     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7154       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7155 
7156     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7157                                    M->getMemoryVT(), M->getMemOperand());
7158   }
7159 
7160   case Intrinsic::amdgcn_raw_buffer_store:
7161   case Intrinsic::amdgcn_raw_buffer_store_format: {
7162     const bool IsFormat =
7163         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7164 
7165     SDValue VData = Op.getOperand(2);
7166     EVT VDataVT = VData.getValueType();
7167     EVT EltType = VDataVT.getScalarType();
7168     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7169     if (IsD16)
7170       VData = handleD16VData(VData, DAG);
7171 
7172     if (!isTypeLegal(VDataVT)) {
7173       VData =
7174           DAG.getNode(ISD::BITCAST, DL,
7175                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7176     }
7177 
7178     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7179     SDValue Ops[] = {
7180       Chain,
7181       VData,
7182       Op.getOperand(3), // rsrc
7183       DAG.getConstant(0, DL, MVT::i32), // vindex
7184       Offsets.first,    // voffset
7185       Op.getOperand(5), // soffset
7186       Offsets.second,   // offset
7187       Op.getOperand(6), // cachepolicy, swizzled buffer
7188       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7189     };
7190     unsigned Opc =
7191         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7192     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7193     MemSDNode *M = cast<MemSDNode>(Op);
7194     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7195 
7196     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7197     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7198       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7199 
7200     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7201                                    M->getMemoryVT(), M->getMemOperand());
7202   }
7203 
7204   case Intrinsic::amdgcn_struct_buffer_store:
7205   case Intrinsic::amdgcn_struct_buffer_store_format: {
7206     const bool IsFormat =
7207         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7208 
7209     SDValue VData = Op.getOperand(2);
7210     EVT VDataVT = VData.getValueType();
7211     EVT EltType = VDataVT.getScalarType();
7212     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7213 
7214     if (IsD16)
7215       VData = handleD16VData(VData, DAG);
7216 
7217     if (!isTypeLegal(VDataVT)) {
7218       VData =
7219           DAG.getNode(ISD::BITCAST, DL,
7220                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7221     }
7222 
7223     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7224     SDValue Ops[] = {
7225       Chain,
7226       VData,
7227       Op.getOperand(3), // rsrc
7228       Op.getOperand(4), // vindex
7229       Offsets.first,    // voffset
7230       Op.getOperand(6), // soffset
7231       Offsets.second,   // offset
7232       Op.getOperand(7), // cachepolicy, swizzled buffer
7233       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7234     };
7235     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7236                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7237     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7238     MemSDNode *M = cast<MemSDNode>(Op);
7239     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7240                                                         Ops[3]));
7241 
7242     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7243     EVT VDataType = VData.getValueType().getScalarType();
7244     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7245       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7246 
7247     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7248                                    M->getMemoryVT(), M->getMemOperand());
7249   }
7250 
7251   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7252     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7253     unsigned IdxEn = 1;
7254     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7255       IdxEn = Idx->getZExtValue() != 0;
7256     SDValue Ops[] = {
7257       Chain,
7258       Op.getOperand(2), // vdata
7259       Op.getOperand(3), // rsrc
7260       Op.getOperand(4), // vindex
7261       SDValue(),        // voffset -- will be set by setBufferOffsets
7262       SDValue(),        // soffset -- will be set by setBufferOffsets
7263       SDValue(),        // offset -- will be set by setBufferOffsets
7264       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7265       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7266     };
7267     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7268     // We don't know the offset if vindex is non-zero, so clear it.
7269     if (IdxEn)
7270       Offset = 0;
7271     EVT VT = Op.getOperand(2).getValueType();
7272 
7273     auto *M = cast<MemSDNode>(Op);
7274     M->getMemOperand()->setOffset(Offset);
7275     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7276                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7277 
7278     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7279                                    M->getMemOperand());
7280   }
7281 
7282   case Intrinsic::amdgcn_global_atomic_fadd: {
7283     SDValue Ops[] = {
7284       Chain,
7285       Op.getOperand(2), // ptr
7286       Op.getOperand(3)  // vdata
7287     };
7288     EVT VT = Op.getOperand(3).getValueType();
7289 
7290     auto *M = cast<MemSDNode>(Op);
7291     if (VT.isVector()) {
7292       return DAG.getMemIntrinsicNode(
7293         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7294         M->getMemOperand());
7295     }
7296 
7297     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7298                          DAG.getVTList(VT, MVT::Other), Ops,
7299                          M->getMemOperand()).getValue(1);
7300   }
7301   case Intrinsic::amdgcn_end_cf:
7302     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7303                                       Op->getOperand(2), Chain), 0);
7304 
7305   default: {
7306     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7307             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7308       return lowerImage(Op, ImageDimIntr, DAG);
7309 
7310     return Op;
7311   }
7312   }
7313 }
7314 
7315 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7316 // offset (the offset that is included in bounds checking and swizzling, to be
7317 // split between the instruction's voffset and immoffset fields) and soffset
7318 // (the offset that is excluded from bounds checking and swizzling, to go in
7319 // the instruction's soffset field).  This function takes the first kind of
7320 // offset and figures out how to split it between voffset and immoffset.
7321 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7322     SDValue Offset, SelectionDAG &DAG) const {
7323   SDLoc DL(Offset);
7324   const unsigned MaxImm = 4095;
7325   SDValue N0 = Offset;
7326   ConstantSDNode *C1 = nullptr;
7327 
7328   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7329     N0 = SDValue();
7330   else if (DAG.isBaseWithConstantOffset(N0)) {
7331     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7332     N0 = N0.getOperand(0);
7333   }
7334 
7335   if (C1) {
7336     unsigned ImmOffset = C1->getZExtValue();
7337     // If the immediate value is too big for the immoffset field, put the value
7338     // and -4096 into the immoffset field so that the value that is copied/added
7339     // for the voffset field is a multiple of 4096, and it stands more chance
7340     // of being CSEd with the copy/add for another similar load/store.
7341     // However, do not do that rounding down to a multiple of 4096 if that is a
7342     // negative number, as it appears to be illegal to have a negative offset
7343     // in the vgpr, even if adding the immediate offset makes it positive.
7344     unsigned Overflow = ImmOffset & ~MaxImm;
7345     ImmOffset -= Overflow;
7346     if ((int32_t)Overflow < 0) {
7347       Overflow += ImmOffset;
7348       ImmOffset = 0;
7349     }
7350     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7351     if (Overflow) {
7352       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7353       if (!N0)
7354         N0 = OverflowVal;
7355       else {
7356         SDValue Ops[] = { N0, OverflowVal };
7357         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7358       }
7359     }
7360   }
7361   if (!N0)
7362     N0 = DAG.getConstant(0, DL, MVT::i32);
7363   if (!C1)
7364     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7365   return {N0, SDValue(C1, 0)};
7366 }
7367 
7368 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7369 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7370 // pointed to by Offsets.
7371 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7372                                         SelectionDAG &DAG, SDValue *Offsets,
7373                                         unsigned Align) const {
7374   SDLoc DL(CombinedOffset);
7375   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7376     uint32_t Imm = C->getZExtValue();
7377     uint32_t SOffset, ImmOffset;
7378     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7379       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7380       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7381       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7382       return SOffset + ImmOffset;
7383     }
7384   }
7385   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7386     SDValue N0 = CombinedOffset.getOperand(0);
7387     SDValue N1 = CombinedOffset.getOperand(1);
7388     uint32_t SOffset, ImmOffset;
7389     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7390     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7391                                                 Subtarget, Align)) {
7392       Offsets[0] = N0;
7393       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7394       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7395       return 0;
7396     }
7397   }
7398   Offsets[0] = CombinedOffset;
7399   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7400   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7401   return 0;
7402 }
7403 
7404 // Handle 8 bit and 16 bit buffer loads
7405 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7406                                                      EVT LoadVT, SDLoc DL,
7407                                                      ArrayRef<SDValue> Ops,
7408                                                      MemSDNode *M) const {
7409   EVT IntVT = LoadVT.changeTypeToInteger();
7410   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7411          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7412 
7413   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7414   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7415                                                Ops, IntVT,
7416                                                M->getMemOperand());
7417   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7418   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7419 
7420   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7421 }
7422 
7423 // Handle 8 bit and 16 bit buffer stores
7424 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7425                                                       EVT VDataType, SDLoc DL,
7426                                                       SDValue Ops[],
7427                                                       MemSDNode *M) const {
7428   if (VDataType == MVT::f16)
7429     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7430 
7431   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7432   Ops[1] = BufferStoreExt;
7433   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7434                                  AMDGPUISD::BUFFER_STORE_SHORT;
7435   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7436   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7437                                      M->getMemOperand());
7438 }
7439 
7440 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7441                                  ISD::LoadExtType ExtType, SDValue Op,
7442                                  const SDLoc &SL, EVT VT) {
7443   if (VT.bitsLT(Op.getValueType()))
7444     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7445 
7446   switch (ExtType) {
7447   case ISD::SEXTLOAD:
7448     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7449   case ISD::ZEXTLOAD:
7450     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7451   case ISD::EXTLOAD:
7452     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7453   case ISD::NON_EXTLOAD:
7454     return Op;
7455   }
7456 
7457   llvm_unreachable("invalid ext type");
7458 }
7459 
7460 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7461   SelectionDAG &DAG = DCI.DAG;
7462   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7463     return SDValue();
7464 
7465   // FIXME: Constant loads should all be marked invariant.
7466   unsigned AS = Ld->getAddressSpace();
7467   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7468       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7469       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7470     return SDValue();
7471 
7472   // Don't do this early, since it may interfere with adjacent load merging for
7473   // illegal types. We can avoid losing alignment information for exotic types
7474   // pre-legalize.
7475   EVT MemVT = Ld->getMemoryVT();
7476   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7477       MemVT.getSizeInBits() >= 32)
7478     return SDValue();
7479 
7480   SDLoc SL(Ld);
7481 
7482   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7483          "unexpected vector extload");
7484 
7485   // TODO: Drop only high part of range.
7486   SDValue Ptr = Ld->getBasePtr();
7487   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7488                                 MVT::i32, SL, Ld->getChain(), Ptr,
7489                                 Ld->getOffset(),
7490                                 Ld->getPointerInfo(), MVT::i32,
7491                                 Ld->getAlignment(),
7492                                 Ld->getMemOperand()->getFlags(),
7493                                 Ld->getAAInfo(),
7494                                 nullptr); // Drop ranges
7495 
7496   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7497   if (MemVT.isFloatingPoint()) {
7498     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7499            "unexpected fp extload");
7500     TruncVT = MemVT.changeTypeToInteger();
7501   }
7502 
7503   SDValue Cvt = NewLoad;
7504   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7505     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7506                       DAG.getValueType(TruncVT));
7507   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7508              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7509     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7510   } else {
7511     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7512   }
7513 
7514   EVT VT = Ld->getValueType(0);
7515   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7516 
7517   DCI.AddToWorklist(Cvt.getNode());
7518 
7519   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7520   // the appropriate extension from the 32-bit load.
7521   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7522   DCI.AddToWorklist(Cvt.getNode());
7523 
7524   // Handle conversion back to floating point if necessary.
7525   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7526 
7527   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7528 }
7529 
7530 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7531   SDLoc DL(Op);
7532   LoadSDNode *Load = cast<LoadSDNode>(Op);
7533   ISD::LoadExtType ExtType = Load->getExtensionType();
7534   EVT MemVT = Load->getMemoryVT();
7535 
7536   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7537     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7538       return SDValue();
7539 
7540     // FIXME: Copied from PPC
7541     // First, load into 32 bits, then truncate to 1 bit.
7542 
7543     SDValue Chain = Load->getChain();
7544     SDValue BasePtr = Load->getBasePtr();
7545     MachineMemOperand *MMO = Load->getMemOperand();
7546 
7547     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7548 
7549     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7550                                    BasePtr, RealMemVT, MMO);
7551 
7552     if (!MemVT.isVector()) {
7553       SDValue Ops[] = {
7554         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7555         NewLD.getValue(1)
7556       };
7557 
7558       return DAG.getMergeValues(Ops, DL);
7559     }
7560 
7561     SmallVector<SDValue, 3> Elts;
7562     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7563       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7564                                 DAG.getConstant(I, DL, MVT::i32));
7565 
7566       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7567     }
7568 
7569     SDValue Ops[] = {
7570       DAG.getBuildVector(MemVT, DL, Elts),
7571       NewLD.getValue(1)
7572     };
7573 
7574     return DAG.getMergeValues(Ops, DL);
7575   }
7576 
7577   if (!MemVT.isVector())
7578     return SDValue();
7579 
7580   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7581          "Custom lowering for non-i32 vectors hasn't been implemented.");
7582 
7583   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7584                                       MemVT, *Load->getMemOperand())) {
7585     SDValue Ops[2];
7586     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7587     return DAG.getMergeValues(Ops, DL);
7588   }
7589 
7590   unsigned Alignment = Load->getAlignment();
7591   unsigned AS = Load->getAddressSpace();
7592   if (Subtarget->hasLDSMisalignedBug() &&
7593       AS == AMDGPUAS::FLAT_ADDRESS &&
7594       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7595     return SplitVectorLoad(Op, DAG);
7596   }
7597 
7598   MachineFunction &MF = DAG.getMachineFunction();
7599   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7600   // If there is a possibilty that flat instruction access scratch memory
7601   // then we need to use the same legalization rules we use for private.
7602   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7603       !Subtarget->hasMultiDwordFlatScratchAddressing())
7604     AS = MFI->hasFlatScratchInit() ?
7605          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7606 
7607   unsigned NumElements = MemVT.getVectorNumElements();
7608 
7609   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7610       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7611     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7612       if (MemVT.isPow2VectorType())
7613         return SDValue();
7614       if (NumElements == 3)
7615         return WidenVectorLoad(Op, DAG);
7616       return SplitVectorLoad(Op, DAG);
7617     }
7618     // Non-uniform loads will be selected to MUBUF instructions, so they
7619     // have the same legalization requirements as global and private
7620     // loads.
7621     //
7622   }
7623 
7624   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7625       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7626       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7627     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7628         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7629         Alignment >= 4 && NumElements < 32) {
7630       if (MemVT.isPow2VectorType())
7631         return SDValue();
7632       if (NumElements == 3)
7633         return WidenVectorLoad(Op, DAG);
7634       return SplitVectorLoad(Op, DAG);
7635     }
7636     // Non-uniform loads will be selected to MUBUF instructions, so they
7637     // have the same legalization requirements as global and private
7638     // loads.
7639     //
7640   }
7641   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7642       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7643       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7644       AS == AMDGPUAS::FLAT_ADDRESS) {
7645     if (NumElements > 4)
7646       return SplitVectorLoad(Op, DAG);
7647     // v3 loads not supported on SI.
7648     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7649       return WidenVectorLoad(Op, DAG);
7650     // v3 and v4 loads are supported for private and global memory.
7651     return SDValue();
7652   }
7653   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7654     // Depending on the setting of the private_element_size field in the
7655     // resource descriptor, we can only make private accesses up to a certain
7656     // size.
7657     switch (Subtarget->getMaxPrivateElementSize()) {
7658     case 4: {
7659       SDValue Ops[2];
7660       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7661       return DAG.getMergeValues(Ops, DL);
7662     }
7663     case 8:
7664       if (NumElements > 2)
7665         return SplitVectorLoad(Op, DAG);
7666       return SDValue();
7667     case 16:
7668       // Same as global/flat
7669       if (NumElements > 4)
7670         return SplitVectorLoad(Op, DAG);
7671       // v3 loads not supported on SI.
7672       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7673         return WidenVectorLoad(Op, DAG);
7674       return SDValue();
7675     default:
7676       llvm_unreachable("unsupported private_element_size");
7677     }
7678   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7679     // Use ds_read_b128 if possible.
7680     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7681         MemVT.getStoreSize() == 16)
7682       return SDValue();
7683 
7684     if (NumElements > 2)
7685       return SplitVectorLoad(Op, DAG);
7686 
7687     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7688     // address is negative, then the instruction is incorrectly treated as
7689     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7690     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7691     // load later in the SILoadStoreOptimizer.
7692     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7693         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7694         Load->getAlignment() < 8) {
7695       return SplitVectorLoad(Op, DAG);
7696     }
7697   }
7698   return SDValue();
7699 }
7700 
7701 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7702   EVT VT = Op.getValueType();
7703   assert(VT.getSizeInBits() == 64);
7704 
7705   SDLoc DL(Op);
7706   SDValue Cond = Op.getOperand(0);
7707 
7708   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7709   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7710 
7711   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7712   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7713 
7714   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7715   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7716 
7717   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7718 
7719   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7720   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7721 
7722   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7723 
7724   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7725   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7726 }
7727 
7728 // Catch division cases where we can use shortcuts with rcp and rsq
7729 // instructions.
7730 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7731                                               SelectionDAG &DAG) const {
7732   SDLoc SL(Op);
7733   SDValue LHS = Op.getOperand(0);
7734   SDValue RHS = Op.getOperand(1);
7735   EVT VT = Op.getValueType();
7736   const SDNodeFlags Flags = Op->getFlags();
7737 
7738   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7739                             Flags.hasApproximateFuncs();
7740 
7741   // Without !fpmath accuracy information, we can't do more because we don't
7742   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7743   if (!AllowInaccurateRcp)
7744     return SDValue();
7745 
7746   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7747     if (CLHS->isExactlyValue(1.0)) {
7748       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7749       // the CI documentation has a worst case error of 1 ulp.
7750       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7751       // use it as long as we aren't trying to use denormals.
7752       //
7753       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7754 
7755       // 1.0 / sqrt(x) -> rsq(x)
7756 
7757       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7758       // error seems really high at 2^29 ULP.
7759       if (RHS.getOpcode() == ISD::FSQRT)
7760         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7761 
7762       // 1.0 / x -> rcp(x)
7763       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7764     }
7765 
7766     // Same as for 1.0, but expand the sign out of the constant.
7767     if (CLHS->isExactlyValue(-1.0)) {
7768       // -1.0 / x -> rcp (fneg x)
7769       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7770       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7771     }
7772   }
7773 
7774   // Turn into multiply by the reciprocal.
7775   // x / y -> x * (1.0 / y)
7776   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7777   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7778 }
7779 
7780 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7781                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7782   if (GlueChain->getNumValues() <= 1) {
7783     return DAG.getNode(Opcode, SL, VT, A, B);
7784   }
7785 
7786   assert(GlueChain->getNumValues() == 3);
7787 
7788   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7789   switch (Opcode) {
7790   default: llvm_unreachable("no chain equivalent for opcode");
7791   case ISD::FMUL:
7792     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7793     break;
7794   }
7795 
7796   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7797                      GlueChain.getValue(2));
7798 }
7799 
7800 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7801                            EVT VT, SDValue A, SDValue B, SDValue C,
7802                            SDValue GlueChain) {
7803   if (GlueChain->getNumValues() <= 1) {
7804     return DAG.getNode(Opcode, SL, VT, A, B, C);
7805   }
7806 
7807   assert(GlueChain->getNumValues() == 3);
7808 
7809   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7810   switch (Opcode) {
7811   default: llvm_unreachable("no chain equivalent for opcode");
7812   case ISD::FMA:
7813     Opcode = AMDGPUISD::FMA_W_CHAIN;
7814     break;
7815   }
7816 
7817   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7818                      GlueChain.getValue(2));
7819 }
7820 
7821 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7822   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7823     return FastLowered;
7824 
7825   SDLoc SL(Op);
7826   SDValue Src0 = Op.getOperand(0);
7827   SDValue Src1 = Op.getOperand(1);
7828 
7829   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7830   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7831 
7832   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7833   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7834 
7835   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7836   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7837 
7838   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7839 }
7840 
7841 // Faster 2.5 ULP division that does not support denormals.
7842 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7843   SDLoc SL(Op);
7844   SDValue LHS = Op.getOperand(1);
7845   SDValue RHS = Op.getOperand(2);
7846 
7847   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7848 
7849   const APFloat K0Val(BitsToFloat(0x6f800000));
7850   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7851 
7852   const APFloat K1Val(BitsToFloat(0x2f800000));
7853   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7854 
7855   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7856 
7857   EVT SetCCVT =
7858     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7859 
7860   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7861 
7862   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7863 
7864   // TODO: Should this propagate fast-math-flags?
7865   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7866 
7867   // rcp does not support denormals.
7868   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7869 
7870   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7871 
7872   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7873 }
7874 
7875 // Returns immediate value for setting the F32 denorm mode when using the
7876 // S_DENORM_MODE instruction.
7877 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7878                                           const SDLoc &SL, const GCNSubtarget *ST) {
7879   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7880   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7881                                 ? FP_DENORM_FLUSH_NONE
7882                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7883 
7884   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7885   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7886 }
7887 
7888 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7889   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7890     return FastLowered;
7891 
7892   SDLoc SL(Op);
7893   SDValue LHS = Op.getOperand(0);
7894   SDValue RHS = Op.getOperand(1);
7895 
7896   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7897 
7898   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7899 
7900   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7901                                           RHS, RHS, LHS);
7902   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7903                                         LHS, RHS, LHS);
7904 
7905   // Denominator is scaled to not be denormal, so using rcp is ok.
7906   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7907                                   DenominatorScaled);
7908   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7909                                      DenominatorScaled);
7910 
7911   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7912                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7913                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7914   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7915 
7916   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7917 
7918   if (!HasFP32Denormals) {
7919     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7920 
7921     SDValue EnableDenorm;
7922     if (Subtarget->hasDenormModeInst()) {
7923       const SDValue EnableDenormValue =
7924           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7925 
7926       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7927                                  DAG.getEntryNode(), EnableDenormValue);
7928     } else {
7929       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7930                                                         SL, MVT::i32);
7931       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7932                                  DAG.getEntryNode(), EnableDenormValue,
7933                                  BitField);
7934     }
7935 
7936     SDValue Ops[3] = {
7937       NegDivScale0,
7938       EnableDenorm.getValue(0),
7939       EnableDenorm.getValue(1)
7940     };
7941 
7942     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7943   }
7944 
7945   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7946                              ApproxRcp, One, NegDivScale0);
7947 
7948   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7949                              ApproxRcp, Fma0);
7950 
7951   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7952                            Fma1, Fma1);
7953 
7954   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7955                              NumeratorScaled, Mul);
7956 
7957   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7958 
7959   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7960                              NumeratorScaled, Fma3);
7961 
7962   if (!HasFP32Denormals) {
7963     SDValue DisableDenorm;
7964     if (Subtarget->hasDenormModeInst()) {
7965       const SDValue DisableDenormValue =
7966           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7967 
7968       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7969                                   Fma4.getValue(1), DisableDenormValue,
7970                                   Fma4.getValue(2));
7971     } else {
7972       const SDValue DisableDenormValue =
7973           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7974 
7975       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7976                                   Fma4.getValue(1), DisableDenormValue,
7977                                   BitField, Fma4.getValue(2));
7978     }
7979 
7980     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7981                                       DisableDenorm, DAG.getRoot());
7982     DAG.setRoot(OutputChain);
7983   }
7984 
7985   SDValue Scale = NumeratorScaled.getValue(1);
7986   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7987                              Fma4, Fma1, Fma3, Scale);
7988 
7989   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7990 }
7991 
7992 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7993   if (DAG.getTarget().Options.UnsafeFPMath)
7994     return lowerFastUnsafeFDIV(Op, DAG);
7995 
7996   SDLoc SL(Op);
7997   SDValue X = Op.getOperand(0);
7998   SDValue Y = Op.getOperand(1);
7999 
8000   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8001 
8002   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8003 
8004   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8005 
8006   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8007 
8008   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8009 
8010   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8011 
8012   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8013 
8014   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8015 
8016   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8017 
8018   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8019   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8020 
8021   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8022                              NegDivScale0, Mul, DivScale1);
8023 
8024   SDValue Scale;
8025 
8026   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8027     // Workaround a hardware bug on SI where the condition output from div_scale
8028     // is not usable.
8029 
8030     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8031 
8032     // Figure out if the scale to use for div_fmas.
8033     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8034     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8035     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8036     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8037 
8038     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8039     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8040 
8041     SDValue Scale0Hi
8042       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8043     SDValue Scale1Hi
8044       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8045 
8046     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8047     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8048     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8049   } else {
8050     Scale = DivScale1.getValue(1);
8051   }
8052 
8053   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8054                              Fma4, Fma3, Mul, Scale);
8055 
8056   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8057 }
8058 
8059 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8060   EVT VT = Op.getValueType();
8061 
8062   if (VT == MVT::f32)
8063     return LowerFDIV32(Op, DAG);
8064 
8065   if (VT == MVT::f64)
8066     return LowerFDIV64(Op, DAG);
8067 
8068   if (VT == MVT::f16)
8069     return LowerFDIV16(Op, DAG);
8070 
8071   llvm_unreachable("Unexpected type for fdiv");
8072 }
8073 
8074 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8075   SDLoc DL(Op);
8076   StoreSDNode *Store = cast<StoreSDNode>(Op);
8077   EVT VT = Store->getMemoryVT();
8078 
8079   if (VT == MVT::i1) {
8080     return DAG.getTruncStore(Store->getChain(), DL,
8081        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8082        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8083   }
8084 
8085   assert(VT.isVector() &&
8086          Store->getValue().getValueType().getScalarType() == MVT::i32);
8087 
8088   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8089                                       VT, *Store->getMemOperand())) {
8090     return expandUnalignedStore(Store, DAG);
8091   }
8092 
8093   unsigned AS = Store->getAddressSpace();
8094   if (Subtarget->hasLDSMisalignedBug() &&
8095       AS == AMDGPUAS::FLAT_ADDRESS &&
8096       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8097     return SplitVectorStore(Op, DAG);
8098   }
8099 
8100   MachineFunction &MF = DAG.getMachineFunction();
8101   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8102   // If there is a possibilty that flat instruction access scratch memory
8103   // then we need to use the same legalization rules we use for private.
8104   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8105       !Subtarget->hasMultiDwordFlatScratchAddressing())
8106     AS = MFI->hasFlatScratchInit() ?
8107          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8108 
8109   unsigned NumElements = VT.getVectorNumElements();
8110   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8111       AS == AMDGPUAS::FLAT_ADDRESS) {
8112     if (NumElements > 4)
8113       return SplitVectorStore(Op, DAG);
8114     // v3 stores not supported on SI.
8115     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8116       return SplitVectorStore(Op, DAG);
8117     return SDValue();
8118   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8119     switch (Subtarget->getMaxPrivateElementSize()) {
8120     case 4:
8121       return scalarizeVectorStore(Store, DAG);
8122     case 8:
8123       if (NumElements > 2)
8124         return SplitVectorStore(Op, DAG);
8125       return SDValue();
8126     case 16:
8127       if (NumElements > 4 || NumElements == 3)
8128         return SplitVectorStore(Op, DAG);
8129       return SDValue();
8130     default:
8131       llvm_unreachable("unsupported private_element_size");
8132     }
8133   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8134     // Use ds_write_b128 if possible.
8135     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8136         VT.getStoreSize() == 16 && NumElements != 3)
8137       return SDValue();
8138 
8139     if (NumElements > 2)
8140       return SplitVectorStore(Op, DAG);
8141 
8142     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8143     // address is negative, then the instruction is incorrectly treated as
8144     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8145     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8146     // store later in the SILoadStoreOptimizer.
8147     if (!Subtarget->hasUsableDSOffset() &&
8148         NumElements == 2 && VT.getStoreSize() == 8 &&
8149         Store->getAlignment() < 8) {
8150       return SplitVectorStore(Op, DAG);
8151     }
8152 
8153     return SDValue();
8154   } else {
8155     llvm_unreachable("unhandled address space");
8156   }
8157 }
8158 
8159 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8160   SDLoc DL(Op);
8161   EVT VT = Op.getValueType();
8162   SDValue Arg = Op.getOperand(0);
8163   SDValue TrigVal;
8164 
8165   // TODO: Should this propagate fast-math-flags?
8166 
8167   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
8168 
8169   if (Subtarget->hasTrigReducedRange()) {
8170     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8171     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
8172   } else {
8173     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8174   }
8175 
8176   switch (Op.getOpcode()) {
8177   case ISD::FCOS:
8178     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
8179   case ISD::FSIN:
8180     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
8181   default:
8182     llvm_unreachable("Wrong trig opcode");
8183   }
8184 }
8185 
8186 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8187   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8188   assert(AtomicNode->isCompareAndSwap());
8189   unsigned AS = AtomicNode->getAddressSpace();
8190 
8191   // No custom lowering required for local address space
8192   if (!isFlatGlobalAddrSpace(AS))
8193     return Op;
8194 
8195   // Non-local address space requires custom lowering for atomic compare
8196   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8197   SDLoc DL(Op);
8198   SDValue ChainIn = Op.getOperand(0);
8199   SDValue Addr = Op.getOperand(1);
8200   SDValue Old = Op.getOperand(2);
8201   SDValue New = Op.getOperand(3);
8202   EVT VT = Op.getValueType();
8203   MVT SimpleVT = VT.getSimpleVT();
8204   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8205 
8206   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8207   SDValue Ops[] = { ChainIn, Addr, NewOld };
8208 
8209   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8210                                  Ops, VT, AtomicNode->getMemOperand());
8211 }
8212 
8213 //===----------------------------------------------------------------------===//
8214 // Custom DAG optimizations
8215 //===----------------------------------------------------------------------===//
8216 
8217 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8218                                                      DAGCombinerInfo &DCI) const {
8219   EVT VT = N->getValueType(0);
8220   EVT ScalarVT = VT.getScalarType();
8221   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8222     return SDValue();
8223 
8224   SelectionDAG &DAG = DCI.DAG;
8225   SDLoc DL(N);
8226 
8227   SDValue Src = N->getOperand(0);
8228   EVT SrcVT = Src.getValueType();
8229 
8230   // TODO: We could try to match extracting the higher bytes, which would be
8231   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8232   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8233   // about in practice.
8234   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8235     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8236       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8237       DCI.AddToWorklist(Cvt.getNode());
8238 
8239       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8240       if (ScalarVT != MVT::f32) {
8241         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8242                           DAG.getTargetConstant(0, DL, MVT::i32));
8243       }
8244       return Cvt;
8245     }
8246   }
8247 
8248   return SDValue();
8249 }
8250 
8251 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8252 
8253 // This is a variant of
8254 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8255 //
8256 // The normal DAG combiner will do this, but only if the add has one use since
8257 // that would increase the number of instructions.
8258 //
8259 // This prevents us from seeing a constant offset that can be folded into a
8260 // memory instruction's addressing mode. If we know the resulting add offset of
8261 // a pointer can be folded into an addressing offset, we can replace the pointer
8262 // operand with the add of new constant offset. This eliminates one of the uses,
8263 // and may allow the remaining use to also be simplified.
8264 //
8265 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8266                                                unsigned AddrSpace,
8267                                                EVT MemVT,
8268                                                DAGCombinerInfo &DCI) const {
8269   SDValue N0 = N->getOperand(0);
8270   SDValue N1 = N->getOperand(1);
8271 
8272   // We only do this to handle cases where it's profitable when there are
8273   // multiple uses of the add, so defer to the standard combine.
8274   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8275       N0->hasOneUse())
8276     return SDValue();
8277 
8278   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8279   if (!CN1)
8280     return SDValue();
8281 
8282   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8283   if (!CAdd)
8284     return SDValue();
8285 
8286   // If the resulting offset is too large, we can't fold it into the addressing
8287   // mode offset.
8288   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8289   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8290 
8291   AddrMode AM;
8292   AM.HasBaseReg = true;
8293   AM.BaseOffs = Offset.getSExtValue();
8294   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8295     return SDValue();
8296 
8297   SelectionDAG &DAG = DCI.DAG;
8298   SDLoc SL(N);
8299   EVT VT = N->getValueType(0);
8300 
8301   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8302   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8303 
8304   SDNodeFlags Flags;
8305   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8306                           (N0.getOpcode() == ISD::OR ||
8307                            N0->getFlags().hasNoUnsignedWrap()));
8308 
8309   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8310 }
8311 
8312 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8313                                                   DAGCombinerInfo &DCI) const {
8314   SDValue Ptr = N->getBasePtr();
8315   SelectionDAG &DAG = DCI.DAG;
8316   SDLoc SL(N);
8317 
8318   // TODO: We could also do this for multiplies.
8319   if (Ptr.getOpcode() == ISD::SHL) {
8320     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8321                                           N->getMemoryVT(), DCI);
8322     if (NewPtr) {
8323       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8324 
8325       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8326       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8327     }
8328   }
8329 
8330   return SDValue();
8331 }
8332 
8333 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8334   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8335          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8336          (Opc == ISD::XOR && Val == 0);
8337 }
8338 
8339 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8340 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8341 // integer combine opportunities since most 64-bit operations are decomposed
8342 // this way.  TODO: We won't want this for SALU especially if it is an inline
8343 // immediate.
8344 SDValue SITargetLowering::splitBinaryBitConstantOp(
8345   DAGCombinerInfo &DCI,
8346   const SDLoc &SL,
8347   unsigned Opc, SDValue LHS,
8348   const ConstantSDNode *CRHS) const {
8349   uint64_t Val = CRHS->getZExtValue();
8350   uint32_t ValLo = Lo_32(Val);
8351   uint32_t ValHi = Hi_32(Val);
8352   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8353 
8354     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8355          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8356         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8357     // If we need to materialize a 64-bit immediate, it will be split up later
8358     // anyway. Avoid creating the harder to understand 64-bit immediate
8359     // materialization.
8360     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8361   }
8362 
8363   return SDValue();
8364 }
8365 
8366 // Returns true if argument is a boolean value which is not serialized into
8367 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8368 static bool isBoolSGPR(SDValue V) {
8369   if (V.getValueType() != MVT::i1)
8370     return false;
8371   switch (V.getOpcode()) {
8372   default: break;
8373   case ISD::SETCC:
8374   case ISD::AND:
8375   case ISD::OR:
8376   case ISD::XOR:
8377   case AMDGPUISD::FP_CLASS:
8378     return true;
8379   }
8380   return false;
8381 }
8382 
8383 // If a constant has all zeroes or all ones within each byte return it.
8384 // Otherwise return 0.
8385 static uint32_t getConstantPermuteMask(uint32_t C) {
8386   // 0xff for any zero byte in the mask
8387   uint32_t ZeroByteMask = 0;
8388   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8389   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8390   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8391   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8392   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8393   if ((NonZeroByteMask & C) != NonZeroByteMask)
8394     return 0; // Partial bytes selected.
8395   return C;
8396 }
8397 
8398 // Check if a node selects whole bytes from its operand 0 starting at a byte
8399 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8400 // or -1 if not succeeded.
8401 // Note byte select encoding:
8402 // value 0-3 selects corresponding source byte;
8403 // value 0xc selects zero;
8404 // value 0xff selects 0xff.
8405 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8406   assert(V.getValueSizeInBits() == 32);
8407 
8408   if (V.getNumOperands() != 2)
8409     return ~0;
8410 
8411   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8412   if (!N1)
8413     return ~0;
8414 
8415   uint32_t C = N1->getZExtValue();
8416 
8417   switch (V.getOpcode()) {
8418   default:
8419     break;
8420   case ISD::AND:
8421     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8422       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8423     }
8424     break;
8425 
8426   case ISD::OR:
8427     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8428       return (0x03020100 & ~ConstMask) | ConstMask;
8429     }
8430     break;
8431 
8432   case ISD::SHL:
8433     if (C % 8)
8434       return ~0;
8435 
8436     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8437 
8438   case ISD::SRL:
8439     if (C % 8)
8440       return ~0;
8441 
8442     return uint32_t(0x0c0c0c0c03020100ull >> C);
8443   }
8444 
8445   return ~0;
8446 }
8447 
8448 SDValue SITargetLowering::performAndCombine(SDNode *N,
8449                                             DAGCombinerInfo &DCI) const {
8450   if (DCI.isBeforeLegalize())
8451     return SDValue();
8452 
8453   SelectionDAG &DAG = DCI.DAG;
8454   EVT VT = N->getValueType(0);
8455   SDValue LHS = N->getOperand(0);
8456   SDValue RHS = N->getOperand(1);
8457 
8458 
8459   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8460   if (VT == MVT::i64 && CRHS) {
8461     if (SDValue Split
8462         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8463       return Split;
8464   }
8465 
8466   if (CRHS && VT == MVT::i32) {
8467     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8468     // nb = number of trailing zeroes in mask
8469     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8470     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8471     uint64_t Mask = CRHS->getZExtValue();
8472     unsigned Bits = countPopulation(Mask);
8473     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8474         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8475       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8476         unsigned Shift = CShift->getZExtValue();
8477         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8478         unsigned Offset = NB + Shift;
8479         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8480           SDLoc SL(N);
8481           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8482                                     LHS->getOperand(0),
8483                                     DAG.getConstant(Offset, SL, MVT::i32),
8484                                     DAG.getConstant(Bits, SL, MVT::i32));
8485           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8486           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8487                                     DAG.getValueType(NarrowVT));
8488           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8489                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8490           return Shl;
8491         }
8492       }
8493     }
8494 
8495     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8496     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8497         isa<ConstantSDNode>(LHS.getOperand(2))) {
8498       uint32_t Sel = getConstantPermuteMask(Mask);
8499       if (!Sel)
8500         return SDValue();
8501 
8502       // Select 0xc for all zero bytes
8503       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8504       SDLoc DL(N);
8505       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8506                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8507     }
8508   }
8509 
8510   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8511   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8512   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8513     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8514     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8515 
8516     SDValue X = LHS.getOperand(0);
8517     SDValue Y = RHS.getOperand(0);
8518     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8519       return SDValue();
8520 
8521     if (LCC == ISD::SETO) {
8522       if (X != LHS.getOperand(1))
8523         return SDValue();
8524 
8525       if (RCC == ISD::SETUNE) {
8526         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8527         if (!C1 || !C1->isInfinity() || C1->isNegative())
8528           return SDValue();
8529 
8530         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8531                               SIInstrFlags::N_SUBNORMAL |
8532                               SIInstrFlags::N_ZERO |
8533                               SIInstrFlags::P_ZERO |
8534                               SIInstrFlags::P_SUBNORMAL |
8535                               SIInstrFlags::P_NORMAL;
8536 
8537         static_assert(((~(SIInstrFlags::S_NAN |
8538                           SIInstrFlags::Q_NAN |
8539                           SIInstrFlags::N_INFINITY |
8540                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8541                       "mask not equal");
8542 
8543         SDLoc DL(N);
8544         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8545                            X, DAG.getConstant(Mask, DL, MVT::i32));
8546       }
8547     }
8548   }
8549 
8550   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8551     std::swap(LHS, RHS);
8552 
8553   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8554       RHS.hasOneUse()) {
8555     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8556     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8557     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8558     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8559     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8560         (RHS.getOperand(0) == LHS.getOperand(0) &&
8561          LHS.getOperand(0) == LHS.getOperand(1))) {
8562       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8563       unsigned NewMask = LCC == ISD::SETO ?
8564         Mask->getZExtValue() & ~OrdMask :
8565         Mask->getZExtValue() & OrdMask;
8566 
8567       SDLoc DL(N);
8568       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8569                          DAG.getConstant(NewMask, DL, MVT::i32));
8570     }
8571   }
8572 
8573   if (VT == MVT::i32 &&
8574       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8575     // and x, (sext cc from i1) => select cc, x, 0
8576     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8577       std::swap(LHS, RHS);
8578     if (isBoolSGPR(RHS.getOperand(0)))
8579       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8580                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8581   }
8582 
8583   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8584   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8585   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8586       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8587     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8588     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8589     if (LHSMask != ~0u && RHSMask != ~0u) {
8590       // Canonicalize the expression in an attempt to have fewer unique masks
8591       // and therefore fewer registers used to hold the masks.
8592       if (LHSMask > RHSMask) {
8593         std::swap(LHSMask, RHSMask);
8594         std::swap(LHS, RHS);
8595       }
8596 
8597       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8598       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8599       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8600       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8601 
8602       // Check of we need to combine values from two sources within a byte.
8603       if (!(LHSUsedLanes & RHSUsedLanes) &&
8604           // If we select high and lower word keep it for SDWA.
8605           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8606           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8607         // Each byte in each mask is either selector mask 0-3, or has higher
8608         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8609         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8610         // mask which is not 0xff wins. By anding both masks we have a correct
8611         // result except that 0x0c shall be corrected to give 0x0c only.
8612         uint32_t Mask = LHSMask & RHSMask;
8613         for (unsigned I = 0; I < 32; I += 8) {
8614           uint32_t ByteSel = 0xff << I;
8615           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8616             Mask &= (0x0c << I) & 0xffffffff;
8617         }
8618 
8619         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8620         // or 0x0c.
8621         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8622         SDLoc DL(N);
8623 
8624         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8625                            LHS.getOperand(0), RHS.getOperand(0),
8626                            DAG.getConstant(Sel, DL, MVT::i32));
8627       }
8628     }
8629   }
8630 
8631   return SDValue();
8632 }
8633 
8634 SDValue SITargetLowering::performOrCombine(SDNode *N,
8635                                            DAGCombinerInfo &DCI) const {
8636   SelectionDAG &DAG = DCI.DAG;
8637   SDValue LHS = N->getOperand(0);
8638   SDValue RHS = N->getOperand(1);
8639 
8640   EVT VT = N->getValueType(0);
8641   if (VT == MVT::i1) {
8642     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8643     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8644         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8645       SDValue Src = LHS.getOperand(0);
8646       if (Src != RHS.getOperand(0))
8647         return SDValue();
8648 
8649       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8650       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8651       if (!CLHS || !CRHS)
8652         return SDValue();
8653 
8654       // Only 10 bits are used.
8655       static const uint32_t MaxMask = 0x3ff;
8656 
8657       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8658       SDLoc DL(N);
8659       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8660                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8661     }
8662 
8663     return SDValue();
8664   }
8665 
8666   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8667   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8668       LHS.getOpcode() == AMDGPUISD::PERM &&
8669       isa<ConstantSDNode>(LHS.getOperand(2))) {
8670     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8671     if (!Sel)
8672       return SDValue();
8673 
8674     Sel |= LHS.getConstantOperandVal(2);
8675     SDLoc DL(N);
8676     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8677                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8678   }
8679 
8680   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8681   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8682   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8683       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8684     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8685     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8686     if (LHSMask != ~0u && RHSMask != ~0u) {
8687       // Canonicalize the expression in an attempt to have fewer unique masks
8688       // and therefore fewer registers used to hold the masks.
8689       if (LHSMask > RHSMask) {
8690         std::swap(LHSMask, RHSMask);
8691         std::swap(LHS, RHS);
8692       }
8693 
8694       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8695       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8696       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8697       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8698 
8699       // Check of we need to combine values from two sources within a byte.
8700       if (!(LHSUsedLanes & RHSUsedLanes) &&
8701           // If we select high and lower word keep it for SDWA.
8702           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8703           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8704         // Kill zero bytes selected by other mask. Zero value is 0xc.
8705         LHSMask &= ~RHSUsedLanes;
8706         RHSMask &= ~LHSUsedLanes;
8707         // Add 4 to each active LHS lane
8708         LHSMask |= LHSUsedLanes & 0x04040404;
8709         // Combine masks
8710         uint32_t Sel = LHSMask | RHSMask;
8711         SDLoc DL(N);
8712 
8713         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8714                            LHS.getOperand(0), RHS.getOperand(0),
8715                            DAG.getConstant(Sel, DL, MVT::i32));
8716       }
8717     }
8718   }
8719 
8720   if (VT != MVT::i64)
8721     return SDValue();
8722 
8723   // TODO: This could be a generic combine with a predicate for extracting the
8724   // high half of an integer being free.
8725 
8726   // (or i64:x, (zero_extend i32:y)) ->
8727   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8728   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8729       RHS.getOpcode() != ISD::ZERO_EXTEND)
8730     std::swap(LHS, RHS);
8731 
8732   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8733     SDValue ExtSrc = RHS.getOperand(0);
8734     EVT SrcVT = ExtSrc.getValueType();
8735     if (SrcVT == MVT::i32) {
8736       SDLoc SL(N);
8737       SDValue LowLHS, HiBits;
8738       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8739       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8740 
8741       DCI.AddToWorklist(LowOr.getNode());
8742       DCI.AddToWorklist(HiBits.getNode());
8743 
8744       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8745                                 LowOr, HiBits);
8746       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8747     }
8748   }
8749 
8750   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8751   if (CRHS) {
8752     if (SDValue Split
8753           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8754       return Split;
8755   }
8756 
8757   return SDValue();
8758 }
8759 
8760 SDValue SITargetLowering::performXorCombine(SDNode *N,
8761                                             DAGCombinerInfo &DCI) const {
8762   EVT VT = N->getValueType(0);
8763   if (VT != MVT::i64)
8764     return SDValue();
8765 
8766   SDValue LHS = N->getOperand(0);
8767   SDValue RHS = N->getOperand(1);
8768 
8769   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8770   if (CRHS) {
8771     if (SDValue Split
8772           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8773       return Split;
8774   }
8775 
8776   return SDValue();
8777 }
8778 
8779 // Instructions that will be lowered with a final instruction that zeros the
8780 // high result bits.
8781 // XXX - probably only need to list legal operations.
8782 static bool fp16SrcZerosHighBits(unsigned Opc) {
8783   switch (Opc) {
8784   case ISD::FADD:
8785   case ISD::FSUB:
8786   case ISD::FMUL:
8787   case ISD::FDIV:
8788   case ISD::FREM:
8789   case ISD::FMA:
8790   case ISD::FMAD:
8791   case ISD::FCANONICALIZE:
8792   case ISD::FP_ROUND:
8793   case ISD::UINT_TO_FP:
8794   case ISD::SINT_TO_FP:
8795   case ISD::FABS:
8796     // Fabs is lowered to a bit operation, but it's an and which will clear the
8797     // high bits anyway.
8798   case ISD::FSQRT:
8799   case ISD::FSIN:
8800   case ISD::FCOS:
8801   case ISD::FPOWI:
8802   case ISD::FPOW:
8803   case ISD::FLOG:
8804   case ISD::FLOG2:
8805   case ISD::FLOG10:
8806   case ISD::FEXP:
8807   case ISD::FEXP2:
8808   case ISD::FCEIL:
8809   case ISD::FTRUNC:
8810   case ISD::FRINT:
8811   case ISD::FNEARBYINT:
8812   case ISD::FROUND:
8813   case ISD::FFLOOR:
8814   case ISD::FMINNUM:
8815   case ISD::FMAXNUM:
8816   case AMDGPUISD::FRACT:
8817   case AMDGPUISD::CLAMP:
8818   case AMDGPUISD::COS_HW:
8819   case AMDGPUISD::SIN_HW:
8820   case AMDGPUISD::FMIN3:
8821   case AMDGPUISD::FMAX3:
8822   case AMDGPUISD::FMED3:
8823   case AMDGPUISD::FMAD_FTZ:
8824   case AMDGPUISD::RCP:
8825   case AMDGPUISD::RSQ:
8826   case AMDGPUISD::RCP_IFLAG:
8827   case AMDGPUISD::LDEXP:
8828     return true;
8829   default:
8830     // fcopysign, select and others may be lowered to 32-bit bit operations
8831     // which don't zero the high bits.
8832     return false;
8833   }
8834 }
8835 
8836 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8837                                                    DAGCombinerInfo &DCI) const {
8838   if (!Subtarget->has16BitInsts() ||
8839       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8840     return SDValue();
8841 
8842   EVT VT = N->getValueType(0);
8843   if (VT != MVT::i32)
8844     return SDValue();
8845 
8846   SDValue Src = N->getOperand(0);
8847   if (Src.getValueType() != MVT::i16)
8848     return SDValue();
8849 
8850   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8851   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8852   if (Src.getOpcode() == ISD::BITCAST) {
8853     SDValue BCSrc = Src.getOperand(0);
8854     if (BCSrc.getValueType() == MVT::f16 &&
8855         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8856       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8857   }
8858 
8859   return SDValue();
8860 }
8861 
8862 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8863                                                         DAGCombinerInfo &DCI)
8864                                                         const {
8865   SDValue Src = N->getOperand(0);
8866   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8867 
8868   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8869       VTSign->getVT() == MVT::i8) ||
8870       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8871       VTSign->getVT() == MVT::i16)) &&
8872       Src.hasOneUse()) {
8873     auto *M = cast<MemSDNode>(Src);
8874     SDValue Ops[] = {
8875       Src.getOperand(0), // Chain
8876       Src.getOperand(1), // rsrc
8877       Src.getOperand(2), // vindex
8878       Src.getOperand(3), // voffset
8879       Src.getOperand(4), // soffset
8880       Src.getOperand(5), // offset
8881       Src.getOperand(6),
8882       Src.getOperand(7)
8883     };
8884     // replace with BUFFER_LOAD_BYTE/SHORT
8885     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8886                                          Src.getOperand(0).getValueType());
8887     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8888                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8889     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8890                                                           ResList,
8891                                                           Ops, M->getMemoryVT(),
8892                                                           M->getMemOperand());
8893     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8894                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8895   }
8896   return SDValue();
8897 }
8898 
8899 SDValue SITargetLowering::performClassCombine(SDNode *N,
8900                                               DAGCombinerInfo &DCI) const {
8901   SelectionDAG &DAG = DCI.DAG;
8902   SDValue Mask = N->getOperand(1);
8903 
8904   // fp_class x, 0 -> false
8905   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8906     if (CMask->isNullValue())
8907       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8908   }
8909 
8910   if (N->getOperand(0).isUndef())
8911     return DAG.getUNDEF(MVT::i1);
8912 
8913   return SDValue();
8914 }
8915 
8916 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8917                                             DAGCombinerInfo &DCI) const {
8918   EVT VT = N->getValueType(0);
8919   SDValue N0 = N->getOperand(0);
8920 
8921   if (N0.isUndef())
8922     return N0;
8923 
8924   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8925                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8926     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8927                            N->getFlags());
8928   }
8929 
8930   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8931     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8932                            N0.getOperand(0), N->getFlags());
8933   }
8934 
8935   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8936 }
8937 
8938 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8939                                        unsigned MaxDepth) const {
8940   unsigned Opcode = Op.getOpcode();
8941   if (Opcode == ISD::FCANONICALIZE)
8942     return true;
8943 
8944   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8945     auto F = CFP->getValueAPF();
8946     if (F.isNaN() && F.isSignaling())
8947       return false;
8948     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8949   }
8950 
8951   // If source is a result of another standard FP operation it is already in
8952   // canonical form.
8953   if (MaxDepth == 0)
8954     return false;
8955 
8956   switch (Opcode) {
8957   // These will flush denorms if required.
8958   case ISD::FADD:
8959   case ISD::FSUB:
8960   case ISD::FMUL:
8961   case ISD::FCEIL:
8962   case ISD::FFLOOR:
8963   case ISD::FMA:
8964   case ISD::FMAD:
8965   case ISD::FSQRT:
8966   case ISD::FDIV:
8967   case ISD::FREM:
8968   case ISD::FP_ROUND:
8969   case ISD::FP_EXTEND:
8970   case AMDGPUISD::FMUL_LEGACY:
8971   case AMDGPUISD::FMAD_FTZ:
8972   case AMDGPUISD::RCP:
8973   case AMDGPUISD::RSQ:
8974   case AMDGPUISD::RSQ_CLAMP:
8975   case AMDGPUISD::RCP_LEGACY:
8976   case AMDGPUISD::RCP_IFLAG:
8977   case AMDGPUISD::TRIG_PREOP:
8978   case AMDGPUISD::DIV_SCALE:
8979   case AMDGPUISD::DIV_FMAS:
8980   case AMDGPUISD::DIV_FIXUP:
8981   case AMDGPUISD::FRACT:
8982   case AMDGPUISD::LDEXP:
8983   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8984   case AMDGPUISD::CVT_F32_UBYTE0:
8985   case AMDGPUISD::CVT_F32_UBYTE1:
8986   case AMDGPUISD::CVT_F32_UBYTE2:
8987   case AMDGPUISD::CVT_F32_UBYTE3:
8988     return true;
8989 
8990   // It can/will be lowered or combined as a bit operation.
8991   // Need to check their input recursively to handle.
8992   case ISD::FNEG:
8993   case ISD::FABS:
8994   case ISD::FCOPYSIGN:
8995     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8996 
8997   case ISD::FSIN:
8998   case ISD::FCOS:
8999   case ISD::FSINCOS:
9000     return Op.getValueType().getScalarType() != MVT::f16;
9001 
9002   case ISD::FMINNUM:
9003   case ISD::FMAXNUM:
9004   case ISD::FMINNUM_IEEE:
9005   case ISD::FMAXNUM_IEEE:
9006   case AMDGPUISD::CLAMP:
9007   case AMDGPUISD::FMED3:
9008   case AMDGPUISD::FMAX3:
9009   case AMDGPUISD::FMIN3: {
9010     // FIXME: Shouldn't treat the generic operations different based these.
9011     // However, we aren't really required to flush the result from
9012     // minnum/maxnum..
9013 
9014     // snans will be quieted, so we only need to worry about denormals.
9015     if (Subtarget->supportsMinMaxDenormModes() ||
9016         denormalsEnabledForType(DAG, Op.getValueType()))
9017       return true;
9018 
9019     // Flushing may be required.
9020     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9021     // targets need to check their input recursively.
9022 
9023     // FIXME: Does this apply with clamp? It's implemented with max.
9024     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9025       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9026         return false;
9027     }
9028 
9029     return true;
9030   }
9031   case ISD::SELECT: {
9032     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9033            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9034   }
9035   case ISD::BUILD_VECTOR: {
9036     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9037       SDValue SrcOp = Op.getOperand(i);
9038       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9039         return false;
9040     }
9041 
9042     return true;
9043   }
9044   case ISD::EXTRACT_VECTOR_ELT:
9045   case ISD::EXTRACT_SUBVECTOR: {
9046     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9047   }
9048   case ISD::INSERT_VECTOR_ELT: {
9049     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9050            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9051   }
9052   case ISD::UNDEF:
9053     // Could be anything.
9054     return false;
9055 
9056   case ISD::BITCAST: {
9057     // Hack round the mess we make when legalizing extract_vector_elt
9058     SDValue Src = Op.getOperand(0);
9059     if (Src.getValueType() == MVT::i16 &&
9060         Src.getOpcode() == ISD::TRUNCATE) {
9061       SDValue TruncSrc = Src.getOperand(0);
9062       if (TruncSrc.getValueType() == MVT::i32 &&
9063           TruncSrc.getOpcode() == ISD::BITCAST &&
9064           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9065         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9066       }
9067     }
9068 
9069     return false;
9070   }
9071   case ISD::INTRINSIC_WO_CHAIN: {
9072     unsigned IntrinsicID
9073       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9074     // TODO: Handle more intrinsics
9075     switch (IntrinsicID) {
9076     case Intrinsic::amdgcn_cvt_pkrtz:
9077     case Intrinsic::amdgcn_cubeid:
9078     case Intrinsic::amdgcn_frexp_mant:
9079     case Intrinsic::amdgcn_fdot2:
9080     case Intrinsic::amdgcn_rcp:
9081     case Intrinsic::amdgcn_rsq:
9082     case Intrinsic::amdgcn_rsq_clamp:
9083     case Intrinsic::amdgcn_rcp_legacy:
9084     case Intrinsic::amdgcn_rsq_legacy:
9085       return true;
9086     default:
9087       break;
9088     }
9089 
9090     LLVM_FALLTHROUGH;
9091   }
9092   default:
9093     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9094            DAG.isKnownNeverSNaN(Op);
9095   }
9096 
9097   llvm_unreachable("invalid operation");
9098 }
9099 
9100 // Constant fold canonicalize.
9101 SDValue SITargetLowering::getCanonicalConstantFP(
9102   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9103   // Flush denormals to 0 if not enabled.
9104   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9105     return DAG.getConstantFP(0.0, SL, VT);
9106 
9107   if (C.isNaN()) {
9108     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9109     if (C.isSignaling()) {
9110       // Quiet a signaling NaN.
9111       // FIXME: Is this supposed to preserve payload bits?
9112       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9113     }
9114 
9115     // Make sure it is the canonical NaN bitpattern.
9116     //
9117     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9118     // immediate?
9119     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9120       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9121   }
9122 
9123   // Already canonical.
9124   return DAG.getConstantFP(C, SL, VT);
9125 }
9126 
9127 static bool vectorEltWillFoldAway(SDValue Op) {
9128   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9129 }
9130 
9131 SDValue SITargetLowering::performFCanonicalizeCombine(
9132   SDNode *N,
9133   DAGCombinerInfo &DCI) const {
9134   SelectionDAG &DAG = DCI.DAG;
9135   SDValue N0 = N->getOperand(0);
9136   EVT VT = N->getValueType(0);
9137 
9138   // fcanonicalize undef -> qnan
9139   if (N0.isUndef()) {
9140     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9141     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9142   }
9143 
9144   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9145     EVT VT = N->getValueType(0);
9146     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9147   }
9148 
9149   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9150   //                                                   (fcanonicalize k)
9151   //
9152   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9153 
9154   // TODO: This could be better with wider vectors that will be split to v2f16,
9155   // and to consider uses since there aren't that many packed operations.
9156   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9157       isTypeLegal(MVT::v2f16)) {
9158     SDLoc SL(N);
9159     SDValue NewElts[2];
9160     SDValue Lo = N0.getOperand(0);
9161     SDValue Hi = N0.getOperand(1);
9162     EVT EltVT = Lo.getValueType();
9163 
9164     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9165       for (unsigned I = 0; I != 2; ++I) {
9166         SDValue Op = N0.getOperand(I);
9167         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9168           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9169                                               CFP->getValueAPF());
9170         } else if (Op.isUndef()) {
9171           // Handled below based on what the other operand is.
9172           NewElts[I] = Op;
9173         } else {
9174           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9175         }
9176       }
9177 
9178       // If one half is undef, and one is constant, perfer a splat vector rather
9179       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9180       // cheaper to use and may be free with a packed operation.
9181       if (NewElts[0].isUndef()) {
9182         if (isa<ConstantFPSDNode>(NewElts[1]))
9183           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9184             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9185       }
9186 
9187       if (NewElts[1].isUndef()) {
9188         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9189           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9190       }
9191 
9192       return DAG.getBuildVector(VT, SL, NewElts);
9193     }
9194   }
9195 
9196   unsigned SrcOpc = N0.getOpcode();
9197 
9198   // If it's free to do so, push canonicalizes further up the source, which may
9199   // find a canonical source.
9200   //
9201   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9202   // sNaNs.
9203   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9204     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9205     if (CRHS && N0.hasOneUse()) {
9206       SDLoc SL(N);
9207       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9208                                    N0.getOperand(0));
9209       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9210       DCI.AddToWorklist(Canon0.getNode());
9211 
9212       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9213     }
9214   }
9215 
9216   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9217 }
9218 
9219 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9220   switch (Opc) {
9221   case ISD::FMAXNUM:
9222   case ISD::FMAXNUM_IEEE:
9223     return AMDGPUISD::FMAX3;
9224   case ISD::SMAX:
9225     return AMDGPUISD::SMAX3;
9226   case ISD::UMAX:
9227     return AMDGPUISD::UMAX3;
9228   case ISD::FMINNUM:
9229   case ISD::FMINNUM_IEEE:
9230     return AMDGPUISD::FMIN3;
9231   case ISD::SMIN:
9232     return AMDGPUISD::SMIN3;
9233   case ISD::UMIN:
9234     return AMDGPUISD::UMIN3;
9235   default:
9236     llvm_unreachable("Not a min/max opcode");
9237   }
9238 }
9239 
9240 SDValue SITargetLowering::performIntMed3ImmCombine(
9241   SelectionDAG &DAG, const SDLoc &SL,
9242   SDValue Op0, SDValue Op1, bool Signed) const {
9243   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9244   if (!K1)
9245     return SDValue();
9246 
9247   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9248   if (!K0)
9249     return SDValue();
9250 
9251   if (Signed) {
9252     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9253       return SDValue();
9254   } else {
9255     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9256       return SDValue();
9257   }
9258 
9259   EVT VT = K0->getValueType(0);
9260   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9261   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9262     return DAG.getNode(Med3Opc, SL, VT,
9263                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9264   }
9265 
9266   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9267   MVT NVT = MVT::i32;
9268   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9269 
9270   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9271   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9272   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9273 
9274   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9275   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9276 }
9277 
9278 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9279   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9280     return C;
9281 
9282   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9283     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9284       return C;
9285   }
9286 
9287   return nullptr;
9288 }
9289 
9290 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9291                                                   const SDLoc &SL,
9292                                                   SDValue Op0,
9293                                                   SDValue Op1) const {
9294   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9295   if (!K1)
9296     return SDValue();
9297 
9298   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9299   if (!K0)
9300     return SDValue();
9301 
9302   // Ordered >= (although NaN inputs should have folded away by now).
9303   if (K0->getValueAPF() > K1->getValueAPF())
9304     return SDValue();
9305 
9306   const MachineFunction &MF = DAG.getMachineFunction();
9307   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9308 
9309   // TODO: Check IEEE bit enabled?
9310   EVT VT = Op0.getValueType();
9311   if (Info->getMode().DX10Clamp) {
9312     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9313     // hardware fmed3 behavior converting to a min.
9314     // FIXME: Should this be allowing -0.0?
9315     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9316       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9317   }
9318 
9319   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9320   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9321     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9322     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9323     // then give the other result, which is different from med3 with a NaN
9324     // input.
9325     SDValue Var = Op0.getOperand(0);
9326     if (!DAG.isKnownNeverSNaN(Var))
9327       return SDValue();
9328 
9329     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9330 
9331     if ((!K0->hasOneUse() ||
9332          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9333         (!K1->hasOneUse() ||
9334          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9335       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9336                          Var, SDValue(K0, 0), SDValue(K1, 0));
9337     }
9338   }
9339 
9340   return SDValue();
9341 }
9342 
9343 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9344                                                DAGCombinerInfo &DCI) const {
9345   SelectionDAG &DAG = DCI.DAG;
9346 
9347   EVT VT = N->getValueType(0);
9348   unsigned Opc = N->getOpcode();
9349   SDValue Op0 = N->getOperand(0);
9350   SDValue Op1 = N->getOperand(1);
9351 
9352   // Only do this if the inner op has one use since this will just increases
9353   // register pressure for no benefit.
9354 
9355   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9356       !VT.isVector() &&
9357       (VT == MVT::i32 || VT == MVT::f32 ||
9358        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9359     // max(max(a, b), c) -> max3(a, b, c)
9360     // min(min(a, b), c) -> min3(a, b, c)
9361     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9362       SDLoc DL(N);
9363       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9364                          DL,
9365                          N->getValueType(0),
9366                          Op0.getOperand(0),
9367                          Op0.getOperand(1),
9368                          Op1);
9369     }
9370 
9371     // Try commuted.
9372     // max(a, max(b, c)) -> max3(a, b, c)
9373     // min(a, min(b, c)) -> min3(a, b, c)
9374     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9375       SDLoc DL(N);
9376       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9377                          DL,
9378                          N->getValueType(0),
9379                          Op0,
9380                          Op1.getOperand(0),
9381                          Op1.getOperand(1));
9382     }
9383   }
9384 
9385   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9386   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9387     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9388       return Med3;
9389   }
9390 
9391   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9392     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9393       return Med3;
9394   }
9395 
9396   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9397   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9398        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9399        (Opc == AMDGPUISD::FMIN_LEGACY &&
9400         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9401       (VT == MVT::f32 || VT == MVT::f64 ||
9402        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9403        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9404       Op0.hasOneUse()) {
9405     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9406       return Res;
9407   }
9408 
9409   return SDValue();
9410 }
9411 
9412 static bool isClampZeroToOne(SDValue A, SDValue B) {
9413   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9414     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9415       // FIXME: Should this be allowing -0.0?
9416       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9417              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9418     }
9419   }
9420 
9421   return false;
9422 }
9423 
9424 // FIXME: Should only worry about snans for version with chain.
9425 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9426                                               DAGCombinerInfo &DCI) const {
9427   EVT VT = N->getValueType(0);
9428   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9429   // NaNs. With a NaN input, the order of the operands may change the result.
9430 
9431   SelectionDAG &DAG = DCI.DAG;
9432   SDLoc SL(N);
9433 
9434   SDValue Src0 = N->getOperand(0);
9435   SDValue Src1 = N->getOperand(1);
9436   SDValue Src2 = N->getOperand(2);
9437 
9438   if (isClampZeroToOne(Src0, Src1)) {
9439     // const_a, const_b, x -> clamp is safe in all cases including signaling
9440     // nans.
9441     // FIXME: Should this be allowing -0.0?
9442     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9443   }
9444 
9445   const MachineFunction &MF = DAG.getMachineFunction();
9446   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9447 
9448   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9449   // handling no dx10-clamp?
9450   if (Info->getMode().DX10Clamp) {
9451     // If NaNs is clamped to 0, we are free to reorder the inputs.
9452 
9453     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9454       std::swap(Src0, Src1);
9455 
9456     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9457       std::swap(Src1, Src2);
9458 
9459     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9460       std::swap(Src0, Src1);
9461 
9462     if (isClampZeroToOne(Src1, Src2))
9463       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9464   }
9465 
9466   return SDValue();
9467 }
9468 
9469 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9470                                                  DAGCombinerInfo &DCI) const {
9471   SDValue Src0 = N->getOperand(0);
9472   SDValue Src1 = N->getOperand(1);
9473   if (Src0.isUndef() && Src1.isUndef())
9474     return DCI.DAG.getUNDEF(N->getValueType(0));
9475   return SDValue();
9476 }
9477 
9478 SDValue SITargetLowering::performExtractVectorEltCombine(
9479   SDNode *N, DAGCombinerInfo &DCI) const {
9480   SDValue Vec = N->getOperand(0);
9481   SelectionDAG &DAG = DCI.DAG;
9482 
9483   EVT VecVT = Vec.getValueType();
9484   EVT EltVT = VecVT.getVectorElementType();
9485 
9486   if ((Vec.getOpcode() == ISD::FNEG ||
9487        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9488     SDLoc SL(N);
9489     EVT EltVT = N->getValueType(0);
9490     SDValue Idx = N->getOperand(1);
9491     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9492                               Vec.getOperand(0), Idx);
9493     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9494   }
9495 
9496   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9497   //    =>
9498   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9499   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9500   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9501   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9502     SDLoc SL(N);
9503     EVT EltVT = N->getValueType(0);
9504     SDValue Idx = N->getOperand(1);
9505     unsigned Opc = Vec.getOpcode();
9506 
9507     switch(Opc) {
9508     default:
9509       break;
9510       // TODO: Support other binary operations.
9511     case ISD::FADD:
9512     case ISD::FSUB:
9513     case ISD::FMUL:
9514     case ISD::ADD:
9515     case ISD::UMIN:
9516     case ISD::UMAX:
9517     case ISD::SMIN:
9518     case ISD::SMAX:
9519     case ISD::FMAXNUM:
9520     case ISD::FMINNUM:
9521     case ISD::FMAXNUM_IEEE:
9522     case ISD::FMINNUM_IEEE: {
9523       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9524                                  Vec.getOperand(0), Idx);
9525       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9526                                  Vec.getOperand(1), Idx);
9527 
9528       DCI.AddToWorklist(Elt0.getNode());
9529       DCI.AddToWorklist(Elt1.getNode());
9530       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9531     }
9532     }
9533   }
9534 
9535   unsigned VecSize = VecVT.getSizeInBits();
9536   unsigned EltSize = EltVT.getSizeInBits();
9537 
9538   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9539   // This elminates non-constant index and subsequent movrel or scratch access.
9540   // Sub-dword vectors of size 2 dword or less have better implementation.
9541   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9542   // instructions.
9543   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9544       !isa<ConstantSDNode>(N->getOperand(1))) {
9545     SDLoc SL(N);
9546     SDValue Idx = N->getOperand(1);
9547     SDValue V;
9548     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9549       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9550       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9551       if (I == 0)
9552         V = Elt;
9553       else
9554         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9555     }
9556     return V;
9557   }
9558 
9559   if (!DCI.isBeforeLegalize())
9560     return SDValue();
9561 
9562   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9563   // elements. This exposes more load reduction opportunities by replacing
9564   // multiple small extract_vector_elements with a single 32-bit extract.
9565   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9566   if (isa<MemSDNode>(Vec) &&
9567       EltSize <= 16 &&
9568       EltVT.isByteSized() &&
9569       VecSize > 32 &&
9570       VecSize % 32 == 0 &&
9571       Idx) {
9572     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9573 
9574     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9575     unsigned EltIdx = BitIndex / 32;
9576     unsigned LeftoverBitIdx = BitIndex % 32;
9577     SDLoc SL(N);
9578 
9579     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9580     DCI.AddToWorklist(Cast.getNode());
9581 
9582     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9583                               DAG.getConstant(EltIdx, SL, MVT::i32));
9584     DCI.AddToWorklist(Elt.getNode());
9585     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9586                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9587     DCI.AddToWorklist(Srl.getNode());
9588 
9589     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9590     DCI.AddToWorklist(Trunc.getNode());
9591     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9592   }
9593 
9594   return SDValue();
9595 }
9596 
9597 SDValue
9598 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9599                                                 DAGCombinerInfo &DCI) const {
9600   SDValue Vec = N->getOperand(0);
9601   SDValue Idx = N->getOperand(2);
9602   EVT VecVT = Vec.getValueType();
9603   EVT EltVT = VecVT.getVectorElementType();
9604   unsigned VecSize = VecVT.getSizeInBits();
9605   unsigned EltSize = EltVT.getSizeInBits();
9606 
9607   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9608   // => BUILD_VECTOR n x select (e, const-idx)
9609   // This elminates non-constant index and subsequent movrel or scratch access.
9610   // Sub-dword vectors of size 2 dword or less have better implementation.
9611   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9612   // instructions.
9613   if (isa<ConstantSDNode>(Idx) ||
9614       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9615     return SDValue();
9616 
9617   SelectionDAG &DAG = DCI.DAG;
9618   SDLoc SL(N);
9619   SDValue Ins = N->getOperand(1);
9620   EVT IdxVT = Idx.getValueType();
9621 
9622   SmallVector<SDValue, 16> Ops;
9623   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9624     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9625     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9626     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9627     Ops.push_back(V);
9628   }
9629 
9630   return DAG.getBuildVector(VecVT, SL, Ops);
9631 }
9632 
9633 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9634                                           const SDNode *N0,
9635                                           const SDNode *N1) const {
9636   EVT VT = N0->getValueType(0);
9637 
9638   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9639   // support denormals ever.
9640   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9641        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9642         getSubtarget()->hasMadF16())) &&
9643        isOperationLegal(ISD::FMAD, VT))
9644     return ISD::FMAD;
9645 
9646   const TargetOptions &Options = DAG.getTarget().Options;
9647   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9648        (N0->getFlags().hasAllowContract() &&
9649         N1->getFlags().hasAllowContract())) &&
9650       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9651     return ISD::FMA;
9652   }
9653 
9654   return 0;
9655 }
9656 
9657 // For a reassociatable opcode perform:
9658 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9659 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9660                                                SelectionDAG &DAG) const {
9661   EVT VT = N->getValueType(0);
9662   if (VT != MVT::i32 && VT != MVT::i64)
9663     return SDValue();
9664 
9665   unsigned Opc = N->getOpcode();
9666   SDValue Op0 = N->getOperand(0);
9667   SDValue Op1 = N->getOperand(1);
9668 
9669   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9670     return SDValue();
9671 
9672   if (Op0->isDivergent())
9673     std::swap(Op0, Op1);
9674 
9675   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9676     return SDValue();
9677 
9678   SDValue Op2 = Op1.getOperand(1);
9679   Op1 = Op1.getOperand(0);
9680   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9681     return SDValue();
9682 
9683   if (Op1->isDivergent())
9684     std::swap(Op1, Op2);
9685 
9686   // If either operand is constant this will conflict with
9687   // DAGCombiner::ReassociateOps().
9688   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9689       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9690     return SDValue();
9691 
9692   SDLoc SL(N);
9693   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9694   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9695 }
9696 
9697 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9698                            EVT VT,
9699                            SDValue N0, SDValue N1, SDValue N2,
9700                            bool Signed) {
9701   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9702   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9703   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9704   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9705 }
9706 
9707 SDValue SITargetLowering::performAddCombine(SDNode *N,
9708                                             DAGCombinerInfo &DCI) const {
9709   SelectionDAG &DAG = DCI.DAG;
9710   EVT VT = N->getValueType(0);
9711   SDLoc SL(N);
9712   SDValue LHS = N->getOperand(0);
9713   SDValue RHS = N->getOperand(1);
9714 
9715   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9716       && Subtarget->hasMad64_32() &&
9717       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9718       VT.getScalarSizeInBits() <= 64) {
9719     if (LHS.getOpcode() != ISD::MUL)
9720       std::swap(LHS, RHS);
9721 
9722     SDValue MulLHS = LHS.getOperand(0);
9723     SDValue MulRHS = LHS.getOperand(1);
9724     SDValue AddRHS = RHS;
9725 
9726     // TODO: Maybe restrict if SGPR inputs.
9727     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9728         numBitsUnsigned(MulRHS, DAG) <= 32) {
9729       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9730       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9731       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9732       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9733     }
9734 
9735     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9736       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9737       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9738       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9739       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9740     }
9741 
9742     return SDValue();
9743   }
9744 
9745   if (SDValue V = reassociateScalarOps(N, DAG)) {
9746     return V;
9747   }
9748 
9749   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9750     return SDValue();
9751 
9752   // add x, zext (setcc) => addcarry x, 0, setcc
9753   // add x, sext (setcc) => subcarry x, 0, setcc
9754   unsigned Opc = LHS.getOpcode();
9755   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9756       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9757     std::swap(RHS, LHS);
9758 
9759   Opc = RHS.getOpcode();
9760   switch (Opc) {
9761   default: break;
9762   case ISD::ZERO_EXTEND:
9763   case ISD::SIGN_EXTEND:
9764   case ISD::ANY_EXTEND: {
9765     auto Cond = RHS.getOperand(0);
9766     // If this won't be a real VOPC output, we would still need to insert an
9767     // extra instruction anyway.
9768     if (!isBoolSGPR(Cond))
9769       break;
9770     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9771     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9772     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9773     return DAG.getNode(Opc, SL, VTList, Args);
9774   }
9775   case ISD::ADDCARRY: {
9776     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9777     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9778     if (!C || C->getZExtValue() != 0) break;
9779     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9780     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9781   }
9782   }
9783   return SDValue();
9784 }
9785 
9786 SDValue SITargetLowering::performSubCombine(SDNode *N,
9787                                             DAGCombinerInfo &DCI) const {
9788   SelectionDAG &DAG = DCI.DAG;
9789   EVT VT = N->getValueType(0);
9790 
9791   if (VT != MVT::i32)
9792     return SDValue();
9793 
9794   SDLoc SL(N);
9795   SDValue LHS = N->getOperand(0);
9796   SDValue RHS = N->getOperand(1);
9797 
9798   // sub x, zext (setcc) => subcarry x, 0, setcc
9799   // sub x, sext (setcc) => addcarry x, 0, setcc
9800   unsigned Opc = RHS.getOpcode();
9801   switch (Opc) {
9802   default: break;
9803   case ISD::ZERO_EXTEND:
9804   case ISD::SIGN_EXTEND:
9805   case ISD::ANY_EXTEND: {
9806     auto Cond = RHS.getOperand(0);
9807     // If this won't be a real VOPC output, we would still need to insert an
9808     // extra instruction anyway.
9809     if (!isBoolSGPR(Cond))
9810       break;
9811     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9812     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9813     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9814     return DAG.getNode(Opc, SL, VTList, Args);
9815   }
9816   }
9817 
9818   if (LHS.getOpcode() == ISD::SUBCARRY) {
9819     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9820     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9821     if (!C || !C->isNullValue())
9822       return SDValue();
9823     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9824     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9825   }
9826   return SDValue();
9827 }
9828 
9829 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9830   DAGCombinerInfo &DCI) const {
9831 
9832   if (N->getValueType(0) != MVT::i32)
9833     return SDValue();
9834 
9835   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9836   if (!C || C->getZExtValue() != 0)
9837     return SDValue();
9838 
9839   SelectionDAG &DAG = DCI.DAG;
9840   SDValue LHS = N->getOperand(0);
9841 
9842   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9843   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9844   unsigned LHSOpc = LHS.getOpcode();
9845   unsigned Opc = N->getOpcode();
9846   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9847       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9848     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9849     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9850   }
9851   return SDValue();
9852 }
9853 
9854 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9855                                              DAGCombinerInfo &DCI) const {
9856   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9857     return SDValue();
9858 
9859   SelectionDAG &DAG = DCI.DAG;
9860   EVT VT = N->getValueType(0);
9861 
9862   SDLoc SL(N);
9863   SDValue LHS = N->getOperand(0);
9864   SDValue RHS = N->getOperand(1);
9865 
9866   // These should really be instruction patterns, but writing patterns with
9867   // source modiifiers is a pain.
9868 
9869   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9870   if (LHS.getOpcode() == ISD::FADD) {
9871     SDValue A = LHS.getOperand(0);
9872     if (A == LHS.getOperand(1)) {
9873       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9874       if (FusedOp != 0) {
9875         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9876         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9877       }
9878     }
9879   }
9880 
9881   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9882   if (RHS.getOpcode() == ISD::FADD) {
9883     SDValue A = RHS.getOperand(0);
9884     if (A == RHS.getOperand(1)) {
9885       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9886       if (FusedOp != 0) {
9887         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9888         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9889       }
9890     }
9891   }
9892 
9893   return SDValue();
9894 }
9895 
9896 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9897                                              DAGCombinerInfo &DCI) const {
9898   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9899     return SDValue();
9900 
9901   SelectionDAG &DAG = DCI.DAG;
9902   SDLoc SL(N);
9903   EVT VT = N->getValueType(0);
9904   assert(!VT.isVector());
9905 
9906   // Try to get the fneg to fold into the source modifier. This undoes generic
9907   // DAG combines and folds them into the mad.
9908   //
9909   // Only do this if we are not trying to support denormals. v_mad_f32 does
9910   // not support denormals ever.
9911   SDValue LHS = N->getOperand(0);
9912   SDValue RHS = N->getOperand(1);
9913   if (LHS.getOpcode() == ISD::FADD) {
9914     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9915     SDValue A = LHS.getOperand(0);
9916     if (A == LHS.getOperand(1)) {
9917       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9918       if (FusedOp != 0){
9919         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9920         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9921 
9922         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9923       }
9924     }
9925   }
9926 
9927   if (RHS.getOpcode() == ISD::FADD) {
9928     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9929 
9930     SDValue A = RHS.getOperand(0);
9931     if (A == RHS.getOperand(1)) {
9932       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9933       if (FusedOp != 0){
9934         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9935         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9936       }
9937     }
9938   }
9939 
9940   return SDValue();
9941 }
9942 
9943 SDValue SITargetLowering::performFMACombine(SDNode *N,
9944                                             DAGCombinerInfo &DCI) const {
9945   SelectionDAG &DAG = DCI.DAG;
9946   EVT VT = N->getValueType(0);
9947   SDLoc SL(N);
9948 
9949   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9950     return SDValue();
9951 
9952   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9953   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9954   SDValue Op1 = N->getOperand(0);
9955   SDValue Op2 = N->getOperand(1);
9956   SDValue FMA = N->getOperand(2);
9957 
9958   if (FMA.getOpcode() != ISD::FMA ||
9959       Op1.getOpcode() != ISD::FP_EXTEND ||
9960       Op2.getOpcode() != ISD::FP_EXTEND)
9961     return SDValue();
9962 
9963   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9964   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9965   // is sufficient to allow generaing fdot2.
9966   const TargetOptions &Options = DAG.getTarget().Options;
9967   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9968       (N->getFlags().hasAllowContract() &&
9969        FMA->getFlags().hasAllowContract())) {
9970     Op1 = Op1.getOperand(0);
9971     Op2 = Op2.getOperand(0);
9972     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9973         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9974       return SDValue();
9975 
9976     SDValue Vec1 = Op1.getOperand(0);
9977     SDValue Idx1 = Op1.getOperand(1);
9978     SDValue Vec2 = Op2.getOperand(0);
9979 
9980     SDValue FMAOp1 = FMA.getOperand(0);
9981     SDValue FMAOp2 = FMA.getOperand(1);
9982     SDValue FMAAcc = FMA.getOperand(2);
9983 
9984     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9985         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9986       return SDValue();
9987 
9988     FMAOp1 = FMAOp1.getOperand(0);
9989     FMAOp2 = FMAOp2.getOperand(0);
9990     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9991         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9992       return SDValue();
9993 
9994     SDValue Vec3 = FMAOp1.getOperand(0);
9995     SDValue Vec4 = FMAOp2.getOperand(0);
9996     SDValue Idx2 = FMAOp1.getOperand(1);
9997 
9998     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9999         // Idx1 and Idx2 cannot be the same.
10000         Idx1 == Idx2)
10001       return SDValue();
10002 
10003     if (Vec1 == Vec2 || Vec3 == Vec4)
10004       return SDValue();
10005 
10006     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10007       return SDValue();
10008 
10009     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10010         (Vec1 == Vec4 && Vec2 == Vec3)) {
10011       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10012                          DAG.getTargetConstant(0, SL, MVT::i1));
10013     }
10014   }
10015   return SDValue();
10016 }
10017 
10018 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10019                                               DAGCombinerInfo &DCI) const {
10020   SelectionDAG &DAG = DCI.DAG;
10021   SDLoc SL(N);
10022 
10023   SDValue LHS = N->getOperand(0);
10024   SDValue RHS = N->getOperand(1);
10025   EVT VT = LHS.getValueType();
10026   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10027 
10028   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10029   if (!CRHS) {
10030     CRHS = dyn_cast<ConstantSDNode>(LHS);
10031     if (CRHS) {
10032       std::swap(LHS, RHS);
10033       CC = getSetCCSwappedOperands(CC);
10034     }
10035   }
10036 
10037   if (CRHS) {
10038     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10039         isBoolSGPR(LHS.getOperand(0))) {
10040       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10041       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10042       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10043       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10044       if ((CRHS->isAllOnesValue() &&
10045            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10046           (CRHS->isNullValue() &&
10047            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10048         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10049                            DAG.getConstant(-1, SL, MVT::i1));
10050       if ((CRHS->isAllOnesValue() &&
10051            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10052           (CRHS->isNullValue() &&
10053            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10054         return LHS.getOperand(0);
10055     }
10056 
10057     uint64_t CRHSVal = CRHS->getZExtValue();
10058     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10059         LHS.getOpcode() == ISD::SELECT &&
10060         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10061         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10062         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10063         isBoolSGPR(LHS.getOperand(0))) {
10064       // Given CT != FT:
10065       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10066       // setcc (select cc, CT, CF), CF, ne => cc
10067       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10068       // setcc (select cc, CT, CF), CT, eq => cc
10069       uint64_t CT = LHS.getConstantOperandVal(1);
10070       uint64_t CF = LHS.getConstantOperandVal(2);
10071 
10072       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10073           (CT == CRHSVal && CC == ISD::SETNE))
10074         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10075                            DAG.getConstant(-1, SL, MVT::i1));
10076       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10077           (CT == CRHSVal && CC == ISD::SETEQ))
10078         return LHS.getOperand(0);
10079     }
10080   }
10081 
10082   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10083                                            VT != MVT::f16))
10084     return SDValue();
10085 
10086   // Match isinf/isfinite pattern
10087   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10088   // (fcmp one (fabs x), inf) -> (fp_class x,
10089   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10090   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10091     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10092     if (!CRHS)
10093       return SDValue();
10094 
10095     const APFloat &APF = CRHS->getValueAPF();
10096     if (APF.isInfinity() && !APF.isNegative()) {
10097       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10098                                  SIInstrFlags::N_INFINITY;
10099       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10100                                     SIInstrFlags::P_ZERO |
10101                                     SIInstrFlags::N_NORMAL |
10102                                     SIInstrFlags::P_NORMAL |
10103                                     SIInstrFlags::N_SUBNORMAL |
10104                                     SIInstrFlags::P_SUBNORMAL;
10105       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10106       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10107                          DAG.getConstant(Mask, SL, MVT::i32));
10108     }
10109   }
10110 
10111   return SDValue();
10112 }
10113 
10114 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10115                                                      DAGCombinerInfo &DCI) const {
10116   SelectionDAG &DAG = DCI.DAG;
10117   SDLoc SL(N);
10118   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10119 
10120   SDValue Src = N->getOperand(0);
10121   SDValue Shift = N->getOperand(0);
10122 
10123   // TODO: Extend type shouldn't matter (assuming legal types).
10124   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10125     Shift = Shift.getOperand(0);
10126 
10127   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10128     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10129     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10130     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10131     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10132     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10133     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10134       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10135                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10136 
10137       unsigned ShiftOffset = 8 * Offset;
10138       if (Shift.getOpcode() == ISD::SHL)
10139         ShiftOffset -= C->getZExtValue();
10140       else
10141         ShiftOffset += C->getZExtValue();
10142 
10143       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10144         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10145                            MVT::f32, Shift);
10146       }
10147     }
10148   }
10149 
10150   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10151   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10152   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10153     // We simplified Src. If this node is not dead, visit it again so it is
10154     // folded properly.
10155     if (N->getOpcode() != ISD::DELETED_NODE)
10156       DCI.AddToWorklist(N);
10157     return SDValue(N, 0);
10158   }
10159 
10160   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10161   if (SDValue DemandedSrc =
10162           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10163     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10164 
10165   return SDValue();
10166 }
10167 
10168 SDValue SITargetLowering::performClampCombine(SDNode *N,
10169                                               DAGCombinerInfo &DCI) const {
10170   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10171   if (!CSrc)
10172     return SDValue();
10173 
10174   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10175   const APFloat &F = CSrc->getValueAPF();
10176   APFloat Zero = APFloat::getZero(F.getSemantics());
10177   if (F < Zero ||
10178       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10179     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10180   }
10181 
10182   APFloat One(F.getSemantics(), "1.0");
10183   if (F > One)
10184     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10185 
10186   return SDValue(CSrc, 0);
10187 }
10188 
10189 
10190 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10191                                             DAGCombinerInfo &DCI) const {
10192   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10193     return SDValue();
10194   switch (N->getOpcode()) {
10195   default:
10196     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10197   case ISD::ADD:
10198     return performAddCombine(N, DCI);
10199   case ISD::SUB:
10200     return performSubCombine(N, DCI);
10201   case ISD::ADDCARRY:
10202   case ISD::SUBCARRY:
10203     return performAddCarrySubCarryCombine(N, DCI);
10204   case ISD::FADD:
10205     return performFAddCombine(N, DCI);
10206   case ISD::FSUB:
10207     return performFSubCombine(N, DCI);
10208   case ISD::SETCC:
10209     return performSetCCCombine(N, DCI);
10210   case ISD::FMAXNUM:
10211   case ISD::FMINNUM:
10212   case ISD::FMAXNUM_IEEE:
10213   case ISD::FMINNUM_IEEE:
10214   case ISD::SMAX:
10215   case ISD::SMIN:
10216   case ISD::UMAX:
10217   case ISD::UMIN:
10218   case AMDGPUISD::FMIN_LEGACY:
10219   case AMDGPUISD::FMAX_LEGACY:
10220     return performMinMaxCombine(N, DCI);
10221   case ISD::FMA:
10222     return performFMACombine(N, DCI);
10223   case ISD::LOAD: {
10224     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10225       return Widended;
10226     LLVM_FALLTHROUGH;
10227   }
10228   case ISD::STORE:
10229   case ISD::ATOMIC_LOAD:
10230   case ISD::ATOMIC_STORE:
10231   case ISD::ATOMIC_CMP_SWAP:
10232   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10233   case ISD::ATOMIC_SWAP:
10234   case ISD::ATOMIC_LOAD_ADD:
10235   case ISD::ATOMIC_LOAD_SUB:
10236   case ISD::ATOMIC_LOAD_AND:
10237   case ISD::ATOMIC_LOAD_OR:
10238   case ISD::ATOMIC_LOAD_XOR:
10239   case ISD::ATOMIC_LOAD_NAND:
10240   case ISD::ATOMIC_LOAD_MIN:
10241   case ISD::ATOMIC_LOAD_MAX:
10242   case ISD::ATOMIC_LOAD_UMIN:
10243   case ISD::ATOMIC_LOAD_UMAX:
10244   case ISD::ATOMIC_LOAD_FADD:
10245   case AMDGPUISD::ATOMIC_INC:
10246   case AMDGPUISD::ATOMIC_DEC:
10247   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10248   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10249     if (DCI.isBeforeLegalize())
10250       break;
10251     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10252   case ISD::AND:
10253     return performAndCombine(N, DCI);
10254   case ISD::OR:
10255     return performOrCombine(N, DCI);
10256   case ISD::XOR:
10257     return performXorCombine(N, DCI);
10258   case ISD::ZERO_EXTEND:
10259     return performZeroExtendCombine(N, DCI);
10260   case ISD::SIGN_EXTEND_INREG:
10261     return performSignExtendInRegCombine(N , DCI);
10262   case AMDGPUISD::FP_CLASS:
10263     return performClassCombine(N, DCI);
10264   case ISD::FCANONICALIZE:
10265     return performFCanonicalizeCombine(N, DCI);
10266   case AMDGPUISD::RCP:
10267     return performRcpCombine(N, DCI);
10268   case AMDGPUISD::FRACT:
10269   case AMDGPUISD::RSQ:
10270   case AMDGPUISD::RCP_LEGACY:
10271   case AMDGPUISD::RCP_IFLAG:
10272   case AMDGPUISD::RSQ_CLAMP:
10273   case AMDGPUISD::LDEXP: {
10274     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10275     SDValue Src = N->getOperand(0);
10276     if (Src.isUndef())
10277       return Src;
10278     break;
10279   }
10280   case ISD::SINT_TO_FP:
10281   case ISD::UINT_TO_FP:
10282     return performUCharToFloatCombine(N, DCI);
10283   case AMDGPUISD::CVT_F32_UBYTE0:
10284   case AMDGPUISD::CVT_F32_UBYTE1:
10285   case AMDGPUISD::CVT_F32_UBYTE2:
10286   case AMDGPUISD::CVT_F32_UBYTE3:
10287     return performCvtF32UByteNCombine(N, DCI);
10288   case AMDGPUISD::FMED3:
10289     return performFMed3Combine(N, DCI);
10290   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10291     return performCvtPkRTZCombine(N, DCI);
10292   case AMDGPUISD::CLAMP:
10293     return performClampCombine(N, DCI);
10294   case ISD::SCALAR_TO_VECTOR: {
10295     SelectionDAG &DAG = DCI.DAG;
10296     EVT VT = N->getValueType(0);
10297 
10298     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10299     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10300       SDLoc SL(N);
10301       SDValue Src = N->getOperand(0);
10302       EVT EltVT = Src.getValueType();
10303       if (EltVT == MVT::f16)
10304         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10305 
10306       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10307       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10308     }
10309 
10310     break;
10311   }
10312   case ISD::EXTRACT_VECTOR_ELT:
10313     return performExtractVectorEltCombine(N, DCI);
10314   case ISD::INSERT_VECTOR_ELT:
10315     return performInsertVectorEltCombine(N, DCI);
10316   }
10317   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10318 }
10319 
10320 /// Helper function for adjustWritemask
10321 static unsigned SubIdx2Lane(unsigned Idx) {
10322   switch (Idx) {
10323   default: return 0;
10324   case AMDGPU::sub0: return 0;
10325   case AMDGPU::sub1: return 1;
10326   case AMDGPU::sub2: return 2;
10327   case AMDGPU::sub3: return 3;
10328   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10329   }
10330 }
10331 
10332 /// Adjust the writemask of MIMG instructions
10333 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10334                                           SelectionDAG &DAG) const {
10335   unsigned Opcode = Node->getMachineOpcode();
10336 
10337   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10338   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10339   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10340     return Node; // not implemented for D16
10341 
10342   SDNode *Users[5] = { nullptr };
10343   unsigned Lane = 0;
10344   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10345   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10346   unsigned NewDmask = 0;
10347   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10348   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10349   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10350                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10351   unsigned TFCLane = 0;
10352   bool HasChain = Node->getNumValues() > 1;
10353 
10354   if (OldDmask == 0) {
10355     // These are folded out, but on the chance it happens don't assert.
10356     return Node;
10357   }
10358 
10359   unsigned OldBitsSet = countPopulation(OldDmask);
10360   // Work out which is the TFE/LWE lane if that is enabled.
10361   if (UsesTFC) {
10362     TFCLane = OldBitsSet;
10363   }
10364 
10365   // Try to figure out the used register components
10366   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10367        I != E; ++I) {
10368 
10369     // Don't look at users of the chain.
10370     if (I.getUse().getResNo() != 0)
10371       continue;
10372 
10373     // Abort if we can't understand the usage
10374     if (!I->isMachineOpcode() ||
10375         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10376       return Node;
10377 
10378     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10379     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10380     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10381     // set, etc.
10382     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10383 
10384     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10385     if (UsesTFC && Lane == TFCLane) {
10386       Users[Lane] = *I;
10387     } else {
10388       // Set which texture component corresponds to the lane.
10389       unsigned Comp;
10390       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10391         Comp = countTrailingZeros(Dmask);
10392         Dmask &= ~(1 << Comp);
10393       }
10394 
10395       // Abort if we have more than one user per component.
10396       if (Users[Lane])
10397         return Node;
10398 
10399       Users[Lane] = *I;
10400       NewDmask |= 1 << Comp;
10401     }
10402   }
10403 
10404   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10405   bool NoChannels = !NewDmask;
10406   if (NoChannels) {
10407     if (!UsesTFC) {
10408       // No uses of the result and not using TFC. Then do nothing.
10409       return Node;
10410     }
10411     // If the original dmask has one channel - then nothing to do
10412     if (OldBitsSet == 1)
10413       return Node;
10414     // Use an arbitrary dmask - required for the instruction to work
10415     NewDmask = 1;
10416   }
10417   // Abort if there's no change
10418   if (NewDmask == OldDmask)
10419     return Node;
10420 
10421   unsigned BitsSet = countPopulation(NewDmask);
10422 
10423   // Check for TFE or LWE - increase the number of channels by one to account
10424   // for the extra return value
10425   // This will need adjustment for D16 if this is also included in
10426   // adjustWriteMask (this function) but at present D16 are excluded.
10427   unsigned NewChannels = BitsSet + UsesTFC;
10428 
10429   int NewOpcode =
10430       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10431   assert(NewOpcode != -1 &&
10432          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10433          "failed to find equivalent MIMG op");
10434 
10435   // Adjust the writemask in the node
10436   SmallVector<SDValue, 12> Ops;
10437   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10438   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10439   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10440 
10441   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10442 
10443   MVT ResultVT = NewChannels == 1 ?
10444     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10445                            NewChannels == 5 ? 8 : NewChannels);
10446   SDVTList NewVTList = HasChain ?
10447     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10448 
10449 
10450   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10451                                               NewVTList, Ops);
10452 
10453   if (HasChain) {
10454     // Update chain.
10455     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10456     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10457   }
10458 
10459   if (NewChannels == 1) {
10460     assert(Node->hasNUsesOfValue(1, 0));
10461     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10462                                       SDLoc(Node), Users[Lane]->getValueType(0),
10463                                       SDValue(NewNode, 0));
10464     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10465     return nullptr;
10466   }
10467 
10468   // Update the users of the node with the new indices
10469   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10470     SDNode *User = Users[i];
10471     if (!User) {
10472       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10473       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10474       if (i || !NoChannels)
10475         continue;
10476     } else {
10477       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10478       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10479     }
10480 
10481     switch (Idx) {
10482     default: break;
10483     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10484     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10485     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10486     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10487     }
10488   }
10489 
10490   DAG.RemoveDeadNode(Node);
10491   return nullptr;
10492 }
10493 
10494 static bool isFrameIndexOp(SDValue Op) {
10495   if (Op.getOpcode() == ISD::AssertZext)
10496     Op = Op.getOperand(0);
10497 
10498   return isa<FrameIndexSDNode>(Op);
10499 }
10500 
10501 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10502 /// with frame index operands.
10503 /// LLVM assumes that inputs are to these instructions are registers.
10504 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10505                                                         SelectionDAG &DAG) const {
10506   if (Node->getOpcode() == ISD::CopyToReg) {
10507     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10508     SDValue SrcVal = Node->getOperand(2);
10509 
10510     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10511     // to try understanding copies to physical registers.
10512     if (SrcVal.getValueType() == MVT::i1 &&
10513         Register::isPhysicalRegister(DestReg->getReg())) {
10514       SDLoc SL(Node);
10515       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10516       SDValue VReg = DAG.getRegister(
10517         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10518 
10519       SDNode *Glued = Node->getGluedNode();
10520       SDValue ToVReg
10521         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10522                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10523       SDValue ToResultReg
10524         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10525                            VReg, ToVReg.getValue(1));
10526       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10527       DAG.RemoveDeadNode(Node);
10528       return ToResultReg.getNode();
10529     }
10530   }
10531 
10532   SmallVector<SDValue, 8> Ops;
10533   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10534     if (!isFrameIndexOp(Node->getOperand(i))) {
10535       Ops.push_back(Node->getOperand(i));
10536       continue;
10537     }
10538 
10539     SDLoc DL(Node);
10540     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10541                                      Node->getOperand(i).getValueType(),
10542                                      Node->getOperand(i)), 0));
10543   }
10544 
10545   return DAG.UpdateNodeOperands(Node, Ops);
10546 }
10547 
10548 /// Fold the instructions after selecting them.
10549 /// Returns null if users were already updated.
10550 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10551                                           SelectionDAG &DAG) const {
10552   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10553   unsigned Opcode = Node->getMachineOpcode();
10554 
10555   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10556       !TII->isGather4(Opcode)) {
10557     return adjustWritemask(Node, DAG);
10558   }
10559 
10560   if (Opcode == AMDGPU::INSERT_SUBREG ||
10561       Opcode == AMDGPU::REG_SEQUENCE) {
10562     legalizeTargetIndependentNode(Node, DAG);
10563     return Node;
10564   }
10565 
10566   switch (Opcode) {
10567   case AMDGPU::V_DIV_SCALE_F32:
10568   case AMDGPU::V_DIV_SCALE_F64: {
10569     // Satisfy the operand register constraint when one of the inputs is
10570     // undefined. Ordinarily each undef value will have its own implicit_def of
10571     // a vreg, so force these to use a single register.
10572     SDValue Src0 = Node->getOperand(0);
10573     SDValue Src1 = Node->getOperand(1);
10574     SDValue Src2 = Node->getOperand(2);
10575 
10576     if ((Src0.isMachineOpcode() &&
10577          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10578         (Src0 == Src1 || Src0 == Src2))
10579       break;
10580 
10581     MVT VT = Src0.getValueType().getSimpleVT();
10582     const TargetRegisterClass *RC =
10583         getRegClassFor(VT, Src0.getNode()->isDivergent());
10584 
10585     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10586     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10587 
10588     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10589                                       UndefReg, Src0, SDValue());
10590 
10591     // src0 must be the same register as src1 or src2, even if the value is
10592     // undefined, so make sure we don't violate this constraint.
10593     if (Src0.isMachineOpcode() &&
10594         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10595       if (Src1.isMachineOpcode() &&
10596           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10597         Src0 = Src1;
10598       else if (Src2.isMachineOpcode() &&
10599                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10600         Src0 = Src2;
10601       else {
10602         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10603         Src0 = UndefReg;
10604         Src1 = UndefReg;
10605       }
10606     } else
10607       break;
10608 
10609     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10610     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10611       Ops.push_back(Node->getOperand(I));
10612 
10613     Ops.push_back(ImpDef.getValue(1));
10614     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10615   }
10616   default:
10617     break;
10618   }
10619 
10620   return Node;
10621 }
10622 
10623 /// Assign the register class depending on the number of
10624 /// bits set in the writemask
10625 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10626                                                      SDNode *Node) const {
10627   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10628 
10629   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10630 
10631   if (TII->isVOP3(MI.getOpcode())) {
10632     // Make sure constant bus requirements are respected.
10633     TII->legalizeOperandsVOP3(MRI, MI);
10634 
10635     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10636     // This saves a chain-copy of registers and better ballance register
10637     // use between vgpr and agpr as agpr tuples tend to be big.
10638     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10639       unsigned Opc = MI.getOpcode();
10640       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10641       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10642                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10643         if (I == -1)
10644           break;
10645         MachineOperand &Op = MI.getOperand(I);
10646         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10647              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10648             !Register::isVirtualRegister(Op.getReg()) ||
10649             !TRI->isAGPR(MRI, Op.getReg()))
10650           continue;
10651         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10652         if (!Src || !Src->isCopy() ||
10653             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10654           continue;
10655         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10656         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10657         // All uses of agpr64 and agpr32 can also accept vgpr except for
10658         // v_accvgpr_read, but we do not produce agpr reads during selection,
10659         // so no use checks are needed.
10660         MRI.setRegClass(Op.getReg(), NewRC);
10661       }
10662     }
10663 
10664     return;
10665   }
10666 
10667   // Replace unused atomics with the no return version.
10668   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10669   if (NoRetAtomicOp != -1) {
10670     if (!Node->hasAnyUseOfValue(0)) {
10671       MI.setDesc(TII->get(NoRetAtomicOp));
10672       MI.RemoveOperand(0);
10673       return;
10674     }
10675 
10676     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10677     // instruction, because the return type of these instructions is a vec2 of
10678     // the memory type, so it can be tied to the input operand.
10679     // This means these instructions always have a use, so we need to add a
10680     // special case to check if the atomic has only one extract_subreg use,
10681     // which itself has no uses.
10682     if ((Node->hasNUsesOfValue(1, 0) &&
10683          Node->use_begin()->isMachineOpcode() &&
10684          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10685          !Node->use_begin()->hasAnyUseOfValue(0))) {
10686       Register Def = MI.getOperand(0).getReg();
10687 
10688       // Change this into a noret atomic.
10689       MI.setDesc(TII->get(NoRetAtomicOp));
10690       MI.RemoveOperand(0);
10691 
10692       // If we only remove the def operand from the atomic instruction, the
10693       // extract_subreg will be left with a use of a vreg without a def.
10694       // So we need to insert an implicit_def to avoid machine verifier
10695       // errors.
10696       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10697               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10698     }
10699     return;
10700   }
10701 }
10702 
10703 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10704                               uint64_t Val) {
10705   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10706   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10707 }
10708 
10709 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10710                                                 const SDLoc &DL,
10711                                                 SDValue Ptr) const {
10712   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10713 
10714   // Build the half of the subregister with the constants before building the
10715   // full 128-bit register. If we are building multiple resource descriptors,
10716   // this will allow CSEing of the 2-component register.
10717   const SDValue Ops0[] = {
10718     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10719     buildSMovImm32(DAG, DL, 0),
10720     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10721     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10722     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10723   };
10724 
10725   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10726                                                 MVT::v2i32, Ops0), 0);
10727 
10728   // Combine the constants and the pointer.
10729   const SDValue Ops1[] = {
10730     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10731     Ptr,
10732     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10733     SubRegHi,
10734     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10735   };
10736 
10737   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10738 }
10739 
10740 /// Return a resource descriptor with the 'Add TID' bit enabled
10741 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10742 ///        of the resource descriptor) to create an offset, which is added to
10743 ///        the resource pointer.
10744 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10745                                            SDValue Ptr, uint32_t RsrcDword1,
10746                                            uint64_t RsrcDword2And3) const {
10747   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10748   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10749   if (RsrcDword1) {
10750     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10751                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10752                     0);
10753   }
10754 
10755   SDValue DataLo = buildSMovImm32(DAG, DL,
10756                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10757   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10758 
10759   const SDValue Ops[] = {
10760     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10761     PtrLo,
10762     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10763     PtrHi,
10764     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10765     DataLo,
10766     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10767     DataHi,
10768     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10769   };
10770 
10771   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10772 }
10773 
10774 //===----------------------------------------------------------------------===//
10775 //                         SI Inline Assembly Support
10776 //===----------------------------------------------------------------------===//
10777 
10778 std::pair<unsigned, const TargetRegisterClass *>
10779 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10780                                                StringRef Constraint,
10781                                                MVT VT) const {
10782   const TargetRegisterClass *RC = nullptr;
10783   if (Constraint.size() == 1) {
10784     const unsigned BitWidth = VT.getSizeInBits();
10785     switch (Constraint[0]) {
10786     default:
10787       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10788     case 's':
10789     case 'r':
10790       switch (BitWidth) {
10791       case 16:
10792         RC = &AMDGPU::SReg_32RegClass;
10793         break;
10794       case 64:
10795         RC = &AMDGPU::SGPR_64RegClass;
10796         break;
10797       default:
10798         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
10799         if (!RC)
10800           return std::make_pair(0U, nullptr);
10801         break;
10802       }
10803       break;
10804     case 'v':
10805       switch (BitWidth) {
10806       case 16:
10807         RC = &AMDGPU::VGPR_32RegClass;
10808         break;
10809       default:
10810         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
10811         if (!RC)
10812           return std::make_pair(0U, nullptr);
10813         break;
10814       }
10815       break;
10816     case 'a':
10817       if (!Subtarget->hasMAIInsts())
10818         break;
10819       switch (BitWidth) {
10820       case 16:
10821         RC = &AMDGPU::AGPR_32RegClass;
10822         break;
10823       default:
10824         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
10825         if (!RC)
10826           return std::make_pair(0U, nullptr);
10827         break;
10828       }
10829       break;
10830     }
10831     // We actually support i128, i16 and f16 as inline parameters
10832     // even if they are not reported as legal
10833     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10834                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10835       return std::make_pair(0U, RC);
10836   }
10837 
10838   if (Constraint.size() > 1) {
10839     if (Constraint[1] == 'v') {
10840       RC = &AMDGPU::VGPR_32RegClass;
10841     } else if (Constraint[1] == 's') {
10842       RC = &AMDGPU::SGPR_32RegClass;
10843     } else if (Constraint[1] == 'a') {
10844       RC = &AMDGPU::AGPR_32RegClass;
10845     }
10846 
10847     if (RC) {
10848       uint32_t Idx;
10849       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10850       if (!Failed && Idx < RC->getNumRegs())
10851         return std::make_pair(RC->getRegister(Idx), RC);
10852     }
10853   }
10854 
10855   // FIXME: Returns VS_32 for physical SGPR constraints
10856   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10857 }
10858 
10859 SITargetLowering::ConstraintType
10860 SITargetLowering::getConstraintType(StringRef Constraint) const {
10861   if (Constraint.size() == 1) {
10862     switch (Constraint[0]) {
10863     default: break;
10864     case 's':
10865     case 'v':
10866     case 'a':
10867       return C_RegisterClass;
10868     }
10869   }
10870   return TargetLowering::getConstraintType(Constraint);
10871 }
10872 
10873 // Figure out which registers should be reserved for stack access. Only after
10874 // the function is legalized do we know all of the non-spill stack objects or if
10875 // calls are present.
10876 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10877   MachineRegisterInfo &MRI = MF.getRegInfo();
10878   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10879   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10880   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10881 
10882   if (Info->isEntryFunction()) {
10883     // Callable functions have fixed registers used for stack access.
10884     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10885   }
10886 
10887   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10888                              Info->getStackPtrOffsetReg()));
10889   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10890     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10891 
10892   // We need to worry about replacing the default register with itself in case
10893   // of MIR testcases missing the MFI.
10894   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10895     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10896 
10897   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10898     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10899 
10900   Info->limitOccupancy(MF);
10901 
10902   if (ST.isWave32() && !MF.empty()) {
10903     // Add VCC_HI def because many instructions marked as imp-use VCC where
10904     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10905     // having a use of undef.
10906 
10907     const SIInstrInfo *TII = ST.getInstrInfo();
10908     DebugLoc DL;
10909 
10910     MachineBasicBlock &MBB = MF.front();
10911     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10912     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10913 
10914     for (auto &MBB : MF) {
10915       for (auto &MI : MBB) {
10916         TII->fixImplicitOperands(MI);
10917       }
10918     }
10919   }
10920 
10921   TargetLoweringBase::finalizeLowering(MF);
10922 
10923   // Allocate a VGPR for future SGPR Spill if
10924   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
10925   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
10926   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
10927       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
10928     Info->reserveVGPRforSGPRSpills(MF);
10929 }
10930 
10931 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10932                                                      KnownBits &Known,
10933                                                      const APInt &DemandedElts,
10934                                                      const SelectionDAG &DAG,
10935                                                      unsigned Depth) const {
10936   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10937                                                 DAG, Depth);
10938 
10939   // Set the high bits to zero based on the maximum allowed scratch size per
10940   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10941   // calculation won't overflow, so assume the sign bit is never set.
10942   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10943 }
10944 
10945 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10946   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10947   const Align CacheLineAlign = Align(64);
10948 
10949   // Pre-GFX10 target did not benefit from loop alignment
10950   if (!ML || DisableLoopAlignment ||
10951       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10952       getSubtarget()->hasInstFwdPrefetchBug())
10953     return PrefAlign;
10954 
10955   // On GFX10 I$ is 4 x 64 bytes cache lines.
10956   // By default prefetcher keeps one cache line behind and reads two ahead.
10957   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10958   // behind and one ahead.
10959   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10960   // If loop fits 64 bytes it always spans no more than two cache lines and
10961   // does not need an alignment.
10962   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10963   // Else if loop is less or equal 192 bytes we need two lines behind.
10964 
10965   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10966   const MachineBasicBlock *Header = ML->getHeader();
10967   if (Header->getAlignment() != PrefAlign)
10968     return Header->getAlignment(); // Already processed.
10969 
10970   unsigned LoopSize = 0;
10971   for (const MachineBasicBlock *MBB : ML->blocks()) {
10972     // If inner loop block is aligned assume in average half of the alignment
10973     // size to be added as nops.
10974     if (MBB != Header)
10975       LoopSize += MBB->getAlignment().value() / 2;
10976 
10977     for (const MachineInstr &MI : *MBB) {
10978       LoopSize += TII->getInstSizeInBytes(MI);
10979       if (LoopSize > 192)
10980         return PrefAlign;
10981     }
10982   }
10983 
10984   if (LoopSize <= 64)
10985     return PrefAlign;
10986 
10987   if (LoopSize <= 128)
10988     return CacheLineAlign;
10989 
10990   // If any of parent loops is surrounded by prefetch instructions do not
10991   // insert new for inner loop, which would reset parent's settings.
10992   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10993     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10994       auto I = Exit->getFirstNonDebugInstr();
10995       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10996         return CacheLineAlign;
10997     }
10998   }
10999 
11000   MachineBasicBlock *Pre = ML->getLoopPreheader();
11001   MachineBasicBlock *Exit = ML->getExitBlock();
11002 
11003   if (Pre && Exit) {
11004     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11005             TII->get(AMDGPU::S_INST_PREFETCH))
11006       .addImm(1); // prefetch 2 lines behind PC
11007 
11008     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11009             TII->get(AMDGPU::S_INST_PREFETCH))
11010       .addImm(2); // prefetch 1 line behind PC
11011   }
11012 
11013   return CacheLineAlign;
11014 }
11015 
11016 LLVM_ATTRIBUTE_UNUSED
11017 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11018   assert(N->getOpcode() == ISD::CopyFromReg);
11019   do {
11020     // Follow the chain until we find an INLINEASM node.
11021     N = N->getOperand(0).getNode();
11022     if (N->getOpcode() == ISD::INLINEASM ||
11023         N->getOpcode() == ISD::INLINEASM_BR)
11024       return true;
11025   } while (N->getOpcode() == ISD::CopyFromReg);
11026   return false;
11027 }
11028 
11029 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11030   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11031 {
11032   switch (N->getOpcode()) {
11033     case ISD::CopyFromReg:
11034     {
11035       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11036       const MachineFunction * MF = FLI->MF;
11037       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
11038       const MachineRegisterInfo &MRI = MF->getRegInfo();
11039       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
11040       Register Reg = R->getReg();
11041       if (Reg.isPhysical())
11042         return !TRI.isSGPRReg(MRI, Reg);
11043 
11044       if (MRI.isLiveIn(Reg)) {
11045         // workitem.id.x workitem.id.y workitem.id.z
11046         // Any VGPR formal argument is also considered divergent
11047         if (!TRI.isSGPRReg(MRI, Reg))
11048           return true;
11049         // Formal arguments of non-entry functions
11050         // are conservatively considered divergent
11051         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
11052           return true;
11053         return false;
11054       }
11055       const Value *V = FLI->getValueFromVirtualReg(Reg);
11056       if (V)
11057         return KDA->isDivergent(V);
11058       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11059       return !TRI.isSGPRReg(MRI, Reg);
11060     }
11061     break;
11062     case ISD::LOAD: {
11063       const LoadSDNode *L = cast<LoadSDNode>(N);
11064       unsigned AS = L->getAddressSpace();
11065       // A flat load may access private memory.
11066       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11067     } break;
11068     case ISD::CALLSEQ_END:
11069     return true;
11070     break;
11071     case ISD::INTRINSIC_WO_CHAIN:
11072     {
11073 
11074     }
11075       return AMDGPU::isIntrinsicSourceOfDivergence(
11076       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11077     case ISD::INTRINSIC_W_CHAIN:
11078       return AMDGPU::isIntrinsicSourceOfDivergence(
11079       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11080   }
11081   return false;
11082 }
11083 
11084 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11085                                                EVT VT) const {
11086   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11087   case MVT::f32:
11088     return hasFP32Denormals(DAG.getMachineFunction());
11089   case MVT::f64:
11090   case MVT::f16:
11091     return hasFP64FP16Denormals(DAG.getMachineFunction());
11092   default:
11093     return false;
11094   }
11095 }
11096 
11097 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11098                                                     const SelectionDAG &DAG,
11099                                                     bool SNaN,
11100                                                     unsigned Depth) const {
11101   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11102     const MachineFunction &MF = DAG.getMachineFunction();
11103     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11104 
11105     if (Info->getMode().DX10Clamp)
11106       return true; // Clamped to 0.
11107     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11108   }
11109 
11110   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11111                                                             SNaN, Depth);
11112 }
11113 
11114 TargetLowering::AtomicExpansionKind
11115 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11116   switch (RMW->getOperation()) {
11117   case AtomicRMWInst::FAdd: {
11118     Type *Ty = RMW->getType();
11119 
11120     // We don't have a way to support 16-bit atomics now, so just leave them
11121     // as-is.
11122     if (Ty->isHalfTy())
11123       return AtomicExpansionKind::None;
11124 
11125     if (!Ty->isFloatTy())
11126       return AtomicExpansionKind::CmpXChg;
11127 
11128     // TODO: Do have these for flat. Older targets also had them for buffers.
11129     unsigned AS = RMW->getPointerAddressSpace();
11130 
11131     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11132       return RMW->use_empty() ? AtomicExpansionKind::None :
11133                                 AtomicExpansionKind::CmpXChg;
11134     }
11135 
11136     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11137       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11138   }
11139   default:
11140     break;
11141   }
11142 
11143   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11144 }
11145 
11146 const TargetRegisterClass *
11147 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11148   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11149   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11150   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11151     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11152                                                : &AMDGPU::SReg_32RegClass;
11153   if (!TRI->isSGPRClass(RC) && !isDivergent)
11154     return TRI->getEquivalentSGPRClass(RC);
11155   else if (TRI->isSGPRClass(RC) && isDivergent)
11156     return TRI->getEquivalentVGPRClass(RC);
11157 
11158   return RC;
11159 }
11160 
11161 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11162 // uniform values (as produced by the mask results of control flow intrinsics)
11163 // used outside of divergent blocks. The phi users need to also be treated as
11164 // always uniform.
11165 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11166                       unsigned WaveSize) {
11167   // FIXME: We asssume we never cast the mask results of a control flow
11168   // intrinsic.
11169   // Early exit if the type won't be consistent as a compile time hack.
11170   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11171   if (!IT || IT->getBitWidth() != WaveSize)
11172     return false;
11173 
11174   if (!isa<Instruction>(V))
11175     return false;
11176   if (!Visited.insert(V).second)
11177     return false;
11178   bool Result = false;
11179   for (auto U : V->users()) {
11180     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11181       if (V == U->getOperand(1)) {
11182         switch (Intrinsic->getIntrinsicID()) {
11183         default:
11184           Result = false;
11185           break;
11186         case Intrinsic::amdgcn_if_break:
11187         case Intrinsic::amdgcn_if:
11188         case Intrinsic::amdgcn_else:
11189           Result = true;
11190           break;
11191         }
11192       }
11193       if (V == U->getOperand(0)) {
11194         switch (Intrinsic->getIntrinsicID()) {
11195         default:
11196           Result = false;
11197           break;
11198         case Intrinsic::amdgcn_end_cf:
11199         case Intrinsic::amdgcn_loop:
11200           Result = true;
11201           break;
11202         }
11203       }
11204     } else {
11205       Result = hasCFUser(U, Visited, WaveSize);
11206     }
11207     if (Result)
11208       break;
11209   }
11210   return Result;
11211 }
11212 
11213 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11214                                                const Value *V) const {
11215   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11216     if (CI->isInlineAsm()) {
11217       // FIXME: This cannot give a correct answer. This should only trigger in
11218       // the case where inline asm returns mixed SGPR and VGPR results, used
11219       // outside the defining block. We don't have a specific result to
11220       // consider, so this assumes if any value is SGPR, the overall register
11221       // also needs to be SGPR.
11222       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11223       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11224           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11225       for (auto &TC : TargetConstraints) {
11226         if (TC.Type == InlineAsm::isOutput) {
11227           ComputeConstraintToUse(TC, SDValue());
11228           unsigned AssignedReg;
11229           const TargetRegisterClass *RC;
11230           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11231               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11232           if (RC) {
11233             MachineRegisterInfo &MRI = MF.getRegInfo();
11234             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11235               return true;
11236             else if (SIRI->isSGPRClass(RC))
11237               return true;
11238           }
11239         }
11240       }
11241     }
11242   }
11243   SmallPtrSet<const Value *, 16> Visited;
11244   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11245 }
11246