1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "Utils/AMDGPUBaseInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/DAGCombine.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineLoopInfo.h"
45 #include "llvm/CodeGen/MachineMemOperand.h"
46 #include "llvm/CodeGen/MachineModuleInfo.h"
47 #include "llvm/CodeGen/MachineOperand.h"
48 #include "llvm/CodeGen/MachineRegisterInfo.h"
49 #include "llvm/CodeGen/SelectionDAG.h"
50 #include "llvm/CodeGen/SelectionDAGNodes.h"
51 #include "llvm/CodeGen/TargetCallingConv.h"
52 #include "llvm/CodeGen/TargetRegisterInfo.h"
53 #include "llvm/CodeGen/ValueTypes.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/DiagnosticInfo.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/KnownBits.h"
72 #include "llvm/Support/MachineValueType.h"
73 #include "llvm/Support/MathExtras.h"
74 #include "llvm/Target/TargetOptions.h"
75 #include <cassert>
76 #include <cmath>
77 #include <cstdint>
78 #include <iterator>
79 #include <tuple>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 #define DEBUG_TYPE "si-lower"
86 
87 STATISTIC(NumTailCalls, "Number of tail calls");
88 
89 static cl::opt<bool> DisableLoopAlignment(
90   "amdgpu-disable-loop-alignment",
91   cl::desc("Do not align and prefetch loops"),
92   cl::init(false));
93 
94 static cl::opt<bool> VGPRReserveforSGPRSpill(
95     "amdgpu-reserve-vgpr-for-sgpr-spill",
96     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
97 
98 static cl::opt<bool> UseDivergentRegisterIndexing(
99   "amdgpu-use-divergent-register-indexing",
100   cl::Hidden,
101   cl::desc("Use indirect register addressing for divergent indexes"),
102   cl::init(false));
103 
104 static bool hasFP32Denormals(const MachineFunction &MF) {
105   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
106   return Info->getMode().allFP32Denormals();
107 }
108 
109 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
110   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
111   return Info->getMode().allFP64FP16Denormals();
112 }
113 
114 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
115   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
116   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
117     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
118       return AMDGPU::SGPR0 + Reg;
119     }
120   }
121   llvm_unreachable("Cannot allocate sgpr");
122 }
123 
124 SITargetLowering::SITargetLowering(const TargetMachine &TM,
125                                    const GCNSubtarget &STI)
126     : AMDGPUTargetLowering(TM, STI),
127       Subtarget(&STI) {
128   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
129   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
130 
131   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
132   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
133 
134   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
135   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
136   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
137 
138   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
139   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
140 
141   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
142   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
143 
144   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
145   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
146 
147   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
148   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
149 
150   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
151   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
152 
153   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
154   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
155 
156   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
157   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
158 
159   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
160   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
161 
162   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
163   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
164 
165   if (Subtarget->has16BitInsts()) {
166     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
167     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
168 
169     // Unless there are also VOP3P operations, not operations are really legal.
170     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
171     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
172     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
173     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
174   }
175 
176   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
177   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
178 
179   computeRegisterProperties(Subtarget->getRegisterInfo());
180 
181   // The boolean content concept here is too inflexible. Compares only ever
182   // really produce a 1-bit result. Any copy/extend from these will turn into a
183   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
184   // it's what most targets use.
185   setBooleanContents(ZeroOrOneBooleanContent);
186   setBooleanVectorContents(ZeroOrOneBooleanContent);
187 
188   // We need to custom lower vector stores from local memory
189   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
190   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::i1, Custom);
196   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
197 
198   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
199   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
204   setOperationAction(ISD::STORE, MVT::i1, Custom);
205   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
206 
207   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
208   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
209   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
210   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
211   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
212   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
213   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
214   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
215   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
216   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
217   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
218   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
219   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
220   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
221   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
222   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
223 
224   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
225   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
227   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
228   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
229 
230   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
231   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
232 
233   setOperationAction(ISD::SELECT, MVT::i1, Promote);
234   setOperationAction(ISD::SELECT, MVT::i64, Custom);
235   setOperationAction(ISD::SELECT, MVT::f64, Promote);
236   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
237 
238   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
239   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
242   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
243 
244   setOperationAction(ISD::SETCC, MVT::i1, Promote);
245   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
246   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
247   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
248 
249   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
250   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
251   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
252   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
253   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
254   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
255   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
256   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
257 
258   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
266 
267   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
268   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
269   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
270   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
271   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
272   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
273 
274   setOperationAction(ISD::UADDO, MVT::i32, Legal);
275   setOperationAction(ISD::USUBO, MVT::i32, Legal);
276 
277   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
278   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
279 
280   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
281   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
282   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
283 
284 #if 0
285   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
286   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
287 #endif
288 
289   // We only support LOAD/STORE and vector manipulation ops for vectors
290   // with > 4 elements.
291   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
292                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
293                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
294                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
295     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
296       switch (Op) {
297       case ISD::LOAD:
298       case ISD::STORE:
299       case ISD::BUILD_VECTOR:
300       case ISD::BITCAST:
301       case ISD::EXTRACT_VECTOR_ELT:
302       case ISD::INSERT_VECTOR_ELT:
303       case ISD::INSERT_SUBVECTOR:
304       case ISD::EXTRACT_SUBVECTOR:
305       case ISD::SCALAR_TO_VECTOR:
306         break;
307       case ISD::CONCAT_VECTORS:
308         setOperationAction(Op, VT, Custom);
309         break;
310       default:
311         setOperationAction(Op, VT, Expand);
312         break;
313       }
314     }
315   }
316 
317   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
318 
319   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
320   // is expanded to avoid having two separate loops in case the index is a VGPR.
321 
322   // Most operations are naturally 32-bit vector operations. We only support
323   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
324   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
325     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
326     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
327 
328     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
329     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
330 
331     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
332     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
333 
334     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
335     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
336   }
337 
338   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
339     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
340     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
341 
342     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
343     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
344 
345     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
346     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
347 
348     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
349     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
350   }
351 
352   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
353     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
354     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
355 
356     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
357     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
358 
359     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
360     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
361 
362     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
363     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
364   }
365 
366   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
367     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
368     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
369 
370     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
371     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
372 
373     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
374     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
375 
376     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
377     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
378   }
379 
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
383   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
384 
385   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
386   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
387 
388   // Avoid stack access for these.
389   // TODO: Generalize to more vector types.
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
394 
395   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
400 
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
403   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
404 
405   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
406   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
407   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
408   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
409 
410   // Deal with vec3 vector operations when widened to vec4.
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
415 
416   // Deal with vec5 vector operations when widened to vec8.
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
420   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
421 
422   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
423   // and output demarshalling
424   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
425   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
426 
427   // We can't return success/failure, only the old value,
428   // let LLVM add the comparison
429   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
430   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
431 
432   if (Subtarget->hasFlatAddressSpace()) {
433     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
434     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
435   }
436 
437   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
438 
439   // FIXME: This should be narrowed to i32, but that only happens if i64 is
440   // illegal.
441   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
442   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
443   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
444 
445   // On SI this is s_memtime and s_memrealtime on VI.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
447   setOperationAction(ISD::TRAP, MVT::Other, Custom);
448   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
449 
450   if (Subtarget->has16BitInsts()) {
451     setOperationAction(ISD::FPOW, MVT::f16, Promote);
452     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
453     setOperationAction(ISD::FLOG, MVT::f16, Custom);
454     setOperationAction(ISD::FEXP, MVT::f16, Custom);
455     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
456   }
457 
458   if (Subtarget->hasMadMacF32Insts())
459     setOperationAction(ISD::FMAD, MVT::f32, Legal);
460 
461   if (!Subtarget->hasBFI()) {
462     // fcopysign can be done in a single instruction with BFI.
463     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
464     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465   }
466 
467   if (!Subtarget->hasBCNT(32))
468     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
469 
470   if (!Subtarget->hasBCNT(64))
471     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
472 
473   if (Subtarget->hasFFBH())
474     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
475 
476   if (Subtarget->hasFFBL())
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
478 
479   // We only really have 32-bit BFE instructions (and 16-bit on VI).
480   //
481   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
482   // effort to match them now. We want this to be false for i64 cases when the
483   // extraction isn't restricted to the upper or lower half. Ideally we would
484   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
485   // span the midpoint are probably relatively rare, so don't worry about them
486   // for now.
487   if (Subtarget->hasBFE())
488     setHasExtractBitsInsn(true);
489 
490   // Clamp modifier on add/sub
491   if (Subtarget->hasIntClamp()) {
492     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
493     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
494   }
495 
496   if (Subtarget->hasAddNoCarry()) {
497     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
498     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
500     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
501   }
502 
503   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
504   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
506   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
507 
508 
509   // These are really only legal for ieee_mode functions. We should be avoiding
510   // them for functions that don't have ieee_mode enabled, so just say they are
511   // legal.
512   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
513   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
515   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
516 
517 
518   if (Subtarget->haveRoundOpsF64()) {
519     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
520     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
521     setOperationAction(ISD::FRINT, MVT::f64, Legal);
522   } else {
523     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
524     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
525     setOperationAction(ISD::FRINT, MVT::f64, Custom);
526     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
527   }
528 
529   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
530 
531   setOperationAction(ISD::FSIN, MVT::f32, Custom);
532   setOperationAction(ISD::FCOS, MVT::f32, Custom);
533   setOperationAction(ISD::FDIV, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f64, Custom);
535 
536   if (Subtarget->has16BitInsts()) {
537     setOperationAction(ISD::Constant, MVT::i16, Legal);
538 
539     setOperationAction(ISD::SMIN, MVT::i16, Legal);
540     setOperationAction(ISD::SMAX, MVT::i16, Legal);
541 
542     setOperationAction(ISD::UMIN, MVT::i16, Legal);
543     setOperationAction(ISD::UMAX, MVT::i16, Legal);
544 
545     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
546     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
547 
548     setOperationAction(ISD::ROTR, MVT::i16, Promote);
549     setOperationAction(ISD::ROTL, MVT::i16, Promote);
550 
551     setOperationAction(ISD::SDIV, MVT::i16, Promote);
552     setOperationAction(ISD::UDIV, MVT::i16, Promote);
553     setOperationAction(ISD::SREM, MVT::i16, Promote);
554     setOperationAction(ISD::UREM, MVT::i16, Promote);
555     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
556     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
557 
558     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
559 
560     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
562     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
564     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
565 
566     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
567 
568     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
569 
570     setOperationAction(ISD::LOAD, MVT::i16, Custom);
571 
572     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
573 
574     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
575     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
576     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
577     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
578 
579     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
580     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
581 
582     // F16 - Constant Actions.
583     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
584 
585     // F16 - Load/Store Actions.
586     setOperationAction(ISD::LOAD, MVT::f16, Promote);
587     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
588     setOperationAction(ISD::STORE, MVT::f16, Promote);
589     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
590 
591     // F16 - VOP1 Actions.
592     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
593     setOperationAction(ISD::FCOS, MVT::f16, Custom);
594     setOperationAction(ISD::FSIN, MVT::f16, Custom);
595 
596     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
597     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
598 
599     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
600     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
601     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
602     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::FROUND, MVT::f16, Custom);
604 
605     // F16 - VOP2 Actions.
606     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
607     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
608 
609     setOperationAction(ISD::FDIV, MVT::f16, Custom);
610 
611     // F16 - VOP3 Actions.
612     setOperationAction(ISD::FMA, MVT::f16, Legal);
613     if (STI.hasMadF16())
614       setOperationAction(ISD::FMAD, MVT::f16, Legal);
615 
616     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
617       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
618         switch (Op) {
619         case ISD::LOAD:
620         case ISD::STORE:
621         case ISD::BUILD_VECTOR:
622         case ISD::BITCAST:
623         case ISD::EXTRACT_VECTOR_ELT:
624         case ISD::INSERT_VECTOR_ELT:
625         case ISD::INSERT_SUBVECTOR:
626         case ISD::EXTRACT_SUBVECTOR:
627         case ISD::SCALAR_TO_VECTOR:
628           break;
629         case ISD::CONCAT_VECTORS:
630           setOperationAction(Op, VT, Custom);
631           break;
632         default:
633           setOperationAction(Op, VT, Expand);
634           break;
635         }
636       }
637     }
638 
639     // v_perm_b32 can handle either of these.
640     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
641     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
643 
644     // XXX - Do these do anything? Vector constants turn into build_vector.
645     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
646     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
647 
648     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
649     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
650 
651     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
652     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
653     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
655 
656     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
657     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
658     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
659     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
660 
661     setOperationAction(ISD::AND, MVT::v2i16, Promote);
662     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
663     setOperationAction(ISD::OR, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
665     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
667 
668     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
669     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
670     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
671     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
672 
673     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
674     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
675     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
676     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
677 
678     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
679     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
682 
683     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
684     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
686 
687     if (!Subtarget->hasVOP3PInsts()) {
688       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
690     }
691 
692     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
693     // This isn't really legal, but this avoids the legalizer unrolling it (and
694     // allows matching fneg (fabs x) patterns)
695     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
696 
697     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
698     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
700     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
701 
702     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
703     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
704 
705     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
706     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
707   }
708 
709   if (Subtarget->hasVOP3PInsts()) {
710     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
711     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
712     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
713     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
716     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
717     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
719     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
720 
721     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
722     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
725 
726     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
727     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
729 
730     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
731     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
732 
733     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
734 
735     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
737 
738     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
740 
741     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
742     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
744     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
745     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
746     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
747 
748     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
749     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
750     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
752 
753     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
754     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
757 
758     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
759     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
761 
762     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
763     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
764 
765     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
766     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
768 
769     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
770     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
772   }
773 
774   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
775   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
776 
777   if (Subtarget->has16BitInsts()) {
778     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
779     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
780     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
781     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
782   } else {
783     // Legalization hack.
784     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
785     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
786 
787     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
788     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
789   }
790 
791   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
792     setOperationAction(ISD::SELECT, VT, Custom);
793   }
794 
795   setOperationAction(ISD::SMULO, MVT::i64, Custom);
796   setOperationAction(ISD::UMULO, MVT::i64, Custom);
797 
798   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
799   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
801   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
802   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
803   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
804   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
805 
806   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
807   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
808   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
809   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
810   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
811   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
812   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
813   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
814   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
815 
816   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
817   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
818   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
819   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
820   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
821   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
822   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
823   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
824 
825   setTargetDAGCombine(ISD::ADD);
826   setTargetDAGCombine(ISD::ADDCARRY);
827   setTargetDAGCombine(ISD::SUB);
828   setTargetDAGCombine(ISD::SUBCARRY);
829   setTargetDAGCombine(ISD::FADD);
830   setTargetDAGCombine(ISD::FSUB);
831   setTargetDAGCombine(ISD::FMINNUM);
832   setTargetDAGCombine(ISD::FMAXNUM);
833   setTargetDAGCombine(ISD::FMINNUM_IEEE);
834   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
835   setTargetDAGCombine(ISD::FMA);
836   setTargetDAGCombine(ISD::SMIN);
837   setTargetDAGCombine(ISD::SMAX);
838   setTargetDAGCombine(ISD::UMIN);
839   setTargetDAGCombine(ISD::UMAX);
840   setTargetDAGCombine(ISD::SETCC);
841   setTargetDAGCombine(ISD::AND);
842   setTargetDAGCombine(ISD::OR);
843   setTargetDAGCombine(ISD::XOR);
844   setTargetDAGCombine(ISD::SINT_TO_FP);
845   setTargetDAGCombine(ISD::UINT_TO_FP);
846   setTargetDAGCombine(ISD::FCANONICALIZE);
847   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
848   setTargetDAGCombine(ISD::ZERO_EXTEND);
849   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
850   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
851   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
852 
853   // All memory operations. Some folding on the pointer operand is done to help
854   // matching the constant offsets in the addressing modes.
855   setTargetDAGCombine(ISD::LOAD);
856   setTargetDAGCombine(ISD::STORE);
857   setTargetDAGCombine(ISD::ATOMIC_LOAD);
858   setTargetDAGCombine(ISD::ATOMIC_STORE);
859   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
860   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
861   setTargetDAGCombine(ISD::ATOMIC_SWAP);
862   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
863   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
864   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
865   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
866   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
867   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
868   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
869   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
870   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
871   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
872   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
873   setTargetDAGCombine(ISD::INTRINSIC_VOID);
874   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
875 
876   // FIXME: In other contexts we pretend this is a per-function property.
877   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
878 
879   setSchedulingPreference(Sched::RegPressure);
880 }
881 
882 const GCNSubtarget *SITargetLowering::getSubtarget() const {
883   return Subtarget;
884 }
885 
886 //===----------------------------------------------------------------------===//
887 // TargetLowering queries
888 //===----------------------------------------------------------------------===//
889 
890 // v_mad_mix* support a conversion from f16 to f32.
891 //
892 // There is only one special case when denormals are enabled we don't currently,
893 // where this is OK to use.
894 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
895                                        EVT DestVT, EVT SrcVT) const {
896   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
897           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
898     DestVT.getScalarType() == MVT::f32 &&
899     SrcVT.getScalarType() == MVT::f16 &&
900     // TODO: This probably only requires no input flushing?
901     !hasFP32Denormals(DAG.getMachineFunction());
902 }
903 
904 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
905   // SI has some legal vector types, but no legal vector operations. Say no
906   // shuffles are legal in order to prefer scalarizing some vector operations.
907   return false;
908 }
909 
910 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
911                                                     CallingConv::ID CC,
912                                                     EVT VT) const {
913   if (CC == CallingConv::AMDGPU_KERNEL)
914     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
915 
916   if (VT.isVector()) {
917     EVT ScalarVT = VT.getScalarType();
918     unsigned Size = ScalarVT.getSizeInBits();
919     if (Size == 32)
920       return ScalarVT.getSimpleVT();
921 
922     if (Size > 32)
923       return MVT::i32;
924 
925     if (Size == 16 && Subtarget->has16BitInsts())
926       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
927   } else if (VT.getSizeInBits() > 32)
928     return MVT::i32;
929 
930   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
931 }
932 
933 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
934                                                          CallingConv::ID CC,
935                                                          EVT VT) const {
936   if (CC == CallingConv::AMDGPU_KERNEL)
937     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
938 
939   if (VT.isVector()) {
940     unsigned NumElts = VT.getVectorNumElements();
941     EVT ScalarVT = VT.getScalarType();
942     unsigned Size = ScalarVT.getSizeInBits();
943 
944     if (Size == 32)
945       return NumElts;
946 
947     if (Size > 32)
948       return NumElts * ((Size + 31) / 32);
949 
950     if (Size == 16 && Subtarget->has16BitInsts())
951       return (NumElts + 1) / 2;
952   } else if (VT.getSizeInBits() > 32)
953     return (VT.getSizeInBits() + 31) / 32;
954 
955   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
956 }
957 
958 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
959   LLVMContext &Context, CallingConv::ID CC,
960   EVT VT, EVT &IntermediateVT,
961   unsigned &NumIntermediates, MVT &RegisterVT) const {
962   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
963     unsigned NumElts = VT.getVectorNumElements();
964     EVT ScalarVT = VT.getScalarType();
965     unsigned Size = ScalarVT.getSizeInBits();
966     if (Size == 32) {
967       RegisterVT = ScalarVT.getSimpleVT();
968       IntermediateVT = RegisterVT;
969       NumIntermediates = NumElts;
970       return NumIntermediates;
971     }
972 
973     if (Size > 32) {
974       RegisterVT = MVT::i32;
975       IntermediateVT = RegisterVT;
976       NumIntermediates = NumElts * ((Size + 31) / 32);
977       return NumIntermediates;
978     }
979 
980     // FIXME: We should fix the ABI to be the same on targets without 16-bit
981     // support, but unless we can properly handle 3-vectors, it will be still be
982     // inconsistent.
983     if (Size == 16 && Subtarget->has16BitInsts()) {
984       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
985       IntermediateVT = RegisterVT;
986       NumIntermediates = (NumElts + 1) / 2;
987       return NumIntermediates;
988     }
989   }
990 
991   return TargetLowering::getVectorTypeBreakdownForCallingConv(
992     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
993 }
994 
995 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
996   assert(DMaskLanes != 0);
997 
998   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
999     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1000     return EVT::getVectorVT(Ty->getContext(),
1001                             EVT::getEVT(VT->getElementType()),
1002                             NumElts);
1003   }
1004 
1005   return EVT::getEVT(Ty);
1006 }
1007 
1008 // Peek through TFE struct returns to only use the data size.
1009 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1010   auto *ST = dyn_cast<StructType>(Ty);
1011   if (!ST)
1012     return memVTFromImageData(Ty, DMaskLanes);
1013 
1014   // Some intrinsics return an aggregate type - special case to work out the
1015   // correct memVT.
1016   //
1017   // Only limited forms of aggregate type currently expected.
1018   if (ST->getNumContainedTypes() != 2 ||
1019       !ST->getContainedType(1)->isIntegerTy(32))
1020     return EVT();
1021   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1022 }
1023 
1024 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1025                                           const CallInst &CI,
1026                                           MachineFunction &MF,
1027                                           unsigned IntrID) const {
1028   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1029           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1030     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1031                                                   (Intrinsic::ID)IntrID);
1032     if (Attr.hasFnAttribute(Attribute::ReadNone))
1033       return false;
1034 
1035     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1036 
1037     if (RsrcIntr->IsImage) {
1038       Info.ptrVal = MFI->getImagePSV(
1039         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1040         CI.getArgOperand(RsrcIntr->RsrcArg));
1041       Info.align.reset();
1042     } else {
1043       Info.ptrVal = MFI->getBufferPSV(
1044         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1045         CI.getArgOperand(RsrcIntr->RsrcArg));
1046     }
1047 
1048     Info.flags = MachineMemOperand::MODereferenceable;
1049     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1050       unsigned DMaskLanes = 4;
1051 
1052       if (RsrcIntr->IsImage) {
1053         const AMDGPU::ImageDimIntrinsicInfo *Intr
1054           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1055         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1056           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1057 
1058         if (!BaseOpcode->Gather4) {
1059           // If this isn't a gather, we may have excess loaded elements in the
1060           // IR type. Check the dmask for the real number of elements loaded.
1061           unsigned DMask
1062             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1063           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1064         }
1065 
1066         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1067       } else
1068         Info.memVT = EVT::getEVT(CI.getType());
1069 
1070       // FIXME: What does alignment mean for an image?
1071       Info.opc = ISD::INTRINSIC_W_CHAIN;
1072       Info.flags |= MachineMemOperand::MOLoad;
1073     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1074       Info.opc = ISD::INTRINSIC_VOID;
1075 
1076       Type *DataTy = CI.getArgOperand(0)->getType();
1077       if (RsrcIntr->IsImage) {
1078         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1079         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1080         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1081       } else
1082         Info.memVT = EVT::getEVT(DataTy);
1083 
1084       Info.flags |= MachineMemOperand::MOStore;
1085     } else {
1086       // Atomic
1087       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1088                                             ISD::INTRINSIC_W_CHAIN;
1089       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1090       Info.flags = MachineMemOperand::MOLoad |
1091                    MachineMemOperand::MOStore |
1092                    MachineMemOperand::MODereferenceable;
1093 
1094       // XXX - Should this be volatile without known ordering?
1095       Info.flags |= MachineMemOperand::MOVolatile;
1096     }
1097     return true;
1098   }
1099 
1100   switch (IntrID) {
1101   case Intrinsic::amdgcn_atomic_inc:
1102   case Intrinsic::amdgcn_atomic_dec:
1103   case Intrinsic::amdgcn_ds_ordered_add:
1104   case Intrinsic::amdgcn_ds_ordered_swap:
1105   case Intrinsic::amdgcn_ds_fadd:
1106   case Intrinsic::amdgcn_ds_fmin:
1107   case Intrinsic::amdgcn_ds_fmax: {
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(4));
1115     if (!Vol->isZero())
1116       Info.flags |= MachineMemOperand::MOVolatile;
1117 
1118     return true;
1119   }
1120   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1121     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1122 
1123     Info.opc = ISD::INTRINSIC_VOID;
1124     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1125     Info.ptrVal = MFI->getBufferPSV(
1126       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1127       CI.getArgOperand(1));
1128     Info.align.reset();
1129     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1130 
1131     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1132     if (!Vol || !Vol->isZero())
1133       Info.flags |= MachineMemOperand::MOVolatile;
1134 
1135     return true;
1136   }
1137   case Intrinsic::amdgcn_global_atomic_fadd: {
1138     Info.opc = ISD::INTRINSIC_VOID;
1139     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1140                             ->getPointerElementType());
1141     Info.ptrVal = CI.getOperand(0);
1142     Info.align.reset();
1143 
1144     // FIXME: Should report an atomic ordering here.
1145     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1146 
1147     return true;
1148   }
1149   case Intrinsic::amdgcn_ds_append:
1150   case Intrinsic::amdgcn_ds_consume: {
1151     Info.opc = ISD::INTRINSIC_W_CHAIN;
1152     Info.memVT = MVT::getVT(CI.getType());
1153     Info.ptrVal = CI.getOperand(0);
1154     Info.align.reset();
1155     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1156 
1157     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1158     if (!Vol->isZero())
1159       Info.flags |= MachineMemOperand::MOVolatile;
1160 
1161     return true;
1162   }
1163   case Intrinsic::amdgcn_global_atomic_csub: {
1164     Info.opc = ISD::INTRINSIC_W_CHAIN;
1165     Info.memVT = MVT::getVT(CI.getType());
1166     Info.ptrVal = CI.getOperand(0);
1167     Info.align.reset();
1168     Info.flags = MachineMemOperand::MOLoad |
1169                  MachineMemOperand::MOStore |
1170                  MachineMemOperand::MOVolatile;
1171     return true;
1172   }
1173   case Intrinsic::amdgcn_ds_gws_init:
1174   case Intrinsic::amdgcn_ds_gws_barrier:
1175   case Intrinsic::amdgcn_ds_gws_sema_v:
1176   case Intrinsic::amdgcn_ds_gws_sema_br:
1177   case Intrinsic::amdgcn_ds_gws_sema_p:
1178   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1179     Info.opc = ISD::INTRINSIC_VOID;
1180 
1181     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1182     Info.ptrVal =
1183         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1184 
1185     // This is an abstract access, but we need to specify a type and size.
1186     Info.memVT = MVT::i32;
1187     Info.size = 4;
1188     Info.align = Align(4);
1189 
1190     Info.flags = MachineMemOperand::MOStore;
1191     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1192       Info.flags = MachineMemOperand::MOLoad;
1193     return true;
1194   }
1195   default:
1196     return false;
1197   }
1198 }
1199 
1200 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1201                                             SmallVectorImpl<Value*> &Ops,
1202                                             Type *&AccessTy) const {
1203   switch (II->getIntrinsicID()) {
1204   case Intrinsic::amdgcn_atomic_inc:
1205   case Intrinsic::amdgcn_atomic_dec:
1206   case Intrinsic::amdgcn_ds_ordered_add:
1207   case Intrinsic::amdgcn_ds_ordered_swap:
1208   case Intrinsic::amdgcn_ds_append:
1209   case Intrinsic::amdgcn_ds_consume:
1210   case Intrinsic::amdgcn_ds_fadd:
1211   case Intrinsic::amdgcn_ds_fmin:
1212   case Intrinsic::amdgcn_ds_fmax:
1213   case Intrinsic::amdgcn_global_atomic_fadd:
1214   case Intrinsic::amdgcn_global_atomic_csub: {
1215     Value *Ptr = II->getArgOperand(0);
1216     AccessTy = II->getType();
1217     Ops.push_back(Ptr);
1218     return true;
1219   }
1220   default:
1221     return false;
1222   }
1223 }
1224 
1225 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1226   if (!Subtarget->hasFlatInstOffsets()) {
1227     // Flat instructions do not have offsets, and only have the register
1228     // address.
1229     return AM.BaseOffs == 0 && AM.Scale == 0;
1230   }
1231 
1232   return AM.Scale == 0 &&
1233          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1234                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1235                                   /*Signed=*/false));
1236 }
1237 
1238 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1239   if (Subtarget->hasFlatGlobalInsts())
1240     return AM.Scale == 0 &&
1241            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1242                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1243                                     /*Signed=*/true));
1244 
1245   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1246       // Assume the we will use FLAT for all global memory accesses
1247       // on VI.
1248       // FIXME: This assumption is currently wrong.  On VI we still use
1249       // MUBUF instructions for the r + i addressing mode.  As currently
1250       // implemented, the MUBUF instructions only work on buffer < 4GB.
1251       // It may be possible to support > 4GB buffers with MUBUF instructions,
1252       // by setting the stride value in the resource descriptor which would
1253       // increase the size limit to (stride * 4GB).  However, this is risky,
1254       // because it has never been validated.
1255     return isLegalFlatAddressingMode(AM);
1256   }
1257 
1258   return isLegalMUBUFAddressingMode(AM);
1259 }
1260 
1261 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1262   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1263   // additionally can do r + r + i with addr64. 32-bit has more addressing
1264   // mode options. Depending on the resource constant, it can also do
1265   // (i64 r0) + (i32 r1) * (i14 i).
1266   //
1267   // Private arrays end up using a scratch buffer most of the time, so also
1268   // assume those use MUBUF instructions. Scratch loads / stores are currently
1269   // implemented as mubuf instructions with offen bit set, so slightly
1270   // different than the normal addr64.
1271   if (!isUInt<12>(AM.BaseOffs))
1272     return false;
1273 
1274   // FIXME: Since we can split immediate into soffset and immediate offset,
1275   // would it make sense to allow any immediate?
1276 
1277   switch (AM.Scale) {
1278   case 0: // r + i or just i, depending on HasBaseReg.
1279     return true;
1280   case 1:
1281     return true; // We have r + r or r + i.
1282   case 2:
1283     if (AM.HasBaseReg) {
1284       // Reject 2 * r + r.
1285       return false;
1286     }
1287 
1288     // Allow 2 * r as r + r
1289     // Or  2 * r + i is allowed as r + r + i.
1290     return true;
1291   default: // Don't allow n * r
1292     return false;
1293   }
1294 }
1295 
1296 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1297                                              const AddrMode &AM, Type *Ty,
1298                                              unsigned AS, Instruction *I) const {
1299   // No global is ever allowed as a base.
1300   if (AM.BaseGV)
1301     return false;
1302 
1303   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1304     return isLegalGlobalAddressingMode(AM);
1305 
1306   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1307       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1308       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1309     // If the offset isn't a multiple of 4, it probably isn't going to be
1310     // correctly aligned.
1311     // FIXME: Can we get the real alignment here?
1312     if (AM.BaseOffs % 4 != 0)
1313       return isLegalMUBUFAddressingMode(AM);
1314 
1315     // There are no SMRD extloads, so if we have to do a small type access we
1316     // will use a MUBUF load.
1317     // FIXME?: We also need to do this if unaligned, but we don't know the
1318     // alignment here.
1319     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1320       return isLegalGlobalAddressingMode(AM);
1321 
1322     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1323       // SMRD instructions have an 8-bit, dword offset on SI.
1324       if (!isUInt<8>(AM.BaseOffs / 4))
1325         return false;
1326     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1327       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1328       // in 8-bits, it can use a smaller encoding.
1329       if (!isUInt<32>(AM.BaseOffs / 4))
1330         return false;
1331     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1332       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1333       if (!isUInt<20>(AM.BaseOffs))
1334         return false;
1335     } else
1336       llvm_unreachable("unhandled generation");
1337 
1338     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1339       return true;
1340 
1341     if (AM.Scale == 1 && AM.HasBaseReg)
1342       return true;
1343 
1344     return false;
1345 
1346   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1347     return isLegalMUBUFAddressingMode(AM);
1348   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1349              AS == AMDGPUAS::REGION_ADDRESS) {
1350     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1351     // field.
1352     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1353     // an 8-bit dword offset but we don't know the alignment here.
1354     if (!isUInt<16>(AM.BaseOffs))
1355       return false;
1356 
1357     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1358       return true;
1359 
1360     if (AM.Scale == 1 && AM.HasBaseReg)
1361       return true;
1362 
1363     return false;
1364   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1365              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1366     // For an unknown address space, this usually means that this is for some
1367     // reason being used for pure arithmetic, and not based on some addressing
1368     // computation. We don't have instructions that compute pointers with any
1369     // addressing modes, so treat them as having no offset like flat
1370     // instructions.
1371     return isLegalFlatAddressingMode(AM);
1372   }
1373 
1374   // Assume a user alias of global for unknown address spaces.
1375   return isLegalGlobalAddressingMode(AM);
1376 }
1377 
1378 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1379                                         const SelectionDAG &DAG) const {
1380   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1381     return (MemVT.getSizeInBits() <= 4 * 32);
1382   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1383     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1384     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1385   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1386     return (MemVT.getSizeInBits() <= 2 * 32);
1387   }
1388   return true;
1389 }
1390 
1391 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1392     unsigned Size, unsigned AddrSpace, Align Alignment,
1393     MachineMemOperand::Flags Flags, bool *IsFast) const {
1394   if (IsFast)
1395     *IsFast = false;
1396 
1397   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1398       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1399     // Check if alignment requirements for ds_read/write instructions are
1400     // disabled.
1401     if (Subtarget->hasUnalignedDSAccessEnabled()) {
1402       if (IsFast)
1403         *IsFast = true;
1404       return true;
1405     }
1406 
1407     if (Size == 64) {
1408       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1409       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1410       // with adjacent offsets.
1411       bool AlignedBy4 = Alignment >= Align(4);
1412       if (IsFast)
1413         *IsFast = AlignedBy4;
1414 
1415       return AlignedBy4;
1416     }
1417     if (Size == 96) {
1418       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1419       bool Aligned =
1420           Alignment >= Align(Subtarget->hasUnalignedDSAccess() ? 4 : 16);
1421       if (IsFast)
1422         *IsFast = Aligned;
1423 
1424       return Aligned;
1425     }
1426     if (Size == 128) {
1427       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1428       // can do a 8 byte aligned, 16 byte access in a single operation using
1429       // ds_read2/write2_b64.
1430       bool Aligned =
1431           Alignment >= Align(Subtarget->hasUnalignedDSAccess() ? 4 : 8);
1432       if (IsFast)
1433         *IsFast = Aligned;
1434 
1435       return Aligned;
1436     }
1437   }
1438 
1439   // FIXME: We have to be conservative here and assume that flat operations
1440   // will access scratch.  If we had access to the IR function, then we
1441   // could determine if any private memory was used in the function.
1442   if (!Subtarget->hasUnalignedScratchAccess() &&
1443       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1444        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1445     bool AlignedBy4 = Alignment >= Align(4);
1446     if (IsFast)
1447       *IsFast = AlignedBy4;
1448 
1449     return AlignedBy4;
1450   }
1451 
1452   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1453       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1454         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1455     // If we have an uniform constant load, it still requires using a slow
1456     // buffer instruction if unaligned.
1457     if (IsFast) {
1458       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1459       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1460       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1461                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1462         Alignment >= Align(4) : Alignment != Align(2);
1463     }
1464 
1465     return true;
1466   }
1467 
1468   // Smaller than dword value must be aligned.
1469   if (Size < 32)
1470     return false;
1471 
1472   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1473   // byte-address are ignored, thus forcing Dword alignment.
1474   // This applies to private, global, and constant memory.
1475   if (IsFast)
1476     *IsFast = true;
1477 
1478   return Size >= 32 && Alignment >= Align(4);
1479 }
1480 
1481 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1482     EVT VT, unsigned AddrSpace, unsigned Alignment,
1483     MachineMemOperand::Flags Flags, bool *IsFast) const {
1484   if (IsFast)
1485     *IsFast = false;
1486 
1487   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1488   // which isn't a simple VT.
1489   // Until MVT is extended to handle this, simply check for the size and
1490   // rely on the condition below: allow accesses if the size is a multiple of 4.
1491   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1492                            VT.getStoreSize() > 16)) {
1493     return false;
1494   }
1495 
1496   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1497                                             Align(Alignment), Flags, IsFast);
1498 }
1499 
1500 EVT SITargetLowering::getOptimalMemOpType(
1501     const MemOp &Op, const AttributeList &FuncAttributes) const {
1502   // FIXME: Should account for address space here.
1503 
1504   // The default fallback uses the private pointer size as a guess for a type to
1505   // use. Make sure we switch these to 64-bit accesses.
1506 
1507   if (Op.size() >= 16 &&
1508       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1509     return MVT::v4i32;
1510 
1511   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1512     return MVT::v2i32;
1513 
1514   // Use the default.
1515   return MVT::Other;
1516 }
1517 
1518 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1519   const MemSDNode *MemNode = cast<MemSDNode>(N);
1520   const Value *Ptr = MemNode->getMemOperand()->getValue();
1521   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1522   return I && I->getMetadata("amdgpu.noclobber");
1523 }
1524 
1525 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1526                                            unsigned DestAS) const {
1527   // Flat -> private/local is a simple truncate.
1528   // Flat -> global is no-op
1529   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1530     return true;
1531 
1532   const GCNTargetMachine &TM =
1533       static_cast<const GCNTargetMachine &>(getTargetMachine());
1534   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1535 }
1536 
1537 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1538   const MemSDNode *MemNode = cast<MemSDNode>(N);
1539 
1540   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1541 }
1542 
1543 TargetLoweringBase::LegalizeTypeAction
1544 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1545   int NumElts = VT.getVectorNumElements();
1546   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1547     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1548   return TargetLoweringBase::getPreferredVectorAction(VT);
1549 }
1550 
1551 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1552                                                          Type *Ty) const {
1553   // FIXME: Could be smarter if called for vector constants.
1554   return true;
1555 }
1556 
1557 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1558   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1559     switch (Op) {
1560     case ISD::LOAD:
1561     case ISD::STORE:
1562 
1563     // These operations are done with 32-bit instructions anyway.
1564     case ISD::AND:
1565     case ISD::OR:
1566     case ISD::XOR:
1567     case ISD::SELECT:
1568       // TODO: Extensions?
1569       return true;
1570     default:
1571       return false;
1572     }
1573   }
1574 
1575   // SimplifySetCC uses this function to determine whether or not it should
1576   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1577   if (VT == MVT::i1 && Op == ISD::SETCC)
1578     return false;
1579 
1580   return TargetLowering::isTypeDesirableForOp(Op, VT);
1581 }
1582 
1583 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1584                                                    const SDLoc &SL,
1585                                                    SDValue Chain,
1586                                                    uint64_t Offset) const {
1587   const DataLayout &DL = DAG.getDataLayout();
1588   MachineFunction &MF = DAG.getMachineFunction();
1589   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1590 
1591   const ArgDescriptor *InputPtrReg;
1592   const TargetRegisterClass *RC;
1593   LLT ArgTy;
1594 
1595   std::tie(InputPtrReg, RC, ArgTy) =
1596       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1597 
1598   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1599   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1600   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1601     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1602 
1603   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1604 }
1605 
1606 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1607                                             const SDLoc &SL) const {
1608   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1609                                                FIRST_IMPLICIT);
1610   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1611 }
1612 
1613 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1614                                          const SDLoc &SL, SDValue Val,
1615                                          bool Signed,
1616                                          const ISD::InputArg *Arg) const {
1617   // First, if it is a widened vector, narrow it.
1618   if (VT.isVector() &&
1619       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1620     EVT NarrowedVT =
1621         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1622                          VT.getVectorNumElements());
1623     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1624                       DAG.getConstant(0, SL, MVT::i32));
1625   }
1626 
1627   // Then convert the vector elements or scalar value.
1628   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1629       VT.bitsLT(MemVT)) {
1630     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1631     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1632   }
1633 
1634   if (MemVT.isFloatingPoint())
1635     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1636   else if (Signed)
1637     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1638   else
1639     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1640 
1641   return Val;
1642 }
1643 
1644 SDValue SITargetLowering::lowerKernargMemParameter(
1645     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1646     uint64_t Offset, Align Alignment, bool Signed,
1647     const ISD::InputArg *Arg) const {
1648   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1649 
1650   // Try to avoid using an extload by loading earlier than the argument address,
1651   // and extracting the relevant bits. The load should hopefully be merged with
1652   // the previous argument.
1653   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1654     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1655     int64_t AlignDownOffset = alignDown(Offset, 4);
1656     int64_t OffsetDiff = Offset - AlignDownOffset;
1657 
1658     EVT IntVT = MemVT.changeTypeToInteger();
1659 
1660     // TODO: If we passed in the base kernel offset we could have a better
1661     // alignment than 4, but we don't really need it.
1662     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1663     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1664                                MachineMemOperand::MODereferenceable |
1665                                MachineMemOperand::MOInvariant);
1666 
1667     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1668     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1669 
1670     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1671     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1672     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1673 
1674 
1675     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1676   }
1677 
1678   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1679   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1680                              MachineMemOperand::MODereferenceable |
1681                                  MachineMemOperand::MOInvariant);
1682 
1683   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1684   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1685 }
1686 
1687 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1688                                               const SDLoc &SL, SDValue Chain,
1689                                               const ISD::InputArg &Arg) const {
1690   MachineFunction &MF = DAG.getMachineFunction();
1691   MachineFrameInfo &MFI = MF.getFrameInfo();
1692 
1693   if (Arg.Flags.isByVal()) {
1694     unsigned Size = Arg.Flags.getByValSize();
1695     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1696     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1697   }
1698 
1699   unsigned ArgOffset = VA.getLocMemOffset();
1700   unsigned ArgSize = VA.getValVT().getStoreSize();
1701 
1702   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1703 
1704   // Create load nodes to retrieve arguments from the stack.
1705   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1706   SDValue ArgValue;
1707 
1708   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1709   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1710   MVT MemVT = VA.getValVT();
1711 
1712   switch (VA.getLocInfo()) {
1713   default:
1714     break;
1715   case CCValAssign::BCvt:
1716     MemVT = VA.getLocVT();
1717     break;
1718   case CCValAssign::SExt:
1719     ExtType = ISD::SEXTLOAD;
1720     break;
1721   case CCValAssign::ZExt:
1722     ExtType = ISD::ZEXTLOAD;
1723     break;
1724   case CCValAssign::AExt:
1725     ExtType = ISD::EXTLOAD;
1726     break;
1727   }
1728 
1729   ArgValue = DAG.getExtLoad(
1730     ExtType, SL, VA.getLocVT(), Chain, FIN,
1731     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1732     MemVT);
1733   return ArgValue;
1734 }
1735 
1736 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1737   const SIMachineFunctionInfo &MFI,
1738   EVT VT,
1739   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1740   const ArgDescriptor *Reg;
1741   const TargetRegisterClass *RC;
1742   LLT Ty;
1743 
1744   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1745   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1746 }
1747 
1748 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1749                                    CallingConv::ID CallConv,
1750                                    ArrayRef<ISD::InputArg> Ins,
1751                                    BitVector &Skipped,
1752                                    FunctionType *FType,
1753                                    SIMachineFunctionInfo *Info) {
1754   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1755     const ISD::InputArg *Arg = &Ins[I];
1756 
1757     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1758            "vector type argument should have been split");
1759 
1760     // First check if it's a PS input addr.
1761     if (CallConv == CallingConv::AMDGPU_PS &&
1762         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1763       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1764 
1765       // Inconveniently only the first part of the split is marked as isSplit,
1766       // so skip to the end. We only want to increment PSInputNum once for the
1767       // entire split argument.
1768       if (Arg->Flags.isSplit()) {
1769         while (!Arg->Flags.isSplitEnd()) {
1770           assert((!Arg->VT.isVector() ||
1771                   Arg->VT.getScalarSizeInBits() == 16) &&
1772                  "unexpected vector split in ps argument type");
1773           if (!SkipArg)
1774             Splits.push_back(*Arg);
1775           Arg = &Ins[++I];
1776         }
1777       }
1778 
1779       if (SkipArg) {
1780         // We can safely skip PS inputs.
1781         Skipped.set(Arg->getOrigArgIndex());
1782         ++PSInputNum;
1783         continue;
1784       }
1785 
1786       Info->markPSInputAllocated(PSInputNum);
1787       if (Arg->Used)
1788         Info->markPSInputEnabled(PSInputNum);
1789 
1790       ++PSInputNum;
1791     }
1792 
1793     Splits.push_back(*Arg);
1794   }
1795 }
1796 
1797 // Allocate special inputs passed in VGPRs.
1798 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1799                                                       MachineFunction &MF,
1800                                                       const SIRegisterInfo &TRI,
1801                                                       SIMachineFunctionInfo &Info) const {
1802   const LLT S32 = LLT::scalar(32);
1803   MachineRegisterInfo &MRI = MF.getRegInfo();
1804 
1805   if (Info.hasWorkItemIDX()) {
1806     Register Reg = AMDGPU::VGPR0;
1807     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1808 
1809     CCInfo.AllocateReg(Reg);
1810     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1811   }
1812 
1813   if (Info.hasWorkItemIDY()) {
1814     Register Reg = AMDGPU::VGPR1;
1815     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1816 
1817     CCInfo.AllocateReg(Reg);
1818     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1819   }
1820 
1821   if (Info.hasWorkItemIDZ()) {
1822     Register Reg = AMDGPU::VGPR2;
1823     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1824 
1825     CCInfo.AllocateReg(Reg);
1826     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1827   }
1828 }
1829 
1830 // Try to allocate a VGPR at the end of the argument list, or if no argument
1831 // VGPRs are left allocating a stack slot.
1832 // If \p Mask is is given it indicates bitfield position in the register.
1833 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1834 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1835                                          ArgDescriptor Arg = ArgDescriptor()) {
1836   if (Arg.isSet())
1837     return ArgDescriptor::createArg(Arg, Mask);
1838 
1839   ArrayRef<MCPhysReg> ArgVGPRs
1840     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1841   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1842   if (RegIdx == ArgVGPRs.size()) {
1843     // Spill to stack required.
1844     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1845 
1846     return ArgDescriptor::createStack(Offset, Mask);
1847   }
1848 
1849   unsigned Reg = ArgVGPRs[RegIdx];
1850   Reg = CCInfo.AllocateReg(Reg);
1851   assert(Reg != AMDGPU::NoRegister);
1852 
1853   MachineFunction &MF = CCInfo.getMachineFunction();
1854   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1855   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1856   return ArgDescriptor::createRegister(Reg, Mask);
1857 }
1858 
1859 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1860                                              const TargetRegisterClass *RC,
1861                                              unsigned NumArgRegs) {
1862   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1863   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1864   if (RegIdx == ArgSGPRs.size())
1865     report_fatal_error("ran out of SGPRs for arguments");
1866 
1867   unsigned Reg = ArgSGPRs[RegIdx];
1868   Reg = CCInfo.AllocateReg(Reg);
1869   assert(Reg != AMDGPU::NoRegister);
1870 
1871   MachineFunction &MF = CCInfo.getMachineFunction();
1872   MF.addLiveIn(Reg, RC);
1873   return ArgDescriptor::createRegister(Reg);
1874 }
1875 
1876 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1877   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1878 }
1879 
1880 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1881   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1882 }
1883 
1884 /// Allocate implicit function VGPR arguments at the end of allocated user
1885 /// arguments.
1886 void SITargetLowering::allocateSpecialInputVGPRs(
1887   CCState &CCInfo, MachineFunction &MF,
1888   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1889   const unsigned Mask = 0x3ff;
1890   ArgDescriptor Arg;
1891 
1892   if (Info.hasWorkItemIDX()) {
1893     Arg = allocateVGPR32Input(CCInfo, Mask);
1894     Info.setWorkItemIDX(Arg);
1895   }
1896 
1897   if (Info.hasWorkItemIDY()) {
1898     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1899     Info.setWorkItemIDY(Arg);
1900   }
1901 
1902   if (Info.hasWorkItemIDZ())
1903     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1904 }
1905 
1906 /// Allocate implicit function VGPR arguments in fixed registers.
1907 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1908   CCState &CCInfo, MachineFunction &MF,
1909   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1910   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1911   if (!Reg)
1912     report_fatal_error("failed to allocated VGPR for implicit arguments");
1913 
1914   const unsigned Mask = 0x3ff;
1915   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1916   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1917   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1918 }
1919 
1920 void SITargetLowering::allocateSpecialInputSGPRs(
1921   CCState &CCInfo,
1922   MachineFunction &MF,
1923   const SIRegisterInfo &TRI,
1924   SIMachineFunctionInfo &Info) const {
1925   auto &ArgInfo = Info.getArgInfo();
1926 
1927   // TODO: Unify handling with private memory pointers.
1928 
1929   if (Info.hasDispatchPtr())
1930     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1931 
1932   if (Info.hasQueuePtr())
1933     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1934 
1935   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1936   // constant offset from the kernarg segment.
1937   if (Info.hasImplicitArgPtr())
1938     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1939 
1940   if (Info.hasDispatchID())
1941     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1942 
1943   // flat_scratch_init is not applicable for non-kernel functions.
1944 
1945   if (Info.hasWorkGroupIDX())
1946     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1947 
1948   if (Info.hasWorkGroupIDY())
1949     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1950 
1951   if (Info.hasWorkGroupIDZ())
1952     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1953 }
1954 
1955 // Allocate special inputs passed in user SGPRs.
1956 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1957                                             MachineFunction &MF,
1958                                             const SIRegisterInfo &TRI,
1959                                             SIMachineFunctionInfo &Info) const {
1960   if (Info.hasImplicitBufferPtr()) {
1961     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1962     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1963     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1964   }
1965 
1966   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1967   if (Info.hasPrivateSegmentBuffer()) {
1968     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1969     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1970     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1971   }
1972 
1973   if (Info.hasDispatchPtr()) {
1974     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
1975     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1976     CCInfo.AllocateReg(DispatchPtrReg);
1977   }
1978 
1979   if (Info.hasQueuePtr()) {
1980     Register QueuePtrReg = Info.addQueuePtr(TRI);
1981     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1982     CCInfo.AllocateReg(QueuePtrReg);
1983   }
1984 
1985   if (Info.hasKernargSegmentPtr()) {
1986     MachineRegisterInfo &MRI = MF.getRegInfo();
1987     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1988     CCInfo.AllocateReg(InputPtrReg);
1989 
1990     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1991     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1992   }
1993 
1994   if (Info.hasDispatchID()) {
1995     Register DispatchIDReg = Info.addDispatchID(TRI);
1996     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1997     CCInfo.AllocateReg(DispatchIDReg);
1998   }
1999 
2000   if (Info.hasFlatScratchInit()) {
2001     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2002     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2003     CCInfo.AllocateReg(FlatScratchInitReg);
2004   }
2005 
2006   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2007   // these from the dispatch pointer.
2008 }
2009 
2010 // Allocate special input registers that are initialized per-wave.
2011 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2012                                            MachineFunction &MF,
2013                                            SIMachineFunctionInfo &Info,
2014                                            CallingConv::ID CallConv,
2015                                            bool IsShader) const {
2016   if (Info.hasWorkGroupIDX()) {
2017     Register Reg = Info.addWorkGroupIDX();
2018     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2019     CCInfo.AllocateReg(Reg);
2020   }
2021 
2022   if (Info.hasWorkGroupIDY()) {
2023     Register Reg = Info.addWorkGroupIDY();
2024     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2025     CCInfo.AllocateReg(Reg);
2026   }
2027 
2028   if (Info.hasWorkGroupIDZ()) {
2029     Register Reg = Info.addWorkGroupIDZ();
2030     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2031     CCInfo.AllocateReg(Reg);
2032   }
2033 
2034   if (Info.hasWorkGroupInfo()) {
2035     Register Reg = Info.addWorkGroupInfo();
2036     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2037     CCInfo.AllocateReg(Reg);
2038   }
2039 
2040   if (Info.hasPrivateSegmentWaveByteOffset()) {
2041     // Scratch wave offset passed in system SGPR.
2042     unsigned PrivateSegmentWaveByteOffsetReg;
2043 
2044     if (IsShader) {
2045       PrivateSegmentWaveByteOffsetReg =
2046         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2047 
2048       // This is true if the scratch wave byte offset doesn't have a fixed
2049       // location.
2050       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2051         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2052         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2053       }
2054     } else
2055       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2056 
2057     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2058     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2059   }
2060 }
2061 
2062 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2063                                      MachineFunction &MF,
2064                                      const SIRegisterInfo &TRI,
2065                                      SIMachineFunctionInfo &Info) {
2066   // Now that we've figured out where the scratch register inputs are, see if
2067   // should reserve the arguments and use them directly.
2068   MachineFrameInfo &MFI = MF.getFrameInfo();
2069   bool HasStackObjects = MFI.hasStackObjects();
2070   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2071 
2072   // Record that we know we have non-spill stack objects so we don't need to
2073   // check all stack objects later.
2074   if (HasStackObjects)
2075     Info.setHasNonSpillStackObjects(true);
2076 
2077   // Everything live out of a block is spilled with fast regalloc, so it's
2078   // almost certain that spilling will be required.
2079   if (TM.getOptLevel() == CodeGenOpt::None)
2080     HasStackObjects = true;
2081 
2082   // For now assume stack access is needed in any callee functions, so we need
2083   // the scratch registers to pass in.
2084   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2085 
2086   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2087     // If we have stack objects, we unquestionably need the private buffer
2088     // resource. For the Code Object V2 ABI, this will be the first 4 user
2089     // SGPR inputs. We can reserve those and use them directly.
2090 
2091     Register PrivateSegmentBufferReg =
2092         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2093     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2094   } else {
2095     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2096     // We tentatively reserve the last registers (skipping the last registers
2097     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2098     // we'll replace these with the ones immediately after those which were
2099     // really allocated. In the prologue copies will be inserted from the
2100     // argument to these reserved registers.
2101 
2102     // Without HSA, relocations are used for the scratch pointer and the
2103     // buffer resource setup is always inserted in the prologue. Scratch wave
2104     // offset is still in an input SGPR.
2105     Info.setScratchRSrcReg(ReservedBufferReg);
2106   }
2107 
2108   MachineRegisterInfo &MRI = MF.getRegInfo();
2109 
2110   // For entry functions we have to set up the stack pointer if we use it,
2111   // whereas non-entry functions get this "for free". This means there is no
2112   // intrinsic advantage to using S32 over S34 in cases where we do not have
2113   // calls but do need a frame pointer (i.e. if we are requested to have one
2114   // because frame pointer elimination is disabled). To keep things simple we
2115   // only ever use S32 as the call ABI stack pointer, and so using it does not
2116   // imply we need a separate frame pointer.
2117   //
2118   // Try to use s32 as the SP, but move it if it would interfere with input
2119   // arguments. This won't work with calls though.
2120   //
2121   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2122   // registers.
2123   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2124     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2125   } else {
2126     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2127 
2128     if (MFI.hasCalls())
2129       report_fatal_error("call in graphics shader with too many input SGPRs");
2130 
2131     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2132       if (!MRI.isLiveIn(Reg)) {
2133         Info.setStackPtrOffsetReg(Reg);
2134         break;
2135       }
2136     }
2137 
2138     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2139       report_fatal_error("failed to find register for SP");
2140   }
2141 
2142   // hasFP should be accurate for entry functions even before the frame is
2143   // finalized, because it does not rely on the known stack size, only
2144   // properties like whether variable sized objects are present.
2145   if (ST.getFrameLowering()->hasFP(MF)) {
2146     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2147   }
2148 }
2149 
2150 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2151   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2152   return !Info->isEntryFunction();
2153 }
2154 
2155 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2156 
2157 }
2158 
2159 void SITargetLowering::insertCopiesSplitCSR(
2160   MachineBasicBlock *Entry,
2161   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2162   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2163 
2164   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2165   if (!IStart)
2166     return;
2167 
2168   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2169   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2170   MachineBasicBlock::iterator MBBI = Entry->begin();
2171   for (const MCPhysReg *I = IStart; *I; ++I) {
2172     const TargetRegisterClass *RC = nullptr;
2173     if (AMDGPU::SReg_64RegClass.contains(*I))
2174       RC = &AMDGPU::SGPR_64RegClass;
2175     else if (AMDGPU::SReg_32RegClass.contains(*I))
2176       RC = &AMDGPU::SGPR_32RegClass;
2177     else
2178       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2179 
2180     Register NewVR = MRI->createVirtualRegister(RC);
2181     // Create copy from CSR to a virtual register.
2182     Entry->addLiveIn(*I);
2183     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2184       .addReg(*I);
2185 
2186     // Insert the copy-back instructions right before the terminator.
2187     for (auto *Exit : Exits)
2188       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2189               TII->get(TargetOpcode::COPY), *I)
2190         .addReg(NewVR);
2191   }
2192 }
2193 
2194 SDValue SITargetLowering::LowerFormalArguments(
2195     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2196     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2197     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2198   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2199 
2200   MachineFunction &MF = DAG.getMachineFunction();
2201   const Function &Fn = MF.getFunction();
2202   FunctionType *FType = MF.getFunction().getFunctionType();
2203   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2204 
2205   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2206     DiagnosticInfoUnsupported NoGraphicsHSA(
2207         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2208     DAG.getContext()->diagnose(NoGraphicsHSA);
2209     return DAG.getEntryNode();
2210   }
2211 
2212   SmallVector<ISD::InputArg, 16> Splits;
2213   SmallVector<CCValAssign, 16> ArgLocs;
2214   BitVector Skipped(Ins.size());
2215   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2216                  *DAG.getContext());
2217 
2218   bool IsShader = AMDGPU::isShader(CallConv);
2219   bool IsKernel = AMDGPU::isKernel(CallConv);
2220   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2221 
2222   if (IsShader) {
2223     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2224 
2225     // At least one interpolation mode must be enabled or else the GPU will
2226     // hang.
2227     //
2228     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2229     // set PSInputAddr, the user wants to enable some bits after the compilation
2230     // based on run-time states. Since we can't know what the final PSInputEna
2231     // will look like, so we shouldn't do anything here and the user should take
2232     // responsibility for the correct programming.
2233     //
2234     // Otherwise, the following restrictions apply:
2235     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2236     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2237     //   enabled too.
2238     if (CallConv == CallingConv::AMDGPU_PS) {
2239       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2240            ((Info->getPSInputAddr() & 0xF) == 0 &&
2241             Info->isPSInputAllocated(11))) {
2242         CCInfo.AllocateReg(AMDGPU::VGPR0);
2243         CCInfo.AllocateReg(AMDGPU::VGPR1);
2244         Info->markPSInputAllocated(0);
2245         Info->markPSInputEnabled(0);
2246       }
2247       if (Subtarget->isAmdPalOS()) {
2248         // For isAmdPalOS, the user does not enable some bits after compilation
2249         // based on run-time states; the register values being generated here are
2250         // the final ones set in hardware. Therefore we need to apply the
2251         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2252         // a bit is set in PSInputAddr but not PSInputEnable is where the
2253         // frontend set up an input arg for a particular interpolation mode, but
2254         // nothing uses that input arg. Really we should have an earlier pass
2255         // that removes such an arg.)
2256         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2257         if ((PsInputBits & 0x7F) == 0 ||
2258             ((PsInputBits & 0xF) == 0 &&
2259              (PsInputBits >> 11 & 1)))
2260           Info->markPSInputEnabled(
2261               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2262       }
2263     }
2264 
2265     assert(!Info->hasDispatchPtr() &&
2266            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2267            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2268            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2269            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2270            !Info->hasWorkItemIDZ());
2271   } else if (IsKernel) {
2272     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2273   } else {
2274     Splits.append(Ins.begin(), Ins.end());
2275   }
2276 
2277   if (IsEntryFunc) {
2278     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2279     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2280   } else {
2281     // For the fixed ABI, pass workitem IDs in the last argument register.
2282     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2283       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2284   }
2285 
2286   if (IsKernel) {
2287     analyzeFormalArgumentsCompute(CCInfo, Ins);
2288   } else {
2289     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2290     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2291   }
2292 
2293   SmallVector<SDValue, 16> Chains;
2294 
2295   // FIXME: This is the minimum kernel argument alignment. We should improve
2296   // this to the maximum alignment of the arguments.
2297   //
2298   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2299   // kern arg offset.
2300   const Align KernelArgBaseAlign = Align(16);
2301 
2302   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2303     const ISD::InputArg &Arg = Ins[i];
2304     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2305       InVals.push_back(DAG.getUNDEF(Arg.VT));
2306       continue;
2307     }
2308 
2309     CCValAssign &VA = ArgLocs[ArgIdx++];
2310     MVT VT = VA.getLocVT();
2311 
2312     if (IsEntryFunc && VA.isMemLoc()) {
2313       VT = Ins[i].VT;
2314       EVT MemVT = VA.getLocVT();
2315 
2316       const uint64_t Offset = VA.getLocMemOffset();
2317       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2318 
2319       if (Arg.Flags.isByRef()) {
2320         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2321 
2322         const GCNTargetMachine &TM =
2323             static_cast<const GCNTargetMachine &>(getTargetMachine());
2324         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2325                                     Arg.Flags.getPointerAddrSpace())) {
2326           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2327                                      Arg.Flags.getPointerAddrSpace());
2328         }
2329 
2330         InVals.push_back(Ptr);
2331         continue;
2332       }
2333 
2334       SDValue Arg = lowerKernargMemParameter(
2335         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2336       Chains.push_back(Arg.getValue(1));
2337 
2338       auto *ParamTy =
2339         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2340       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2341           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2342                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2343         // On SI local pointers are just offsets into LDS, so they are always
2344         // less than 16-bits.  On CI and newer they could potentially be
2345         // real pointers, so we can't guarantee their size.
2346         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2347                           DAG.getValueType(MVT::i16));
2348       }
2349 
2350       InVals.push_back(Arg);
2351       continue;
2352     } else if (!IsEntryFunc && VA.isMemLoc()) {
2353       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2354       InVals.push_back(Val);
2355       if (!Arg.Flags.isByVal())
2356         Chains.push_back(Val.getValue(1));
2357       continue;
2358     }
2359 
2360     assert(VA.isRegLoc() && "Parameter must be in a register!");
2361 
2362     Register Reg = VA.getLocReg();
2363     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2364     EVT ValVT = VA.getValVT();
2365 
2366     Reg = MF.addLiveIn(Reg, RC);
2367     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2368 
2369     if (Arg.Flags.isSRet()) {
2370       // The return object should be reasonably addressable.
2371 
2372       // FIXME: This helps when the return is a real sret. If it is a
2373       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2374       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2375       unsigned NumBits
2376         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2377       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2378         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2379     }
2380 
2381     // If this is an 8 or 16-bit value, it is really passed promoted
2382     // to 32 bits. Insert an assert[sz]ext to capture this, then
2383     // truncate to the right size.
2384     switch (VA.getLocInfo()) {
2385     case CCValAssign::Full:
2386       break;
2387     case CCValAssign::BCvt:
2388       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2389       break;
2390     case CCValAssign::SExt:
2391       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2392                         DAG.getValueType(ValVT));
2393       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2394       break;
2395     case CCValAssign::ZExt:
2396       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2397                         DAG.getValueType(ValVT));
2398       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2399       break;
2400     case CCValAssign::AExt:
2401       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2402       break;
2403     default:
2404       llvm_unreachable("Unknown loc info!");
2405     }
2406 
2407     InVals.push_back(Val);
2408   }
2409 
2410   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2411     // Special inputs come after user arguments.
2412     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2413   }
2414 
2415   // Start adding system SGPRs.
2416   if (IsEntryFunc) {
2417     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2418   } else {
2419     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2420     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2421   }
2422 
2423   auto &ArgUsageInfo =
2424     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2425   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2426 
2427   unsigned StackArgSize = CCInfo.getNextStackOffset();
2428   Info->setBytesInStackArgArea(StackArgSize);
2429 
2430   return Chains.empty() ? Chain :
2431     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2432 }
2433 
2434 // TODO: If return values can't fit in registers, we should return as many as
2435 // possible in registers before passing on stack.
2436 bool SITargetLowering::CanLowerReturn(
2437   CallingConv::ID CallConv,
2438   MachineFunction &MF, bool IsVarArg,
2439   const SmallVectorImpl<ISD::OutputArg> &Outs,
2440   LLVMContext &Context) const {
2441   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2442   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2443   // for shaders. Vector types should be explicitly handled by CC.
2444   if (AMDGPU::isEntryFunctionCC(CallConv))
2445     return true;
2446 
2447   SmallVector<CCValAssign, 16> RVLocs;
2448   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2449   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2450 }
2451 
2452 SDValue
2453 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2454                               bool isVarArg,
2455                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2456                               const SmallVectorImpl<SDValue> &OutVals,
2457                               const SDLoc &DL, SelectionDAG &DAG) const {
2458   MachineFunction &MF = DAG.getMachineFunction();
2459   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2460 
2461   if (AMDGPU::isKernel(CallConv)) {
2462     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2463                                              OutVals, DL, DAG);
2464   }
2465 
2466   bool IsShader = AMDGPU::isShader(CallConv);
2467 
2468   Info->setIfReturnsVoid(Outs.empty());
2469   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2470 
2471   // CCValAssign - represent the assignment of the return value to a location.
2472   SmallVector<CCValAssign, 48> RVLocs;
2473   SmallVector<ISD::OutputArg, 48> Splits;
2474 
2475   // CCState - Info about the registers and stack slots.
2476   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2477                  *DAG.getContext());
2478 
2479   // Analyze outgoing return values.
2480   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2481 
2482   SDValue Flag;
2483   SmallVector<SDValue, 48> RetOps;
2484   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2485 
2486   // Add return address for callable functions.
2487   if (!Info->isEntryFunction()) {
2488     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2489     SDValue ReturnAddrReg = CreateLiveInRegister(
2490       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2491 
2492     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2493         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2494         MVT::i64);
2495     Chain =
2496         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2497     Flag = Chain.getValue(1);
2498     RetOps.push_back(ReturnAddrVirtualReg);
2499   }
2500 
2501   // Copy the result values into the output registers.
2502   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2503        ++I, ++RealRVLocIdx) {
2504     CCValAssign &VA = RVLocs[I];
2505     assert(VA.isRegLoc() && "Can only return in registers!");
2506     // TODO: Partially return in registers if return values don't fit.
2507     SDValue Arg = OutVals[RealRVLocIdx];
2508 
2509     // Copied from other backends.
2510     switch (VA.getLocInfo()) {
2511     case CCValAssign::Full:
2512       break;
2513     case CCValAssign::BCvt:
2514       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2515       break;
2516     case CCValAssign::SExt:
2517       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2518       break;
2519     case CCValAssign::ZExt:
2520       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2521       break;
2522     case CCValAssign::AExt:
2523       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2524       break;
2525     default:
2526       llvm_unreachable("Unknown loc info!");
2527     }
2528 
2529     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2530     Flag = Chain.getValue(1);
2531     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2532   }
2533 
2534   // FIXME: Does sret work properly?
2535   if (!Info->isEntryFunction()) {
2536     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2537     const MCPhysReg *I =
2538       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2539     if (I) {
2540       for (; *I; ++I) {
2541         if (AMDGPU::SReg_64RegClass.contains(*I))
2542           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2543         else if (AMDGPU::SReg_32RegClass.contains(*I))
2544           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2545         else
2546           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2547       }
2548     }
2549   }
2550 
2551   // Update chain and glue.
2552   RetOps[0] = Chain;
2553   if (Flag.getNode())
2554     RetOps.push_back(Flag);
2555 
2556   unsigned Opc = AMDGPUISD::ENDPGM;
2557   if (!IsWaveEnd)
2558     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2559   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2560 }
2561 
2562 SDValue SITargetLowering::LowerCallResult(
2563     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2564     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2565     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2566     SDValue ThisVal) const {
2567   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2568 
2569   // Assign locations to each value returned by this call.
2570   SmallVector<CCValAssign, 16> RVLocs;
2571   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2572                  *DAG.getContext());
2573   CCInfo.AnalyzeCallResult(Ins, RetCC);
2574 
2575   // Copy all of the result registers out of their specified physreg.
2576   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2577     CCValAssign VA = RVLocs[i];
2578     SDValue Val;
2579 
2580     if (VA.isRegLoc()) {
2581       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2582       Chain = Val.getValue(1);
2583       InFlag = Val.getValue(2);
2584     } else if (VA.isMemLoc()) {
2585       report_fatal_error("TODO: return values in memory");
2586     } else
2587       llvm_unreachable("unknown argument location type");
2588 
2589     switch (VA.getLocInfo()) {
2590     case CCValAssign::Full:
2591       break;
2592     case CCValAssign::BCvt:
2593       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2594       break;
2595     case CCValAssign::ZExt:
2596       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2597                         DAG.getValueType(VA.getValVT()));
2598       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2599       break;
2600     case CCValAssign::SExt:
2601       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2602                         DAG.getValueType(VA.getValVT()));
2603       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2604       break;
2605     case CCValAssign::AExt:
2606       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2607       break;
2608     default:
2609       llvm_unreachable("Unknown loc info!");
2610     }
2611 
2612     InVals.push_back(Val);
2613   }
2614 
2615   return Chain;
2616 }
2617 
2618 // Add code to pass special inputs required depending on used features separate
2619 // from the explicit user arguments present in the IR.
2620 void SITargetLowering::passSpecialInputs(
2621     CallLoweringInfo &CLI,
2622     CCState &CCInfo,
2623     const SIMachineFunctionInfo &Info,
2624     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2625     SmallVectorImpl<SDValue> &MemOpChains,
2626     SDValue Chain) const {
2627   // If we don't have a call site, this was a call inserted by
2628   // legalization. These can never use special inputs.
2629   if (!CLI.CB)
2630     return;
2631 
2632   SelectionDAG &DAG = CLI.DAG;
2633   const SDLoc &DL = CLI.DL;
2634 
2635   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2636   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2637 
2638   const AMDGPUFunctionArgInfo *CalleeArgInfo
2639     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2640   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2641     auto &ArgUsageInfo =
2642       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2643     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2644   }
2645 
2646   // TODO: Unify with private memory register handling. This is complicated by
2647   // the fact that at least in kernels, the input argument is not necessarily
2648   // in the same location as the input.
2649   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2650     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2651     AMDGPUFunctionArgInfo::QUEUE_PTR,
2652     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2653     AMDGPUFunctionArgInfo::DISPATCH_ID,
2654     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2655     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2656     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2657   };
2658 
2659   for (auto InputID : InputRegs) {
2660     const ArgDescriptor *OutgoingArg;
2661     const TargetRegisterClass *ArgRC;
2662     LLT ArgTy;
2663 
2664     std::tie(OutgoingArg, ArgRC, ArgTy) =
2665         CalleeArgInfo->getPreloadedValue(InputID);
2666     if (!OutgoingArg)
2667       continue;
2668 
2669     const ArgDescriptor *IncomingArg;
2670     const TargetRegisterClass *IncomingArgRC;
2671     LLT Ty;
2672     std::tie(IncomingArg, IncomingArgRC, Ty) =
2673         CallerArgInfo.getPreloadedValue(InputID);
2674     assert(IncomingArgRC == ArgRC);
2675 
2676     // All special arguments are ints for now.
2677     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2678     SDValue InputReg;
2679 
2680     if (IncomingArg) {
2681       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2682     } else {
2683       // The implicit arg ptr is special because it doesn't have a corresponding
2684       // input for kernels, and is computed from the kernarg segment pointer.
2685       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2686       InputReg = getImplicitArgPtr(DAG, DL);
2687     }
2688 
2689     if (OutgoingArg->isRegister()) {
2690       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2691       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2692         report_fatal_error("failed to allocate implicit input argument");
2693     } else {
2694       unsigned SpecialArgOffset =
2695           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2696       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2697                                               SpecialArgOffset);
2698       MemOpChains.push_back(ArgStore);
2699     }
2700   }
2701 
2702   // Pack workitem IDs into a single register or pass it as is if already
2703   // packed.
2704   const ArgDescriptor *OutgoingArg;
2705   const TargetRegisterClass *ArgRC;
2706   LLT Ty;
2707 
2708   std::tie(OutgoingArg, ArgRC, Ty) =
2709       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2710   if (!OutgoingArg)
2711     std::tie(OutgoingArg, ArgRC, Ty) =
2712         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2713   if (!OutgoingArg)
2714     std::tie(OutgoingArg, ArgRC, Ty) =
2715         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2716   if (!OutgoingArg)
2717     return;
2718 
2719   const ArgDescriptor *IncomingArgX = std::get<0>(
2720       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2721   const ArgDescriptor *IncomingArgY = std::get<0>(
2722       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2723   const ArgDescriptor *IncomingArgZ = std::get<0>(
2724       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2725 
2726   SDValue InputReg;
2727   SDLoc SL;
2728 
2729   // If incoming ids are not packed we need to pack them.
2730   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2731     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2732 
2733   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2734     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2735     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2736                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2737     InputReg = InputReg.getNode() ?
2738                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2739   }
2740 
2741   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2742     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2743     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2744                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2745     InputReg = InputReg.getNode() ?
2746                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2747   }
2748 
2749   if (!InputReg.getNode()) {
2750     // Workitem ids are already packed, any of present incoming arguments
2751     // will carry all required fields.
2752     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2753       IncomingArgX ? *IncomingArgX :
2754       IncomingArgY ? *IncomingArgY :
2755                      *IncomingArgZ, ~0u);
2756     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2757   }
2758 
2759   if (OutgoingArg->isRegister()) {
2760     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2761     CCInfo.AllocateReg(OutgoingArg->getRegister());
2762   } else {
2763     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2764     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2765                                             SpecialArgOffset);
2766     MemOpChains.push_back(ArgStore);
2767   }
2768 }
2769 
2770 static bool canGuaranteeTCO(CallingConv::ID CC) {
2771   return CC == CallingConv::Fast;
2772 }
2773 
2774 /// Return true if we might ever do TCO for calls with this calling convention.
2775 static bool mayTailCallThisCC(CallingConv::ID CC) {
2776   switch (CC) {
2777   case CallingConv::C:
2778     return true;
2779   default:
2780     return canGuaranteeTCO(CC);
2781   }
2782 }
2783 
2784 bool SITargetLowering::isEligibleForTailCallOptimization(
2785     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2786     const SmallVectorImpl<ISD::OutputArg> &Outs,
2787     const SmallVectorImpl<SDValue> &OutVals,
2788     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2789   if (!mayTailCallThisCC(CalleeCC))
2790     return false;
2791 
2792   MachineFunction &MF = DAG.getMachineFunction();
2793   const Function &CallerF = MF.getFunction();
2794   CallingConv::ID CallerCC = CallerF.getCallingConv();
2795   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2796   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2797 
2798   // Kernels aren't callable, and don't have a live in return address so it
2799   // doesn't make sense to do a tail call with entry functions.
2800   if (!CallerPreserved)
2801     return false;
2802 
2803   bool CCMatch = CallerCC == CalleeCC;
2804 
2805   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2806     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2807       return true;
2808     return false;
2809   }
2810 
2811   // TODO: Can we handle var args?
2812   if (IsVarArg)
2813     return false;
2814 
2815   for (const Argument &Arg : CallerF.args()) {
2816     if (Arg.hasByValAttr())
2817       return false;
2818   }
2819 
2820   LLVMContext &Ctx = *DAG.getContext();
2821 
2822   // Check that the call results are passed in the same way.
2823   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2824                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2825                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2826     return false;
2827 
2828   // The callee has to preserve all registers the caller needs to preserve.
2829   if (!CCMatch) {
2830     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2831     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2832       return false;
2833   }
2834 
2835   // Nothing more to check if the callee is taking no arguments.
2836   if (Outs.empty())
2837     return true;
2838 
2839   SmallVector<CCValAssign, 16> ArgLocs;
2840   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2841 
2842   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2843 
2844   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2845   // If the stack arguments for this call do not fit into our own save area then
2846   // the call cannot be made tail.
2847   // TODO: Is this really necessary?
2848   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2849     return false;
2850 
2851   const MachineRegisterInfo &MRI = MF.getRegInfo();
2852   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2853 }
2854 
2855 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2856   if (!CI->isTailCall())
2857     return false;
2858 
2859   const Function *ParentFn = CI->getParent()->getParent();
2860   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2861     return false;
2862   return true;
2863 }
2864 
2865 // The wave scratch offset register is used as the global base pointer.
2866 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2867                                     SmallVectorImpl<SDValue> &InVals) const {
2868   SelectionDAG &DAG = CLI.DAG;
2869   const SDLoc &DL = CLI.DL;
2870   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2871   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2872   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2873   SDValue Chain = CLI.Chain;
2874   SDValue Callee = CLI.Callee;
2875   bool &IsTailCall = CLI.IsTailCall;
2876   CallingConv::ID CallConv = CLI.CallConv;
2877   bool IsVarArg = CLI.IsVarArg;
2878   bool IsSibCall = false;
2879   bool IsThisReturn = false;
2880   MachineFunction &MF = DAG.getMachineFunction();
2881 
2882   if (Callee.isUndef() || isNullConstant(Callee)) {
2883     if (!CLI.IsTailCall) {
2884       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2885         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2886     }
2887 
2888     return Chain;
2889   }
2890 
2891   if (IsVarArg) {
2892     return lowerUnhandledCall(CLI, InVals,
2893                               "unsupported call to variadic function ");
2894   }
2895 
2896   if (!CLI.CB)
2897     report_fatal_error("unsupported libcall legalization");
2898 
2899   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2900       !CLI.CB->getCalledFunction()) {
2901     return lowerUnhandledCall(CLI, InVals,
2902                               "unsupported indirect call to function ");
2903   }
2904 
2905   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2906     return lowerUnhandledCall(CLI, InVals,
2907                               "unsupported required tail call to function ");
2908   }
2909 
2910   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2911     // Note the issue is with the CC of the calling function, not of the call
2912     // itself.
2913     return lowerUnhandledCall(CLI, InVals,
2914                           "unsupported call from graphics shader of function ");
2915   }
2916 
2917   if (IsTailCall) {
2918     IsTailCall = isEligibleForTailCallOptimization(
2919       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2920     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2921       report_fatal_error("failed to perform tail call elimination on a call "
2922                          "site marked musttail");
2923     }
2924 
2925     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2926 
2927     // A sibling call is one where we're under the usual C ABI and not planning
2928     // to change that but can still do a tail call:
2929     if (!TailCallOpt && IsTailCall)
2930       IsSibCall = true;
2931 
2932     if (IsTailCall)
2933       ++NumTailCalls;
2934   }
2935 
2936   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2937   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2938   SmallVector<SDValue, 8> MemOpChains;
2939 
2940   // Analyze operands of the call, assigning locations to each operand.
2941   SmallVector<CCValAssign, 16> ArgLocs;
2942   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2943   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2944 
2945   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2946     // With a fixed ABI, allocate fixed registers before user arguments.
2947     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2948   }
2949 
2950   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2951 
2952   // Get a count of how many bytes are to be pushed on the stack.
2953   unsigned NumBytes = CCInfo.getNextStackOffset();
2954 
2955   if (IsSibCall) {
2956     // Since we're not changing the ABI to make this a tail call, the memory
2957     // operands are already available in the caller's incoming argument space.
2958     NumBytes = 0;
2959   }
2960 
2961   // FPDiff is the byte offset of the call's argument area from the callee's.
2962   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2963   // by this amount for a tail call. In a sibling call it must be 0 because the
2964   // caller will deallocate the entire stack and the callee still expects its
2965   // arguments to begin at SP+0. Completely unused for non-tail calls.
2966   int32_t FPDiff = 0;
2967   MachineFrameInfo &MFI = MF.getFrameInfo();
2968 
2969   // Adjust the stack pointer for the new arguments...
2970   // These operations are automatically eliminated by the prolog/epilog pass
2971   if (!IsSibCall) {
2972     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2973 
2974     SmallVector<SDValue, 4> CopyFromChains;
2975 
2976     // In the HSA case, this should be an identity copy.
2977     SDValue ScratchRSrcReg
2978       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2979     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2980     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2981     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2982   }
2983 
2984   MVT PtrVT = MVT::i32;
2985 
2986   // Walk the register/memloc assignments, inserting copies/loads.
2987   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2988     CCValAssign &VA = ArgLocs[i];
2989     SDValue Arg = OutVals[i];
2990 
2991     // Promote the value if needed.
2992     switch (VA.getLocInfo()) {
2993     case CCValAssign::Full:
2994       break;
2995     case CCValAssign::BCvt:
2996       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2997       break;
2998     case CCValAssign::ZExt:
2999       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3000       break;
3001     case CCValAssign::SExt:
3002       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3003       break;
3004     case CCValAssign::AExt:
3005       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3006       break;
3007     case CCValAssign::FPExt:
3008       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3009       break;
3010     default:
3011       llvm_unreachable("Unknown loc info!");
3012     }
3013 
3014     if (VA.isRegLoc()) {
3015       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3016     } else {
3017       assert(VA.isMemLoc());
3018 
3019       SDValue DstAddr;
3020       MachinePointerInfo DstInfo;
3021 
3022       unsigned LocMemOffset = VA.getLocMemOffset();
3023       int32_t Offset = LocMemOffset;
3024 
3025       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3026       MaybeAlign Alignment;
3027 
3028       if (IsTailCall) {
3029         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3030         unsigned OpSize = Flags.isByVal() ?
3031           Flags.getByValSize() : VA.getValVT().getStoreSize();
3032 
3033         // FIXME: We can have better than the minimum byval required alignment.
3034         Alignment =
3035             Flags.isByVal()
3036                 ? Flags.getNonZeroByValAlign()
3037                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3038 
3039         Offset = Offset + FPDiff;
3040         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3041 
3042         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3043         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3044 
3045         // Make sure any stack arguments overlapping with where we're storing
3046         // are loaded before this eventual operation. Otherwise they'll be
3047         // clobbered.
3048 
3049         // FIXME: Why is this really necessary? This seems to just result in a
3050         // lot of code to copy the stack and write them back to the same
3051         // locations, which are supposed to be immutable?
3052         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3053       } else {
3054         DstAddr = PtrOff;
3055         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3056         Alignment =
3057             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3058       }
3059 
3060       if (Outs[i].Flags.isByVal()) {
3061         SDValue SizeNode =
3062             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3063         SDValue Cpy =
3064             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3065                           Outs[i].Flags.getNonZeroByValAlign(),
3066                           /*isVol = */ false, /*AlwaysInline = */ true,
3067                           /*isTailCall = */ false, DstInfo,
3068                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3069 
3070         MemOpChains.push_back(Cpy);
3071       } else {
3072         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
3073                                      Alignment ? Alignment->value() : 0);
3074         MemOpChains.push_back(Store);
3075       }
3076     }
3077   }
3078 
3079   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
3080     // Copy special input registers after user input arguments.
3081     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3082   }
3083 
3084   if (!MemOpChains.empty())
3085     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3086 
3087   // Build a sequence of copy-to-reg nodes chained together with token chain
3088   // and flag operands which copy the outgoing args into the appropriate regs.
3089   SDValue InFlag;
3090   for (auto &RegToPass : RegsToPass) {
3091     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3092                              RegToPass.second, InFlag);
3093     InFlag = Chain.getValue(1);
3094   }
3095 
3096 
3097   SDValue PhysReturnAddrReg;
3098   if (IsTailCall) {
3099     // Since the return is being combined with the call, we need to pass on the
3100     // return address.
3101 
3102     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3103     SDValue ReturnAddrReg = CreateLiveInRegister(
3104       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3105 
3106     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3107                                         MVT::i64);
3108     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3109     InFlag = Chain.getValue(1);
3110   }
3111 
3112   // We don't usually want to end the call-sequence here because we would tidy
3113   // the frame up *after* the call, however in the ABI-changing tail-call case
3114   // we've carefully laid out the parameters so that when sp is reset they'll be
3115   // in the correct location.
3116   if (IsTailCall && !IsSibCall) {
3117     Chain = DAG.getCALLSEQ_END(Chain,
3118                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3119                                DAG.getTargetConstant(0, DL, MVT::i32),
3120                                InFlag, DL);
3121     InFlag = Chain.getValue(1);
3122   }
3123 
3124   std::vector<SDValue> Ops;
3125   Ops.push_back(Chain);
3126   Ops.push_back(Callee);
3127   // Add a redundant copy of the callee global which will not be legalized, as
3128   // we need direct access to the callee later.
3129   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3130     const GlobalValue *GV = GSD->getGlobal();
3131     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3132   } else {
3133     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3134   }
3135 
3136   if (IsTailCall) {
3137     // Each tail call may have to adjust the stack by a different amount, so
3138     // this information must travel along with the operation for eventual
3139     // consumption by emitEpilogue.
3140     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3141 
3142     Ops.push_back(PhysReturnAddrReg);
3143   }
3144 
3145   // Add argument registers to the end of the list so that they are known live
3146   // into the call.
3147   for (auto &RegToPass : RegsToPass) {
3148     Ops.push_back(DAG.getRegister(RegToPass.first,
3149                                   RegToPass.second.getValueType()));
3150   }
3151 
3152   // Add a register mask operand representing the call-preserved registers.
3153 
3154   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3155   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3156   assert(Mask && "Missing call preserved mask for calling convention");
3157   Ops.push_back(DAG.getRegisterMask(Mask));
3158 
3159   if (InFlag.getNode())
3160     Ops.push_back(InFlag);
3161 
3162   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3163 
3164   // If we're doing a tall call, use a TC_RETURN here rather than an
3165   // actual call instruction.
3166   if (IsTailCall) {
3167     MFI.setHasTailCall();
3168     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3169   }
3170 
3171   // Returns a chain and a flag for retval copy to use.
3172   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3173   Chain = Call.getValue(0);
3174   InFlag = Call.getValue(1);
3175 
3176   uint64_t CalleePopBytes = NumBytes;
3177   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3178                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3179                              InFlag, DL);
3180   if (!Ins.empty())
3181     InFlag = Chain.getValue(1);
3182 
3183   // Handle result values, copying them out of physregs into vregs that we
3184   // return.
3185   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3186                          InVals, IsThisReturn,
3187                          IsThisReturn ? OutVals[0] : SDValue());
3188 }
3189 
3190 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3191 // except for applying the wave size scale to the increment amount.
3192 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3193     SDValue Op, SelectionDAG &DAG) const {
3194   const MachineFunction &MF = DAG.getMachineFunction();
3195   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3196 
3197   SDLoc dl(Op);
3198   EVT VT = Op.getValueType();
3199   SDValue Tmp1 = Op;
3200   SDValue Tmp2 = Op.getValue(1);
3201   SDValue Tmp3 = Op.getOperand(2);
3202   SDValue Chain = Tmp1.getOperand(0);
3203 
3204   Register SPReg = Info->getStackPtrOffsetReg();
3205 
3206   // Chain the dynamic stack allocation so that it doesn't modify the stack
3207   // pointer when other instructions are using the stack.
3208   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3209 
3210   SDValue Size  = Tmp2.getOperand(1);
3211   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3212   Chain = SP.getValue(1);
3213   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3214   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3215   const TargetFrameLowering *TFL = ST.getFrameLowering();
3216   unsigned Opc =
3217     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3218     ISD::ADD : ISD::SUB;
3219 
3220   SDValue ScaledSize = DAG.getNode(
3221       ISD::SHL, dl, VT, Size,
3222       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3223 
3224   Align StackAlign = TFL->getStackAlign();
3225   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3226   if (Alignment && *Alignment > StackAlign) {
3227     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3228                        DAG.getConstant(-(uint64_t)Alignment->value()
3229                                            << ST.getWavefrontSizeLog2(),
3230                                        dl, VT));
3231   }
3232 
3233   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3234   Tmp2 = DAG.getCALLSEQ_END(
3235       Chain, DAG.getIntPtrConstant(0, dl, true),
3236       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3237 
3238   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3239 }
3240 
3241 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3242                                                   SelectionDAG &DAG) const {
3243   // We only handle constant sizes here to allow non-entry block, static sized
3244   // allocas. A truly dynamic value is more difficult to support because we
3245   // don't know if the size value is uniform or not. If the size isn't uniform,
3246   // we would need to do a wave reduction to get the maximum size to know how
3247   // much to increment the uniform stack pointer.
3248   SDValue Size = Op.getOperand(1);
3249   if (isa<ConstantSDNode>(Size))
3250       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3251 
3252   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3253 }
3254 
3255 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3256                                              const MachineFunction &MF) const {
3257   Register Reg = StringSwitch<Register>(RegName)
3258     .Case("m0", AMDGPU::M0)
3259     .Case("exec", AMDGPU::EXEC)
3260     .Case("exec_lo", AMDGPU::EXEC_LO)
3261     .Case("exec_hi", AMDGPU::EXEC_HI)
3262     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3263     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3264     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3265     .Default(Register());
3266 
3267   if (Reg == AMDGPU::NoRegister) {
3268     report_fatal_error(Twine("invalid register name \""
3269                              + StringRef(RegName)  + "\"."));
3270 
3271   }
3272 
3273   if (!Subtarget->hasFlatScrRegister() &&
3274        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3275     report_fatal_error(Twine("invalid register \""
3276                              + StringRef(RegName)  + "\" for subtarget."));
3277   }
3278 
3279   switch (Reg) {
3280   case AMDGPU::M0:
3281   case AMDGPU::EXEC_LO:
3282   case AMDGPU::EXEC_HI:
3283   case AMDGPU::FLAT_SCR_LO:
3284   case AMDGPU::FLAT_SCR_HI:
3285     if (VT.getSizeInBits() == 32)
3286       return Reg;
3287     break;
3288   case AMDGPU::EXEC:
3289   case AMDGPU::FLAT_SCR:
3290     if (VT.getSizeInBits() == 64)
3291       return Reg;
3292     break;
3293   default:
3294     llvm_unreachable("missing register type checking");
3295   }
3296 
3297   report_fatal_error(Twine("invalid type for register \""
3298                            + StringRef(RegName) + "\"."));
3299 }
3300 
3301 // If kill is not the last instruction, split the block so kill is always a
3302 // proper terminator.
3303 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3304                                                     MachineBasicBlock *BB) const {
3305   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3306 
3307   MachineBasicBlock::iterator SplitPoint(&MI);
3308   ++SplitPoint;
3309 
3310   if (SplitPoint == BB->end()) {
3311     // Don't bother with a new block.
3312     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3313     return BB;
3314   }
3315 
3316   MachineFunction *MF = BB->getParent();
3317   MachineBasicBlock *SplitBB
3318     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3319 
3320   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3321   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3322 
3323   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3324   BB->addSuccessor(SplitBB);
3325 
3326   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3327   return SplitBB;
3328 }
3329 
3330 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3331 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3332 // be the first instruction in the remainder block.
3333 //
3334 /// \returns { LoopBody, Remainder }
3335 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3336 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3337   MachineFunction *MF = MBB.getParent();
3338   MachineBasicBlock::iterator I(&MI);
3339 
3340   // To insert the loop we need to split the block. Move everything after this
3341   // point to a new block, and insert a new empty block between the two.
3342   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3343   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3344   MachineFunction::iterator MBBI(MBB);
3345   ++MBBI;
3346 
3347   MF->insert(MBBI, LoopBB);
3348   MF->insert(MBBI, RemainderBB);
3349 
3350   LoopBB->addSuccessor(LoopBB);
3351   LoopBB->addSuccessor(RemainderBB);
3352 
3353   // Move the rest of the block into a new block.
3354   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3355 
3356   if (InstInLoop) {
3357     auto Next = std::next(I);
3358 
3359     // Move instruction to loop body.
3360     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3361 
3362     // Move the rest of the block.
3363     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3364   } else {
3365     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3366   }
3367 
3368   MBB.addSuccessor(LoopBB);
3369 
3370   return std::make_pair(LoopBB, RemainderBB);
3371 }
3372 
3373 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3374 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3375   MachineBasicBlock *MBB = MI.getParent();
3376   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3377   auto I = MI.getIterator();
3378   auto E = std::next(I);
3379 
3380   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3381     .addImm(0);
3382 
3383   MIBundleBuilder Bundler(*MBB, I, E);
3384   finalizeBundle(*MBB, Bundler.begin());
3385 }
3386 
3387 MachineBasicBlock *
3388 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3389                                          MachineBasicBlock *BB) const {
3390   const DebugLoc &DL = MI.getDebugLoc();
3391 
3392   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3393 
3394   MachineBasicBlock *LoopBB;
3395   MachineBasicBlock *RemainderBB;
3396   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3397 
3398   // Apparently kill flags are only valid if the def is in the same block?
3399   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3400     Src->setIsKill(false);
3401 
3402   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3403 
3404   MachineBasicBlock::iterator I = LoopBB->end();
3405 
3406   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3407     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3408 
3409   // Clear TRAP_STS.MEM_VIOL
3410   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3411     .addImm(0)
3412     .addImm(EncodedReg);
3413 
3414   bundleInstWithWaitcnt(MI);
3415 
3416   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3417 
3418   // Load and check TRAP_STS.MEM_VIOL
3419   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3420     .addImm(EncodedReg);
3421 
3422   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3423   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3424     .addReg(Reg, RegState::Kill)
3425     .addImm(0);
3426   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3427     .addMBB(LoopBB);
3428 
3429   return RemainderBB;
3430 }
3431 
3432 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3433 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3434 // will only do one iteration. In the worst case, this will loop 64 times.
3435 //
3436 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3437 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3438   const SIInstrInfo *TII,
3439   MachineRegisterInfo &MRI,
3440   MachineBasicBlock &OrigBB,
3441   MachineBasicBlock &LoopBB,
3442   const DebugLoc &DL,
3443   const MachineOperand &IdxReg,
3444   unsigned InitReg,
3445   unsigned ResultReg,
3446   unsigned PhiReg,
3447   unsigned InitSaveExecReg,
3448   int Offset,
3449   bool UseGPRIdxMode,
3450   bool IsIndirectSrc) {
3451   MachineFunction *MF = OrigBB.getParent();
3452   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3453   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3454   MachineBasicBlock::iterator I = LoopBB.begin();
3455 
3456   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3457   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3458   Register NewExec = MRI.createVirtualRegister(BoolRC);
3459   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3460   Register CondReg = MRI.createVirtualRegister(BoolRC);
3461 
3462   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3463     .addReg(InitReg)
3464     .addMBB(&OrigBB)
3465     .addReg(ResultReg)
3466     .addMBB(&LoopBB);
3467 
3468   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3469     .addReg(InitSaveExecReg)
3470     .addMBB(&OrigBB)
3471     .addReg(NewExec)
3472     .addMBB(&LoopBB);
3473 
3474   // Read the next variant <- also loop target.
3475   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3476     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3477 
3478   // Compare the just read M0 value to all possible Idx values.
3479   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3480     .addReg(CurrentIdxReg)
3481     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3482 
3483   // Update EXEC, save the original EXEC value to VCC.
3484   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3485                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3486           NewExec)
3487     .addReg(CondReg, RegState::Kill);
3488 
3489   MRI.setSimpleHint(NewExec, CondReg);
3490 
3491   if (UseGPRIdxMode) {
3492     unsigned IdxReg;
3493     if (Offset == 0) {
3494       IdxReg = CurrentIdxReg;
3495     } else {
3496       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3497       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3498         .addReg(CurrentIdxReg, RegState::Kill)
3499         .addImm(Offset);
3500     }
3501     unsigned IdxMode = IsIndirectSrc ?
3502       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3503     MachineInstr *SetOn =
3504       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3505       .addReg(IdxReg, RegState::Kill)
3506       .addImm(IdxMode);
3507     SetOn->getOperand(3).setIsUndef();
3508   } else {
3509     // Move index from VCC into M0
3510     if (Offset == 0) {
3511       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3512         .addReg(CurrentIdxReg, RegState::Kill);
3513     } else {
3514       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3515         .addReg(CurrentIdxReg, RegState::Kill)
3516         .addImm(Offset);
3517     }
3518   }
3519 
3520   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3521   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3522   MachineInstr *InsertPt =
3523     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3524                                                   : AMDGPU::S_XOR_B64_term), Exec)
3525       .addReg(Exec)
3526       .addReg(NewExec);
3527 
3528   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3529   // s_cbranch_scc0?
3530 
3531   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3532   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3533     .addMBB(&LoopBB);
3534 
3535   return InsertPt->getIterator();
3536 }
3537 
3538 // This has slightly sub-optimal regalloc when the source vector is killed by
3539 // the read. The register allocator does not understand that the kill is
3540 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3541 // subregister from it, using 1 more VGPR than necessary. This was saved when
3542 // this was expanded after register allocation.
3543 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3544                                                   MachineBasicBlock &MBB,
3545                                                   MachineInstr &MI,
3546                                                   unsigned InitResultReg,
3547                                                   unsigned PhiReg,
3548                                                   int Offset,
3549                                                   bool UseGPRIdxMode,
3550                                                   bool IsIndirectSrc) {
3551   MachineFunction *MF = MBB.getParent();
3552   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3553   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3554   MachineRegisterInfo &MRI = MF->getRegInfo();
3555   const DebugLoc &DL = MI.getDebugLoc();
3556   MachineBasicBlock::iterator I(&MI);
3557 
3558   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3559   Register DstReg = MI.getOperand(0).getReg();
3560   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3561   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3562   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3563   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3564 
3565   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3566 
3567   // Save the EXEC mask
3568   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3569     .addReg(Exec);
3570 
3571   MachineBasicBlock *LoopBB;
3572   MachineBasicBlock *RemainderBB;
3573   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3574 
3575   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3576 
3577   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3578                                       InitResultReg, DstReg, PhiReg, TmpExec,
3579                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3580   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3581   MachineFunction::iterator MBBI(LoopBB);
3582   ++MBBI;
3583   MF->insert(MBBI, LandingPad);
3584   LoopBB->removeSuccessor(RemainderBB);
3585   LandingPad->addSuccessor(RemainderBB);
3586   LoopBB->addSuccessor(LandingPad);
3587   MachineBasicBlock::iterator First = LandingPad->begin();
3588   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3589     .addReg(SaveExec);
3590 
3591   return InsPt;
3592 }
3593 
3594 // Returns subreg index, offset
3595 static std::pair<unsigned, int>
3596 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3597                             const TargetRegisterClass *SuperRC,
3598                             unsigned VecReg,
3599                             int Offset) {
3600   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3601 
3602   // Skip out of bounds offsets, or else we would end up using an undefined
3603   // register.
3604   if (Offset >= NumElts || Offset < 0)
3605     return std::make_pair(AMDGPU::sub0, Offset);
3606 
3607   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3608 }
3609 
3610 // Return true if the index is an SGPR and was set.
3611 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3612                                  MachineRegisterInfo &MRI,
3613                                  MachineInstr &MI,
3614                                  int Offset,
3615                                  bool UseGPRIdxMode,
3616                                  bool IsIndirectSrc) {
3617   MachineBasicBlock *MBB = MI.getParent();
3618   const DebugLoc &DL = MI.getDebugLoc();
3619   MachineBasicBlock::iterator I(&MI);
3620 
3621   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3622   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3623 
3624   assert(Idx->getReg() != AMDGPU::NoRegister);
3625 
3626   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3627     return false;
3628 
3629   if (UseGPRIdxMode) {
3630     unsigned IdxMode = IsIndirectSrc ?
3631       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3632     if (Offset == 0) {
3633       MachineInstr *SetOn =
3634           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3635               .add(*Idx)
3636               .addImm(IdxMode);
3637 
3638       SetOn->getOperand(3).setIsUndef();
3639     } else {
3640       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3641       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3642           .add(*Idx)
3643           .addImm(Offset);
3644       MachineInstr *SetOn =
3645         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3646         .addReg(Tmp, RegState::Kill)
3647         .addImm(IdxMode);
3648 
3649       SetOn->getOperand(3).setIsUndef();
3650     }
3651 
3652     return true;
3653   }
3654 
3655   if (Offset == 0) {
3656     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3657       .add(*Idx);
3658   } else {
3659     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3660       .add(*Idx)
3661       .addImm(Offset);
3662   }
3663 
3664   return true;
3665 }
3666 
3667 // Control flow needs to be inserted if indexing with a VGPR.
3668 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3669                                           MachineBasicBlock &MBB,
3670                                           const GCNSubtarget &ST) {
3671   const SIInstrInfo *TII = ST.getInstrInfo();
3672   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3673   MachineFunction *MF = MBB.getParent();
3674   MachineRegisterInfo &MRI = MF->getRegInfo();
3675 
3676   Register Dst = MI.getOperand(0).getReg();
3677   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3678   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3679 
3680   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3681 
3682   unsigned SubReg;
3683   std::tie(SubReg, Offset)
3684     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3685 
3686   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3687 
3688   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3689     MachineBasicBlock::iterator I(&MI);
3690     const DebugLoc &DL = MI.getDebugLoc();
3691 
3692     if (UseGPRIdxMode) {
3693       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3694       // to avoid interfering with other uses, so probably requires a new
3695       // optimization pass.
3696       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3697         .addReg(SrcReg, 0, SubReg)
3698         .addReg(SrcReg, RegState::Implicit)
3699         .addReg(AMDGPU::M0, RegState::Implicit);
3700       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3701     } else {
3702       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3703         .addReg(SrcReg, 0, SubReg)
3704         .addReg(SrcReg, RegState::Implicit);
3705     }
3706 
3707     MI.eraseFromParent();
3708 
3709     return &MBB;
3710   }
3711 
3712   const DebugLoc &DL = MI.getDebugLoc();
3713   MachineBasicBlock::iterator I(&MI);
3714 
3715   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3716   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3717 
3718   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3719 
3720   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3721                               Offset, UseGPRIdxMode, true);
3722   MachineBasicBlock *LoopBB = InsPt->getParent();
3723 
3724   if (UseGPRIdxMode) {
3725     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3726       .addReg(SrcReg, 0, SubReg)
3727       .addReg(SrcReg, RegState::Implicit)
3728       .addReg(AMDGPU::M0, RegState::Implicit);
3729     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3730   } else {
3731     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3732       .addReg(SrcReg, 0, SubReg)
3733       .addReg(SrcReg, RegState::Implicit);
3734   }
3735 
3736   MI.eraseFromParent();
3737 
3738   return LoopBB;
3739 }
3740 
3741 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3742                                           MachineBasicBlock &MBB,
3743                                           const GCNSubtarget &ST) {
3744   const SIInstrInfo *TII = ST.getInstrInfo();
3745   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3746   MachineFunction *MF = MBB.getParent();
3747   MachineRegisterInfo &MRI = MF->getRegInfo();
3748 
3749   Register Dst = MI.getOperand(0).getReg();
3750   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3751   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3752   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3753   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3754   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3755 
3756   // This can be an immediate, but will be folded later.
3757   assert(Val->getReg());
3758 
3759   unsigned SubReg;
3760   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3761                                                          SrcVec->getReg(),
3762                                                          Offset);
3763   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3764 
3765   if (Idx->getReg() == AMDGPU::NoRegister) {
3766     MachineBasicBlock::iterator I(&MI);
3767     const DebugLoc &DL = MI.getDebugLoc();
3768 
3769     assert(Offset == 0);
3770 
3771     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3772         .add(*SrcVec)
3773         .add(*Val)
3774         .addImm(SubReg);
3775 
3776     MI.eraseFromParent();
3777     return &MBB;
3778   }
3779 
3780   const MCInstrDesc &MovRelDesc
3781     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3782 
3783   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3784     MachineBasicBlock::iterator I(&MI);
3785     const DebugLoc &DL = MI.getDebugLoc();
3786     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3787       .addReg(SrcVec->getReg())
3788       .add(*Val)
3789       .addImm(SubReg);
3790     if (UseGPRIdxMode)
3791       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3792 
3793     MI.eraseFromParent();
3794     return &MBB;
3795   }
3796 
3797   if (Val->isReg())
3798     MRI.clearKillFlags(Val->getReg());
3799 
3800   const DebugLoc &DL = MI.getDebugLoc();
3801 
3802   Register PhiReg = MRI.createVirtualRegister(VecRC);
3803 
3804   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3805                               Offset, UseGPRIdxMode, false);
3806   MachineBasicBlock *LoopBB = InsPt->getParent();
3807 
3808   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3809     .addReg(PhiReg)
3810     .add(*Val)
3811     .addImm(AMDGPU::sub0);
3812   if (UseGPRIdxMode)
3813     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3814 
3815   MI.eraseFromParent();
3816   return LoopBB;
3817 }
3818 
3819 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3820   MachineInstr &MI, MachineBasicBlock *BB) const {
3821 
3822   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3823   MachineFunction *MF = BB->getParent();
3824   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3825 
3826   switch (MI.getOpcode()) {
3827   case AMDGPU::S_UADDO_PSEUDO:
3828   case AMDGPU::S_USUBO_PSEUDO: {
3829     const DebugLoc &DL = MI.getDebugLoc();
3830     MachineOperand &Dest0 = MI.getOperand(0);
3831     MachineOperand &Dest1 = MI.getOperand(1);
3832     MachineOperand &Src0 = MI.getOperand(2);
3833     MachineOperand &Src1 = MI.getOperand(3);
3834 
3835     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3836                        ? AMDGPU::S_ADD_I32
3837                        : AMDGPU::S_SUB_I32;
3838     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3839 
3840     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3841         .addImm(1)
3842         .addImm(0);
3843 
3844     MI.eraseFromParent();
3845     return BB;
3846   }
3847   case AMDGPU::S_ADD_U64_PSEUDO:
3848   case AMDGPU::S_SUB_U64_PSEUDO: {
3849     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3850     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3851     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3852     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3853     const DebugLoc &DL = MI.getDebugLoc();
3854 
3855     MachineOperand &Dest = MI.getOperand(0);
3856     MachineOperand &Src0 = MI.getOperand(1);
3857     MachineOperand &Src1 = MI.getOperand(2);
3858 
3859     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3860     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3861 
3862     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3863         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3864     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3865         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3866 
3867     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3868         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3869     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3870         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3871 
3872     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3873 
3874     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3875     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3876     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3877     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3878     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3879         .addReg(DestSub0)
3880         .addImm(AMDGPU::sub0)
3881         .addReg(DestSub1)
3882         .addImm(AMDGPU::sub1);
3883     MI.eraseFromParent();
3884     return BB;
3885   }
3886   case AMDGPU::V_ADD_U64_PSEUDO:
3887   case AMDGPU::V_SUB_U64_PSEUDO: {
3888     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3889     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3890     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3891     const DebugLoc &DL = MI.getDebugLoc();
3892 
3893     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3894 
3895     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3896 
3897     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3898     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3899 
3900     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3901     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3902 
3903     MachineOperand &Dest = MI.getOperand(0);
3904     MachineOperand &Src0 = MI.getOperand(1);
3905     MachineOperand &Src1 = MI.getOperand(2);
3906 
3907     const TargetRegisterClass *Src0RC = Src0.isReg()
3908                                             ? MRI.getRegClass(Src0.getReg())
3909                                             : &AMDGPU::VReg_64RegClass;
3910     const TargetRegisterClass *Src1RC = Src1.isReg()
3911                                             ? MRI.getRegClass(Src1.getReg())
3912                                             : &AMDGPU::VReg_64RegClass;
3913 
3914     const TargetRegisterClass *Src0SubRC =
3915         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3916     const TargetRegisterClass *Src1SubRC =
3917         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3918 
3919     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3920         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3921     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3922         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3923 
3924     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3925         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3926     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3927         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3928 
3929     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3930     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3931                                .addReg(CarryReg, RegState::Define)
3932                                .add(SrcReg0Sub0)
3933                                .add(SrcReg1Sub0)
3934                                .addImm(0); // clamp bit
3935 
3936     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3937     MachineInstr *HiHalf =
3938         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3939             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3940             .add(SrcReg0Sub1)
3941             .add(SrcReg1Sub1)
3942             .addReg(CarryReg, RegState::Kill)
3943             .addImm(0); // clamp bit
3944 
3945     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3946         .addReg(DestSub0)
3947         .addImm(AMDGPU::sub0)
3948         .addReg(DestSub1)
3949         .addImm(AMDGPU::sub1);
3950     TII->legalizeOperands(*LoHalf);
3951     TII->legalizeOperands(*HiHalf);
3952     MI.eraseFromParent();
3953     return BB;
3954   }
3955   case AMDGPU::S_ADD_CO_PSEUDO:
3956   case AMDGPU::S_SUB_CO_PSEUDO: {
3957     // This pseudo has a chance to be selected
3958     // only from uniform add/subcarry node. All the VGPR operands
3959     // therefore assumed to be splat vectors.
3960     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3961     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3962     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3963     MachineBasicBlock::iterator MII = MI;
3964     const DebugLoc &DL = MI.getDebugLoc();
3965     MachineOperand &Dest = MI.getOperand(0);
3966     MachineOperand &CarryDest = MI.getOperand(1);
3967     MachineOperand &Src0 = MI.getOperand(2);
3968     MachineOperand &Src1 = MI.getOperand(3);
3969     MachineOperand &Src2 = MI.getOperand(4);
3970     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3971                        ? AMDGPU::S_ADDC_U32
3972                        : AMDGPU::S_SUBB_U32;
3973     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3974       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3975       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3976           .addReg(Src0.getReg());
3977       Src0.setReg(RegOp0);
3978     }
3979     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3980       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3981       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3982           .addReg(Src1.getReg());
3983       Src1.setReg(RegOp1);
3984     }
3985     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3986     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3987       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3988           .addReg(Src2.getReg());
3989       Src2.setReg(RegOp2);
3990     }
3991 
3992     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3993       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3994           .addReg(Src2.getReg())
3995           .addImm(0);
3996     } else {
3997       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3998           .addReg(Src2.getReg())
3999           .addImm(0);
4000     }
4001 
4002     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4003 
4004     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4005       .addReg(AMDGPU::SCC);
4006     MI.eraseFromParent();
4007     return BB;
4008   }
4009   case AMDGPU::SI_INIT_M0: {
4010     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4011             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4012         .add(MI.getOperand(0));
4013     MI.eraseFromParent();
4014     return BB;
4015   }
4016   case AMDGPU::SI_INIT_EXEC:
4017     // This should be before all vector instructions.
4018     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
4019             AMDGPU::EXEC)
4020         .addImm(MI.getOperand(0).getImm());
4021     MI.eraseFromParent();
4022     return BB;
4023 
4024   case AMDGPU::SI_INIT_EXEC_LO:
4025     // This should be before all vector instructions.
4026     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
4027             AMDGPU::EXEC_LO)
4028         .addImm(MI.getOperand(0).getImm());
4029     MI.eraseFromParent();
4030     return BB;
4031 
4032   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
4033     // Extract the thread count from an SGPR input and set EXEC accordingly.
4034     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
4035     //
4036     // S_BFE_U32 count, input, {shift, 7}
4037     // S_BFM_B64 exec, count, 0
4038     // S_CMP_EQ_U32 count, 64
4039     // S_CMOV_B64 exec, -1
4040     MachineInstr *FirstMI = &*BB->begin();
4041     MachineRegisterInfo &MRI = MF->getRegInfo();
4042     Register InputReg = MI.getOperand(0).getReg();
4043     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4044     bool Found = false;
4045 
4046     // Move the COPY of the input reg to the beginning, so that we can use it.
4047     for (auto I = BB->begin(); I != &MI; I++) {
4048       if (I->getOpcode() != TargetOpcode::COPY ||
4049           I->getOperand(0).getReg() != InputReg)
4050         continue;
4051 
4052       if (I == FirstMI) {
4053         FirstMI = &*++BB->begin();
4054       } else {
4055         I->removeFromParent();
4056         BB->insert(FirstMI, &*I);
4057       }
4058       Found = true;
4059       break;
4060     }
4061     assert(Found);
4062     (void)Found;
4063 
4064     // This should be before all vector instructions.
4065     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4066     bool isWave32 = getSubtarget()->isWave32();
4067     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4068     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4069         .addReg(InputReg)
4070         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4071     BuildMI(*BB, FirstMI, DebugLoc(),
4072             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4073             Exec)
4074         .addReg(CountReg)
4075         .addImm(0);
4076     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4077         .addReg(CountReg, RegState::Kill)
4078         .addImm(getSubtarget()->getWavefrontSize());
4079     BuildMI(*BB, FirstMI, DebugLoc(),
4080             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4081             Exec)
4082         .addImm(-1);
4083     MI.eraseFromParent();
4084     return BB;
4085   }
4086 
4087   case AMDGPU::GET_GROUPSTATICSIZE: {
4088     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4089            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4090     DebugLoc DL = MI.getDebugLoc();
4091     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4092         .add(MI.getOperand(0))
4093         .addImm(MFI->getLDSSize());
4094     MI.eraseFromParent();
4095     return BB;
4096   }
4097   case AMDGPU::SI_INDIRECT_SRC_V1:
4098   case AMDGPU::SI_INDIRECT_SRC_V2:
4099   case AMDGPU::SI_INDIRECT_SRC_V4:
4100   case AMDGPU::SI_INDIRECT_SRC_V8:
4101   case AMDGPU::SI_INDIRECT_SRC_V16:
4102   case AMDGPU::SI_INDIRECT_SRC_V32:
4103     return emitIndirectSrc(MI, *BB, *getSubtarget());
4104   case AMDGPU::SI_INDIRECT_DST_V1:
4105   case AMDGPU::SI_INDIRECT_DST_V2:
4106   case AMDGPU::SI_INDIRECT_DST_V4:
4107   case AMDGPU::SI_INDIRECT_DST_V8:
4108   case AMDGPU::SI_INDIRECT_DST_V16:
4109   case AMDGPU::SI_INDIRECT_DST_V32:
4110     return emitIndirectDst(MI, *BB, *getSubtarget());
4111   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4112   case AMDGPU::SI_KILL_I1_PSEUDO:
4113     return splitKillBlock(MI, BB);
4114   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4115     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4116     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4117     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4118 
4119     Register Dst = MI.getOperand(0).getReg();
4120     Register Src0 = MI.getOperand(1).getReg();
4121     Register Src1 = MI.getOperand(2).getReg();
4122     const DebugLoc &DL = MI.getDebugLoc();
4123     Register SrcCond = MI.getOperand(3).getReg();
4124 
4125     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4126     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4127     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4128     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4129 
4130     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4131       .addReg(SrcCond);
4132     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4133       .addImm(0)
4134       .addReg(Src0, 0, AMDGPU::sub0)
4135       .addImm(0)
4136       .addReg(Src1, 0, AMDGPU::sub0)
4137       .addReg(SrcCondCopy);
4138     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4139       .addImm(0)
4140       .addReg(Src0, 0, AMDGPU::sub1)
4141       .addImm(0)
4142       .addReg(Src1, 0, AMDGPU::sub1)
4143       .addReg(SrcCondCopy);
4144 
4145     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4146       .addReg(DstLo)
4147       .addImm(AMDGPU::sub0)
4148       .addReg(DstHi)
4149       .addImm(AMDGPU::sub1);
4150     MI.eraseFromParent();
4151     return BB;
4152   }
4153   case AMDGPU::SI_BR_UNDEF: {
4154     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4155     const DebugLoc &DL = MI.getDebugLoc();
4156     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4157                            .add(MI.getOperand(0));
4158     Br->getOperand(1).setIsUndef(true); // read undef SCC
4159     MI.eraseFromParent();
4160     return BB;
4161   }
4162   case AMDGPU::ADJCALLSTACKUP:
4163   case AMDGPU::ADJCALLSTACKDOWN: {
4164     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4165     MachineInstrBuilder MIB(*MF, &MI);
4166 
4167     // Add an implicit use of the frame offset reg to prevent the restore copy
4168     // inserted after the call from being reorderd after stack operations in the
4169     // the caller's frame.
4170     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4171         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4172         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4173     return BB;
4174   }
4175   case AMDGPU::SI_CALL_ISEL: {
4176     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4177     const DebugLoc &DL = MI.getDebugLoc();
4178 
4179     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4180 
4181     MachineInstrBuilder MIB;
4182     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4183 
4184     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4185       MIB.add(MI.getOperand(I));
4186 
4187     MIB.cloneMemRefs(MI);
4188     MI.eraseFromParent();
4189     return BB;
4190   }
4191   case AMDGPU::V_ADD_CO_U32_e32:
4192   case AMDGPU::V_SUB_CO_U32_e32:
4193   case AMDGPU::V_SUBREV_CO_U32_e32: {
4194     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4195     const DebugLoc &DL = MI.getDebugLoc();
4196     unsigned Opc = MI.getOpcode();
4197 
4198     bool NeedClampOperand = false;
4199     if (TII->pseudoToMCOpcode(Opc) == -1) {
4200       Opc = AMDGPU::getVOPe64(Opc);
4201       NeedClampOperand = true;
4202     }
4203 
4204     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4205     if (TII->isVOP3(*I)) {
4206       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4207       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4208       I.addReg(TRI->getVCC(), RegState::Define);
4209     }
4210     I.add(MI.getOperand(1))
4211      .add(MI.getOperand(2));
4212     if (NeedClampOperand)
4213       I.addImm(0); // clamp bit for e64 encoding
4214 
4215     TII->legalizeOperands(*I);
4216 
4217     MI.eraseFromParent();
4218     return BB;
4219   }
4220   case AMDGPU::DS_GWS_INIT:
4221   case AMDGPU::DS_GWS_SEMA_V:
4222   case AMDGPU::DS_GWS_SEMA_BR:
4223   case AMDGPU::DS_GWS_SEMA_P:
4224   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4225   case AMDGPU::DS_GWS_BARRIER:
4226     // A s_waitcnt 0 is required to be the instruction immediately following.
4227     if (getSubtarget()->hasGWSAutoReplay()) {
4228       bundleInstWithWaitcnt(MI);
4229       return BB;
4230     }
4231 
4232     return emitGWSMemViolTestLoop(MI, BB);
4233   case AMDGPU::S_SETREG_B32: {
4234     if (!getSubtarget()->hasDenormModeInst())
4235       return BB;
4236 
4237     // Try to optimize cases that only set the denormal mode or rounding mode.
4238     //
4239     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4240     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4241     // instead.
4242     //
4243     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4244     // allow you to have a no side effect instruction in the output of a
4245     // sideeffecting pattern.
4246 
4247     // TODO: Should also emit a no side effects pseudo if only FP bits are
4248     // touched, even if not all of them or to a variable.
4249     unsigned ID, Offset, Width;
4250     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4251     if (ID != AMDGPU::Hwreg::ID_MODE)
4252       return BB;
4253 
4254     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4255     const unsigned SetMask = WidthMask << Offset;
4256     unsigned SetDenormOp = 0;
4257     unsigned SetRoundOp = 0;
4258 
4259     // The dedicated instructions can only set the whole denorm or round mode at
4260     // once, not a subset of bits in either.
4261     if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4262                                   AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) {
4263       // If this fully sets both the round and denorm mode, emit the two
4264       // dedicated instructions for these.
4265       assert(Offset == 0);
4266       SetRoundOp = AMDGPU::S_ROUND_MODE;
4267       SetDenormOp = AMDGPU::S_DENORM_MODE;
4268     } else if (Width == 4) {
4269       if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) {
4270         SetRoundOp = AMDGPU::S_ROUND_MODE;
4271         assert(Offset == 0);
4272       } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) {
4273         SetDenormOp = AMDGPU::S_DENORM_MODE;
4274         assert(Offset == 4);
4275       }
4276     }
4277 
4278     if (SetRoundOp || SetDenormOp) {
4279       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4280       MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4281       if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4282         unsigned ImmVal = Def->getOperand(1).getImm();
4283         if (SetRoundOp) {
4284           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4285             .addImm(ImmVal & 0xf);
4286 
4287           // If we also have the denorm mode, get just the denorm mode bits.
4288           ImmVal >>= 4;
4289         }
4290 
4291         if (SetDenormOp) {
4292           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4293             .addImm(ImmVal & 0xf);
4294         }
4295 
4296         MI.eraseFromParent();
4297       }
4298     }
4299 
4300     return BB;
4301   }
4302   default:
4303     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4304   }
4305 }
4306 
4307 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4308   return isTypeLegal(VT.getScalarType());
4309 }
4310 
4311 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4312   // This currently forces unfolding various combinations of fsub into fma with
4313   // free fneg'd operands. As long as we have fast FMA (controlled by
4314   // isFMAFasterThanFMulAndFAdd), we should perform these.
4315 
4316   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4317   // most of these combines appear to be cycle neutral but save on instruction
4318   // count / code size.
4319   return true;
4320 }
4321 
4322 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4323                                          EVT VT) const {
4324   if (!VT.isVector()) {
4325     return MVT::i1;
4326   }
4327   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4328 }
4329 
4330 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4331   // TODO: Should i16 be used always if legal? For now it would force VALU
4332   // shifts.
4333   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4334 }
4335 
4336 // Answering this is somewhat tricky and depends on the specific device which
4337 // have different rates for fma or all f64 operations.
4338 //
4339 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4340 // regardless of which device (although the number of cycles differs between
4341 // devices), so it is always profitable for f64.
4342 //
4343 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4344 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4345 // which we can always do even without fused FP ops since it returns the same
4346 // result as the separate operations and since it is always full
4347 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4348 // however does not support denormals, so we do report fma as faster if we have
4349 // a fast fma device and require denormals.
4350 //
4351 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4352                                                   EVT VT) const {
4353   VT = VT.getScalarType();
4354 
4355   switch (VT.getSimpleVT().SimpleTy) {
4356   case MVT::f32: {
4357     // If mad is not available this depends only on if f32 fma is full rate.
4358     if (!Subtarget->hasMadMacF32Insts())
4359       return Subtarget->hasFastFMAF32();
4360 
4361     // Otherwise f32 mad is always full rate and returns the same result as
4362     // the separate operations so should be preferred over fma.
4363     // However does not support denomals.
4364     if (hasFP32Denormals(MF))
4365       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4366 
4367     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4368     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4369   }
4370   case MVT::f64:
4371     return true;
4372   case MVT::f16:
4373     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4374   default:
4375     break;
4376   }
4377 
4378   return false;
4379 }
4380 
4381 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4382                                    const SDNode *N) const {
4383   // TODO: Check future ftz flag
4384   // v_mad_f32/v_mac_f32 do not support denormals.
4385   EVT VT = N->getValueType(0);
4386   if (VT == MVT::f32)
4387     return Subtarget->hasMadMacF32Insts() &&
4388            !hasFP32Denormals(DAG.getMachineFunction());
4389   if (VT == MVT::f16) {
4390     return Subtarget->hasMadF16() &&
4391            !hasFP64FP16Denormals(DAG.getMachineFunction());
4392   }
4393 
4394   return false;
4395 }
4396 
4397 //===----------------------------------------------------------------------===//
4398 // Custom DAG Lowering Operations
4399 //===----------------------------------------------------------------------===//
4400 
4401 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4402 // wider vector type is legal.
4403 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4404                                              SelectionDAG &DAG) const {
4405   unsigned Opc = Op.getOpcode();
4406   EVT VT = Op.getValueType();
4407   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4408 
4409   SDValue Lo, Hi;
4410   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4411 
4412   SDLoc SL(Op);
4413   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4414                              Op->getFlags());
4415   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4416                              Op->getFlags());
4417 
4418   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4419 }
4420 
4421 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4422 // wider vector type is legal.
4423 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4424                                               SelectionDAG &DAG) const {
4425   unsigned Opc = Op.getOpcode();
4426   EVT VT = Op.getValueType();
4427   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4428 
4429   SDValue Lo0, Hi0;
4430   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4431   SDValue Lo1, Hi1;
4432   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4433 
4434   SDLoc SL(Op);
4435 
4436   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4437                              Op->getFlags());
4438   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4439                              Op->getFlags());
4440 
4441   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4442 }
4443 
4444 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4445                                               SelectionDAG &DAG) const {
4446   unsigned Opc = Op.getOpcode();
4447   EVT VT = Op.getValueType();
4448   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4449 
4450   SDValue Lo0, Hi0;
4451   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4452   SDValue Lo1, Hi1;
4453   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4454   SDValue Lo2, Hi2;
4455   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4456 
4457   SDLoc SL(Op);
4458 
4459   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4460                              Op->getFlags());
4461   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4462                              Op->getFlags());
4463 
4464   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4465 }
4466 
4467 
4468 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4469   switch (Op.getOpcode()) {
4470   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4471   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4472   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4473   case ISD::LOAD: {
4474     SDValue Result = LowerLOAD(Op, DAG);
4475     assert((!Result.getNode() ||
4476             Result.getNode()->getNumValues() == 2) &&
4477            "Load should return a value and a chain");
4478     return Result;
4479   }
4480 
4481   case ISD::FSIN:
4482   case ISD::FCOS:
4483     return LowerTrig(Op, DAG);
4484   case ISD::SELECT: return LowerSELECT(Op, DAG);
4485   case ISD::FDIV: return LowerFDIV(Op, DAG);
4486   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4487   case ISD::STORE: return LowerSTORE(Op, DAG);
4488   case ISD::GlobalAddress: {
4489     MachineFunction &MF = DAG.getMachineFunction();
4490     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4491     return LowerGlobalAddress(MFI, Op, DAG);
4492   }
4493   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4494   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4495   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4496   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4497   case ISD::INSERT_SUBVECTOR:
4498     return lowerINSERT_SUBVECTOR(Op, DAG);
4499   case ISD::INSERT_VECTOR_ELT:
4500     return lowerINSERT_VECTOR_ELT(Op, DAG);
4501   case ISD::EXTRACT_VECTOR_ELT:
4502     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4503   case ISD::VECTOR_SHUFFLE:
4504     return lowerVECTOR_SHUFFLE(Op, DAG);
4505   case ISD::BUILD_VECTOR:
4506     return lowerBUILD_VECTOR(Op, DAG);
4507   case ISD::FP_ROUND:
4508     return lowerFP_ROUND(Op, DAG);
4509   case ISD::TRAP:
4510     return lowerTRAP(Op, DAG);
4511   case ISD::DEBUGTRAP:
4512     return lowerDEBUGTRAP(Op, DAG);
4513   case ISD::FABS:
4514   case ISD::FNEG:
4515   case ISD::FCANONICALIZE:
4516   case ISD::BSWAP:
4517     return splitUnaryVectorOp(Op, DAG);
4518   case ISD::FMINNUM:
4519   case ISD::FMAXNUM:
4520     return lowerFMINNUM_FMAXNUM(Op, DAG);
4521   case ISD::FMA:
4522     return splitTernaryVectorOp(Op, DAG);
4523   case ISD::SHL:
4524   case ISD::SRA:
4525   case ISD::SRL:
4526   case ISD::ADD:
4527   case ISD::SUB:
4528   case ISD::MUL:
4529   case ISD::SMIN:
4530   case ISD::SMAX:
4531   case ISD::UMIN:
4532   case ISD::UMAX:
4533   case ISD::FADD:
4534   case ISD::FMUL:
4535   case ISD::FMINNUM_IEEE:
4536   case ISD::FMAXNUM_IEEE:
4537   case ISD::UADDSAT:
4538   case ISD::USUBSAT:
4539   case ISD::SADDSAT:
4540   case ISD::SSUBSAT:
4541     return splitBinaryVectorOp(Op, DAG);
4542   case ISD::SMULO:
4543   case ISD::UMULO:
4544     return lowerXMULO(Op, DAG);
4545   case ISD::DYNAMIC_STACKALLOC:
4546     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4547   }
4548   return SDValue();
4549 }
4550 
4551 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4552                                        const SDLoc &DL,
4553                                        SelectionDAG &DAG, bool Unpacked) {
4554   if (!LoadVT.isVector())
4555     return Result;
4556 
4557   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4558     // Truncate to v2i16/v4i16.
4559     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4560 
4561     // Workaround legalizer not scalarizing truncate after vector op
4562     // legalization but not creating intermediate vector trunc.
4563     SmallVector<SDValue, 4> Elts;
4564     DAG.ExtractVectorElements(Result, Elts);
4565     for (SDValue &Elt : Elts)
4566       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4567 
4568     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4569 
4570     // Bitcast to original type (v2f16/v4f16).
4571     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4572   }
4573 
4574   // Cast back to the original packed type.
4575   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4576 }
4577 
4578 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4579                                               MemSDNode *M,
4580                                               SelectionDAG &DAG,
4581                                               ArrayRef<SDValue> Ops,
4582                                               bool IsIntrinsic) const {
4583   SDLoc DL(M);
4584 
4585   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4586   EVT LoadVT = M->getValueType(0);
4587 
4588   EVT EquivLoadVT = LoadVT;
4589   if (Unpacked && LoadVT.isVector()) {
4590     EquivLoadVT = LoadVT.isVector() ?
4591       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4592                        LoadVT.getVectorNumElements()) : LoadVT;
4593   }
4594 
4595   // Change from v4f16/v2f16 to EquivLoadVT.
4596   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4597 
4598   SDValue Load
4599     = DAG.getMemIntrinsicNode(
4600       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4601       VTList, Ops, M->getMemoryVT(),
4602       M->getMemOperand());
4603   if (!Unpacked) // Just adjusted the opcode.
4604     return Load;
4605 
4606   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4607 
4608   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4609 }
4610 
4611 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4612                                              SelectionDAG &DAG,
4613                                              ArrayRef<SDValue> Ops) const {
4614   SDLoc DL(M);
4615   EVT LoadVT = M->getValueType(0);
4616   EVT EltType = LoadVT.getScalarType();
4617   EVT IntVT = LoadVT.changeTypeToInteger();
4618 
4619   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4620 
4621   unsigned Opc =
4622       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4623 
4624   if (IsD16) {
4625     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4626   }
4627 
4628   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4629   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4630     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4631 
4632   if (isTypeLegal(LoadVT)) {
4633     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4634                                M->getMemOperand(), DAG);
4635   }
4636 
4637   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4638   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4639   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4640                                         M->getMemOperand(), DAG);
4641   return DAG.getMergeValues(
4642       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4643       DL);
4644 }
4645 
4646 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4647                                   SDNode *N, SelectionDAG &DAG) {
4648   EVT VT = N->getValueType(0);
4649   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4650   unsigned CondCode = CD->getZExtValue();
4651   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4652     return DAG.getUNDEF(VT);
4653 
4654   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4655 
4656   SDValue LHS = N->getOperand(1);
4657   SDValue RHS = N->getOperand(2);
4658 
4659   SDLoc DL(N);
4660 
4661   EVT CmpVT = LHS.getValueType();
4662   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4663     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4664       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4665     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4666     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4667   }
4668 
4669   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4670 
4671   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4672   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4673 
4674   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4675                               DAG.getCondCode(CCOpcode));
4676   if (VT.bitsEq(CCVT))
4677     return SetCC;
4678   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4679 }
4680 
4681 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4682                                   SDNode *N, SelectionDAG &DAG) {
4683   EVT VT = N->getValueType(0);
4684   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4685 
4686   unsigned CondCode = CD->getZExtValue();
4687   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4688     return DAG.getUNDEF(VT);
4689 
4690   SDValue Src0 = N->getOperand(1);
4691   SDValue Src1 = N->getOperand(2);
4692   EVT CmpVT = Src0.getValueType();
4693   SDLoc SL(N);
4694 
4695   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4696     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4697     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4698   }
4699 
4700   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4701   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4702   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4703   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4704   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4705                               Src1, DAG.getCondCode(CCOpcode));
4706   if (VT.bitsEq(CCVT))
4707     return SetCC;
4708   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4709 }
4710 
4711 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4712                                     SelectionDAG &DAG) {
4713   EVT VT = N->getValueType(0);
4714   SDValue Src = N->getOperand(1);
4715   SDLoc SL(N);
4716 
4717   if (Src.getOpcode() == ISD::SETCC) {
4718     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4719     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4720                        Src.getOperand(1), Src.getOperand(2));
4721   }
4722   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4723     // (ballot 0) -> 0
4724     if (Arg->isNullValue())
4725       return DAG.getConstant(0, SL, VT);
4726 
4727     // (ballot 1) -> EXEC/EXEC_LO
4728     if (Arg->isOne()) {
4729       Register Exec;
4730       if (VT.getScalarSizeInBits() == 32)
4731         Exec = AMDGPU::EXEC_LO;
4732       else if (VT.getScalarSizeInBits() == 64)
4733         Exec = AMDGPU::EXEC;
4734       else
4735         return SDValue();
4736 
4737       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4738     }
4739   }
4740 
4741   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4742   // ISD::SETNE)
4743   return DAG.getNode(
4744       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4745       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4746 }
4747 
4748 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4749                                           SmallVectorImpl<SDValue> &Results,
4750                                           SelectionDAG &DAG) const {
4751   switch (N->getOpcode()) {
4752   case ISD::INSERT_VECTOR_ELT: {
4753     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4754       Results.push_back(Res);
4755     return;
4756   }
4757   case ISD::EXTRACT_VECTOR_ELT: {
4758     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4759       Results.push_back(Res);
4760     return;
4761   }
4762   case ISD::INTRINSIC_WO_CHAIN: {
4763     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4764     switch (IID) {
4765     case Intrinsic::amdgcn_cvt_pkrtz: {
4766       SDValue Src0 = N->getOperand(1);
4767       SDValue Src1 = N->getOperand(2);
4768       SDLoc SL(N);
4769       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4770                                 Src0, Src1);
4771       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4772       return;
4773     }
4774     case Intrinsic::amdgcn_cvt_pknorm_i16:
4775     case Intrinsic::amdgcn_cvt_pknorm_u16:
4776     case Intrinsic::amdgcn_cvt_pk_i16:
4777     case Intrinsic::amdgcn_cvt_pk_u16: {
4778       SDValue Src0 = N->getOperand(1);
4779       SDValue Src1 = N->getOperand(2);
4780       SDLoc SL(N);
4781       unsigned Opcode;
4782 
4783       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4784         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4785       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4786         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4787       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4788         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4789       else
4790         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4791 
4792       EVT VT = N->getValueType(0);
4793       if (isTypeLegal(VT))
4794         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4795       else {
4796         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4797         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4798       }
4799       return;
4800     }
4801     }
4802     break;
4803   }
4804   case ISD::INTRINSIC_W_CHAIN: {
4805     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4806       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4807         // FIXME: Hacky
4808         Results.push_back(Res.getOperand(0));
4809         Results.push_back(Res.getOperand(1));
4810       } else {
4811         Results.push_back(Res);
4812         Results.push_back(Res.getValue(1));
4813       }
4814       return;
4815     }
4816 
4817     break;
4818   }
4819   case ISD::SELECT: {
4820     SDLoc SL(N);
4821     EVT VT = N->getValueType(0);
4822     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4823     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4824     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4825 
4826     EVT SelectVT = NewVT;
4827     if (NewVT.bitsLT(MVT::i32)) {
4828       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4829       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4830       SelectVT = MVT::i32;
4831     }
4832 
4833     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4834                                     N->getOperand(0), LHS, RHS);
4835 
4836     if (NewVT != SelectVT)
4837       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4838     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4839     return;
4840   }
4841   case ISD::FNEG: {
4842     if (N->getValueType(0) != MVT::v2f16)
4843       break;
4844 
4845     SDLoc SL(N);
4846     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4847 
4848     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4849                              BC,
4850                              DAG.getConstant(0x80008000, SL, MVT::i32));
4851     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4852     return;
4853   }
4854   case ISD::FABS: {
4855     if (N->getValueType(0) != MVT::v2f16)
4856       break;
4857 
4858     SDLoc SL(N);
4859     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4860 
4861     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4862                              BC,
4863                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4864     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4865     return;
4866   }
4867   default:
4868     break;
4869   }
4870 }
4871 
4872 /// Helper function for LowerBRCOND
4873 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4874 
4875   SDNode *Parent = Value.getNode();
4876   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4877        I != E; ++I) {
4878 
4879     if (I.getUse().get() != Value)
4880       continue;
4881 
4882     if (I->getOpcode() == Opcode)
4883       return *I;
4884   }
4885   return nullptr;
4886 }
4887 
4888 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4889   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4890     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4891     case Intrinsic::amdgcn_if:
4892       return AMDGPUISD::IF;
4893     case Intrinsic::amdgcn_else:
4894       return AMDGPUISD::ELSE;
4895     case Intrinsic::amdgcn_loop:
4896       return AMDGPUISD::LOOP;
4897     case Intrinsic::amdgcn_end_cf:
4898       llvm_unreachable("should not occur");
4899     default:
4900       return 0;
4901     }
4902   }
4903 
4904   // break, if_break, else_break are all only used as inputs to loop, not
4905   // directly as branch conditions.
4906   return 0;
4907 }
4908 
4909 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4910   const Triple &TT = getTargetMachine().getTargetTriple();
4911   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4912           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4913          AMDGPU::shouldEmitConstantsToTextSection(TT);
4914 }
4915 
4916 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4917   // FIXME: Either avoid relying on address space here or change the default
4918   // address space for functions to avoid the explicit check.
4919   return (GV->getValueType()->isFunctionTy() ||
4920           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4921          !shouldEmitFixup(GV) &&
4922          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4923 }
4924 
4925 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4926   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4927 }
4928 
4929 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4930   if (!GV->hasExternalLinkage())
4931     return true;
4932 
4933   const auto OS = getTargetMachine().getTargetTriple().getOS();
4934   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4935 }
4936 
4937 /// This transforms the control flow intrinsics to get the branch destination as
4938 /// last parameter, also switches branch target with BR if the need arise
4939 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4940                                       SelectionDAG &DAG) const {
4941   SDLoc DL(BRCOND);
4942 
4943   SDNode *Intr = BRCOND.getOperand(1).getNode();
4944   SDValue Target = BRCOND.getOperand(2);
4945   SDNode *BR = nullptr;
4946   SDNode *SetCC = nullptr;
4947 
4948   if (Intr->getOpcode() == ISD::SETCC) {
4949     // As long as we negate the condition everything is fine
4950     SetCC = Intr;
4951     Intr = SetCC->getOperand(0).getNode();
4952 
4953   } else {
4954     // Get the target from BR if we don't negate the condition
4955     BR = findUser(BRCOND, ISD::BR);
4956     assert(BR && "brcond missing unconditional branch user");
4957     Target = BR->getOperand(1);
4958   }
4959 
4960   unsigned CFNode = isCFIntrinsic(Intr);
4961   if (CFNode == 0) {
4962     // This is a uniform branch so we don't need to legalize.
4963     return BRCOND;
4964   }
4965 
4966   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4967                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4968 
4969   assert(!SetCC ||
4970         (SetCC->getConstantOperandVal(1) == 1 &&
4971          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4972                                                              ISD::SETNE));
4973 
4974   // operands of the new intrinsic call
4975   SmallVector<SDValue, 4> Ops;
4976   if (HaveChain)
4977     Ops.push_back(BRCOND.getOperand(0));
4978 
4979   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4980   Ops.push_back(Target);
4981 
4982   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4983 
4984   // build the new intrinsic call
4985   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4986 
4987   if (!HaveChain) {
4988     SDValue Ops[] =  {
4989       SDValue(Result, 0),
4990       BRCOND.getOperand(0)
4991     };
4992 
4993     Result = DAG.getMergeValues(Ops, DL).getNode();
4994   }
4995 
4996   if (BR) {
4997     // Give the branch instruction our target
4998     SDValue Ops[] = {
4999       BR->getOperand(0),
5000       BRCOND.getOperand(2)
5001     };
5002     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5003     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5004   }
5005 
5006   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5007 
5008   // Copy the intrinsic results to registers
5009   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5010     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5011     if (!CopyToReg)
5012       continue;
5013 
5014     Chain = DAG.getCopyToReg(
5015       Chain, DL,
5016       CopyToReg->getOperand(1),
5017       SDValue(Result, i - 1),
5018       SDValue());
5019 
5020     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5021   }
5022 
5023   // Remove the old intrinsic from the chain
5024   DAG.ReplaceAllUsesOfValueWith(
5025     SDValue(Intr, Intr->getNumValues() - 1),
5026     Intr->getOperand(0));
5027 
5028   return Chain;
5029 }
5030 
5031 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5032                                           SelectionDAG &DAG) const {
5033   MVT VT = Op.getSimpleValueType();
5034   SDLoc DL(Op);
5035   // Checking the depth
5036   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5037     return DAG.getConstant(0, DL, VT);
5038 
5039   MachineFunction &MF = DAG.getMachineFunction();
5040   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5041   // Check for kernel and shader functions
5042   if (Info->isEntryFunction())
5043     return DAG.getConstant(0, DL, VT);
5044 
5045   MachineFrameInfo &MFI = MF.getFrameInfo();
5046   // There is a call to @llvm.returnaddress in this function
5047   MFI.setReturnAddressIsTaken(true);
5048 
5049   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5050   // Get the return address reg and mark it as an implicit live-in
5051   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5052 
5053   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5054 }
5055 
5056 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5057                                             SDValue Op,
5058                                             const SDLoc &DL,
5059                                             EVT VT) const {
5060   return Op.getValueType().bitsLE(VT) ?
5061       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5062     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5063                 DAG.getTargetConstant(0, DL, MVT::i32));
5064 }
5065 
5066 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5067   assert(Op.getValueType() == MVT::f16 &&
5068          "Do not know how to custom lower FP_ROUND for non-f16 type");
5069 
5070   SDValue Src = Op.getOperand(0);
5071   EVT SrcVT = Src.getValueType();
5072   if (SrcVT != MVT::f64)
5073     return Op;
5074 
5075   SDLoc DL(Op);
5076 
5077   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5078   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5079   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5080 }
5081 
5082 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5083                                                SelectionDAG &DAG) const {
5084   EVT VT = Op.getValueType();
5085   const MachineFunction &MF = DAG.getMachineFunction();
5086   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5087   bool IsIEEEMode = Info->getMode().IEEE;
5088 
5089   // FIXME: Assert during selection that this is only selected for
5090   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5091   // mode functions, but this happens to be OK since it's only done in cases
5092   // where there is known no sNaN.
5093   if (IsIEEEMode)
5094     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5095 
5096   if (VT == MVT::v4f16)
5097     return splitBinaryVectorOp(Op, DAG);
5098   return Op;
5099 }
5100 
5101 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5102   EVT VT = Op.getValueType();
5103   SDLoc SL(Op);
5104   SDValue LHS = Op.getOperand(0);
5105   SDValue RHS = Op.getOperand(1);
5106   bool isSigned = Op.getOpcode() == ISD::SMULO;
5107 
5108   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5109     const APInt &C = RHSC->getAPIntValue();
5110     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5111     if (C.isPowerOf2()) {
5112       // smulo(x, signed_min) is same as umulo(x, signed_min).
5113       bool UseArithShift = isSigned && !C.isMinSignedValue();
5114       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5115       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5116       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5117           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5118                       SL, VT, Result, ShiftAmt),
5119           LHS, ISD::SETNE);
5120       return DAG.getMergeValues({ Result, Overflow }, SL);
5121     }
5122   }
5123 
5124   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5125   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5126                             SL, VT, LHS, RHS);
5127 
5128   SDValue Sign = isSigned
5129     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5130                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5131     : DAG.getConstant(0, SL, VT);
5132   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5133 
5134   return DAG.getMergeValues({ Result, Overflow }, SL);
5135 }
5136 
5137 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5138   SDLoc SL(Op);
5139   SDValue Chain = Op.getOperand(0);
5140 
5141   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5142       !Subtarget->isTrapHandlerEnabled())
5143     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5144 
5145   MachineFunction &MF = DAG.getMachineFunction();
5146   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5147   Register UserSGPR = Info->getQueuePtrUserSGPR();
5148   assert(UserSGPR != AMDGPU::NoRegister);
5149   SDValue QueuePtr = CreateLiveInRegister(
5150     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5151   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5152   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5153                                    QueuePtr, SDValue());
5154   SDValue Ops[] = {
5155     ToReg,
5156     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5157     SGPR01,
5158     ToReg.getValue(1)
5159   };
5160   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5161 }
5162 
5163 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5164   SDLoc SL(Op);
5165   SDValue Chain = Op.getOperand(0);
5166   MachineFunction &MF = DAG.getMachineFunction();
5167 
5168   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5169       !Subtarget->isTrapHandlerEnabled()) {
5170     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5171                                      "debugtrap handler not supported",
5172                                      Op.getDebugLoc(),
5173                                      DS_Warning);
5174     LLVMContext &Ctx = MF.getFunction().getContext();
5175     Ctx.diagnose(NoTrap);
5176     return Chain;
5177   }
5178 
5179   SDValue Ops[] = {
5180     Chain,
5181     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5182   };
5183   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5184 }
5185 
5186 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5187                                              SelectionDAG &DAG) const {
5188   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5189   if (Subtarget->hasApertureRegs()) {
5190     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5191         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5192         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5193     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5194         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5195         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5196     unsigned Encoding =
5197         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5198         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5199         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5200 
5201     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5202     SDValue ApertureReg = SDValue(
5203         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5204     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5205     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5206   }
5207 
5208   MachineFunction &MF = DAG.getMachineFunction();
5209   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5210   Register UserSGPR = Info->getQueuePtrUserSGPR();
5211   assert(UserSGPR != AMDGPU::NoRegister);
5212 
5213   SDValue QueuePtr = CreateLiveInRegister(
5214     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5215 
5216   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5217   // private_segment_aperture_base_hi.
5218   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5219 
5220   SDValue Ptr =
5221       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5222 
5223   // TODO: Use custom target PseudoSourceValue.
5224   // TODO: We should use the value from the IR intrinsic call, but it might not
5225   // be available and how do we get it?
5226   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5227   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5228                      MinAlign(64, StructOffset),
5229                      MachineMemOperand::MODereferenceable |
5230                          MachineMemOperand::MOInvariant);
5231 }
5232 
5233 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5234                                              SelectionDAG &DAG) const {
5235   SDLoc SL(Op);
5236   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5237 
5238   SDValue Src = ASC->getOperand(0);
5239   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5240 
5241   const AMDGPUTargetMachine &TM =
5242     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5243 
5244   // flat -> local/private
5245   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5246     unsigned DestAS = ASC->getDestAddressSpace();
5247 
5248     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5249         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5250       unsigned NullVal = TM.getNullPointerValue(DestAS);
5251       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5252       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5253       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5254 
5255       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5256                          NonNull, Ptr, SegmentNullPtr);
5257     }
5258   }
5259 
5260   // local/private -> flat
5261   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5262     unsigned SrcAS = ASC->getSrcAddressSpace();
5263 
5264     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5265         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5266       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5267       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5268 
5269       SDValue NonNull
5270         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5271 
5272       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5273       SDValue CvtPtr
5274         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5275 
5276       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5277                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5278                          FlatNullPtr);
5279     }
5280   }
5281 
5282   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5283       Src.getValueType() == MVT::i64)
5284     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5285 
5286   // global <-> flat are no-ops and never emitted.
5287 
5288   const MachineFunction &MF = DAG.getMachineFunction();
5289   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5290     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5291   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5292 
5293   return DAG.getUNDEF(ASC->getValueType(0));
5294 }
5295 
5296 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5297 // the small vector and inserting them into the big vector. That is better than
5298 // the default expansion of doing it via a stack slot. Even though the use of
5299 // the stack slot would be optimized away afterwards, the stack slot itself
5300 // remains.
5301 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5302                                                 SelectionDAG &DAG) const {
5303   SDValue Vec = Op.getOperand(0);
5304   SDValue Ins = Op.getOperand(1);
5305   SDValue Idx = Op.getOperand(2);
5306   EVT VecVT = Vec.getValueType();
5307   EVT InsVT = Ins.getValueType();
5308   EVT EltVT = VecVT.getVectorElementType();
5309   unsigned InsNumElts = InsVT.getVectorNumElements();
5310   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5311   SDLoc SL(Op);
5312 
5313   for (unsigned I = 0; I != InsNumElts; ++I) {
5314     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5315                               DAG.getConstant(I, SL, MVT::i32));
5316     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5317                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5318   }
5319   return Vec;
5320 }
5321 
5322 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5323                                                  SelectionDAG &DAG) const {
5324   SDValue Vec = Op.getOperand(0);
5325   SDValue InsVal = Op.getOperand(1);
5326   SDValue Idx = Op.getOperand(2);
5327   EVT VecVT = Vec.getValueType();
5328   EVT EltVT = VecVT.getVectorElementType();
5329   unsigned VecSize = VecVT.getSizeInBits();
5330   unsigned EltSize = EltVT.getSizeInBits();
5331 
5332 
5333   assert(VecSize <= 64);
5334 
5335   unsigned NumElts = VecVT.getVectorNumElements();
5336   SDLoc SL(Op);
5337   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5338 
5339   if (NumElts == 4 && EltSize == 16 && KIdx) {
5340     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5341 
5342     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5343                                  DAG.getConstant(0, SL, MVT::i32));
5344     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5345                                  DAG.getConstant(1, SL, MVT::i32));
5346 
5347     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5348     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5349 
5350     unsigned Idx = KIdx->getZExtValue();
5351     bool InsertLo = Idx < 2;
5352     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5353       InsertLo ? LoVec : HiVec,
5354       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5355       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5356 
5357     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5358 
5359     SDValue Concat = InsertLo ?
5360       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5361       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5362 
5363     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5364   }
5365 
5366   if (isa<ConstantSDNode>(Idx))
5367     return SDValue();
5368 
5369   MVT IntVT = MVT::getIntegerVT(VecSize);
5370 
5371   // Avoid stack access for dynamic indexing.
5372   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5373 
5374   // Create a congruent vector with the target value in each element so that
5375   // the required element can be masked and ORed into the target vector.
5376   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5377                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5378 
5379   assert(isPowerOf2_32(EltSize));
5380   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5381 
5382   // Convert vector index to bit-index.
5383   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5384 
5385   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5386   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5387                             DAG.getConstant(0xffff, SL, IntVT),
5388                             ScaledIdx);
5389 
5390   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5391   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5392                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5393 
5394   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5395   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5396 }
5397 
5398 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5399                                                   SelectionDAG &DAG) const {
5400   SDLoc SL(Op);
5401 
5402   EVT ResultVT = Op.getValueType();
5403   SDValue Vec = Op.getOperand(0);
5404   SDValue Idx = Op.getOperand(1);
5405   EVT VecVT = Vec.getValueType();
5406   unsigned VecSize = VecVT.getSizeInBits();
5407   EVT EltVT = VecVT.getVectorElementType();
5408   assert(VecSize <= 64);
5409 
5410   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5411 
5412   // Make sure we do any optimizations that will make it easier to fold
5413   // source modifiers before obscuring it with bit operations.
5414 
5415   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5416   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5417     return Combined;
5418 
5419   unsigned EltSize = EltVT.getSizeInBits();
5420   assert(isPowerOf2_32(EltSize));
5421 
5422   MVT IntVT = MVT::getIntegerVT(VecSize);
5423   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5424 
5425   // Convert vector index to bit-index (* EltSize)
5426   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5427 
5428   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5429   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5430 
5431   if (ResultVT == MVT::f16) {
5432     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5433     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5434   }
5435 
5436   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5437 }
5438 
5439 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5440   assert(Elt % 2 == 0);
5441   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5442 }
5443 
5444 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5445                                               SelectionDAG &DAG) const {
5446   SDLoc SL(Op);
5447   EVT ResultVT = Op.getValueType();
5448   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5449 
5450   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5451   EVT EltVT = PackVT.getVectorElementType();
5452   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5453 
5454   // vector_shuffle <0,1,6,7> lhs, rhs
5455   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5456   //
5457   // vector_shuffle <6,7,2,3> lhs, rhs
5458   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5459   //
5460   // vector_shuffle <6,7,0,1> lhs, rhs
5461   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5462 
5463   // Avoid scalarizing when both halves are reading from consecutive elements.
5464   SmallVector<SDValue, 4> Pieces;
5465   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5466     if (elementPairIsContiguous(SVN->getMask(), I)) {
5467       const int Idx = SVN->getMaskElt(I);
5468       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5469       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5470       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5471                                     PackVT, SVN->getOperand(VecIdx),
5472                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5473       Pieces.push_back(SubVec);
5474     } else {
5475       const int Idx0 = SVN->getMaskElt(I);
5476       const int Idx1 = SVN->getMaskElt(I + 1);
5477       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5478       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5479       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5480       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5481 
5482       SDValue Vec0 = SVN->getOperand(VecIdx0);
5483       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5484                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5485 
5486       SDValue Vec1 = SVN->getOperand(VecIdx1);
5487       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5488                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5489       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5490     }
5491   }
5492 
5493   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5494 }
5495 
5496 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5497                                             SelectionDAG &DAG) const {
5498   SDLoc SL(Op);
5499   EVT VT = Op.getValueType();
5500 
5501   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5502     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5503 
5504     // Turn into pair of packed build_vectors.
5505     // TODO: Special case for constants that can be materialized with s_mov_b64.
5506     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5507                                     { Op.getOperand(0), Op.getOperand(1) });
5508     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5509                                     { Op.getOperand(2), Op.getOperand(3) });
5510 
5511     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5512     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5513 
5514     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5515     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5516   }
5517 
5518   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5519   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5520 
5521   SDValue Lo = Op.getOperand(0);
5522   SDValue Hi = Op.getOperand(1);
5523 
5524   // Avoid adding defined bits with the zero_extend.
5525   if (Hi.isUndef()) {
5526     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5527     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5528     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5529   }
5530 
5531   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5532   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5533 
5534   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5535                               DAG.getConstant(16, SL, MVT::i32));
5536   if (Lo.isUndef())
5537     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5538 
5539   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5540   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5541 
5542   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5543   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5544 }
5545 
5546 bool
5547 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5548   // We can fold offsets for anything that doesn't require a GOT relocation.
5549   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5550           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5551           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5552          !shouldEmitGOTReloc(GA->getGlobal());
5553 }
5554 
5555 static SDValue
5556 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5557                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5558                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5559   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5560   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5561   // lowered to the following code sequence:
5562   //
5563   // For constant address space:
5564   //   s_getpc_b64 s[0:1]
5565   //   s_add_u32 s0, s0, $symbol
5566   //   s_addc_u32 s1, s1, 0
5567   //
5568   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5569   //   a fixup or relocation is emitted to replace $symbol with a literal
5570   //   constant, which is a pc-relative offset from the encoding of the $symbol
5571   //   operand to the global variable.
5572   //
5573   // For global address space:
5574   //   s_getpc_b64 s[0:1]
5575   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5576   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5577   //
5578   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5579   //   fixups or relocations are emitted to replace $symbol@*@lo and
5580   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5581   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5582   //   operand to the global variable.
5583   //
5584   // What we want here is an offset from the value returned by s_getpc
5585   // (which is the address of the s_add_u32 instruction) to the global
5586   // variable, but since the encoding of $symbol starts 4 bytes after the start
5587   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5588   // small. This requires us to add 4 to the global variable offset in order to
5589   // compute the correct address.
5590   SDValue PtrLo =
5591       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5592   SDValue PtrHi;
5593   if (GAFlags == SIInstrInfo::MO_NONE) {
5594     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5595   } else {
5596     PtrHi =
5597         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5598   }
5599   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5600 }
5601 
5602 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5603                                              SDValue Op,
5604                                              SelectionDAG &DAG) const {
5605   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5606   SDLoc DL(GSD);
5607   EVT PtrVT = Op.getValueType();
5608 
5609   const GlobalValue *GV = GSD->getGlobal();
5610   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5611        shouldUseLDSConstAddress(GV)) ||
5612       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5613       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5614     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5615         GV->hasExternalLinkage()) {
5616       Type *Ty = GV->getValueType();
5617       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5618       // zero-sized type in other languages to declare the dynamic shared
5619       // memory which size is not known at the compile time. They will be
5620       // allocated by the runtime and placed directly after the static
5621       // allocated ones. They all share the same offset.
5622       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5623         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5624         // Adjust alignment for that dynamic shared memory array.
5625         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5626         return SDValue(
5627             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5628       }
5629     }
5630     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5631   }
5632 
5633   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5634     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5635                                             SIInstrInfo::MO_ABS32_LO);
5636     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5637   }
5638 
5639   if (shouldEmitFixup(GV))
5640     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5641   else if (shouldEmitPCReloc(GV))
5642     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5643                                    SIInstrInfo::MO_REL32);
5644 
5645   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5646                                             SIInstrInfo::MO_GOTPCREL32);
5647 
5648   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5649   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5650   const DataLayout &DataLayout = DAG.getDataLayout();
5651   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5652   MachinePointerInfo PtrInfo
5653     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5654 
5655   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5656                      MachineMemOperand::MODereferenceable |
5657                          MachineMemOperand::MOInvariant);
5658 }
5659 
5660 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5661                                    const SDLoc &DL, SDValue V) const {
5662   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5663   // the destination register.
5664   //
5665   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5666   // so we will end up with redundant moves to m0.
5667   //
5668   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5669 
5670   // A Null SDValue creates a glue result.
5671   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5672                                   V, Chain);
5673   return SDValue(M0, 0);
5674 }
5675 
5676 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5677                                                  SDValue Op,
5678                                                  MVT VT,
5679                                                  unsigned Offset) const {
5680   SDLoc SL(Op);
5681   SDValue Param = lowerKernargMemParameter(
5682       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5683   // The local size values will have the hi 16-bits as zero.
5684   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5685                      DAG.getValueType(VT));
5686 }
5687 
5688 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5689                                         EVT VT) {
5690   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5691                                       "non-hsa intrinsic with hsa target",
5692                                       DL.getDebugLoc());
5693   DAG.getContext()->diagnose(BadIntrin);
5694   return DAG.getUNDEF(VT);
5695 }
5696 
5697 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5698                                          EVT VT) {
5699   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5700                                       "intrinsic not supported on subtarget",
5701                                       DL.getDebugLoc());
5702   DAG.getContext()->diagnose(BadIntrin);
5703   return DAG.getUNDEF(VT);
5704 }
5705 
5706 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5707                                     ArrayRef<SDValue> Elts) {
5708   assert(!Elts.empty());
5709   MVT Type;
5710   unsigned NumElts;
5711 
5712   if (Elts.size() == 1) {
5713     Type = MVT::f32;
5714     NumElts = 1;
5715   } else if (Elts.size() == 2) {
5716     Type = MVT::v2f32;
5717     NumElts = 2;
5718   } else if (Elts.size() == 3) {
5719     Type = MVT::v3f32;
5720     NumElts = 3;
5721   } else if (Elts.size() <= 4) {
5722     Type = MVT::v4f32;
5723     NumElts = 4;
5724   } else if (Elts.size() <= 8) {
5725     Type = MVT::v8f32;
5726     NumElts = 8;
5727   } else {
5728     assert(Elts.size() <= 16);
5729     Type = MVT::v16f32;
5730     NumElts = 16;
5731   }
5732 
5733   SmallVector<SDValue, 16> VecElts(NumElts);
5734   for (unsigned i = 0; i < Elts.size(); ++i) {
5735     SDValue Elt = Elts[i];
5736     if (Elt.getValueType() != MVT::f32)
5737       Elt = DAG.getBitcast(MVT::f32, Elt);
5738     VecElts[i] = Elt;
5739   }
5740   for (unsigned i = Elts.size(); i < NumElts; ++i)
5741     VecElts[i] = DAG.getUNDEF(MVT::f32);
5742 
5743   if (NumElts == 1)
5744     return VecElts[0];
5745   return DAG.getBuildVector(Type, DL, VecElts);
5746 }
5747 
5748 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5749                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5750   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5751 
5752   uint64_t Value = CachePolicyConst->getZExtValue();
5753   SDLoc DL(CachePolicy);
5754   if (GLC) {
5755     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5756     Value &= ~(uint64_t)0x1;
5757   }
5758   if (SLC) {
5759     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5760     Value &= ~(uint64_t)0x2;
5761   }
5762   if (DLC) {
5763     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5764     Value &= ~(uint64_t)0x4;
5765   }
5766 
5767   return Value == 0;
5768 }
5769 
5770 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5771                               SDValue Src, int ExtraElts) {
5772   EVT SrcVT = Src.getValueType();
5773 
5774   SmallVector<SDValue, 8> Elts;
5775 
5776   if (SrcVT.isVector())
5777     DAG.ExtractVectorElements(Src, Elts);
5778   else
5779     Elts.push_back(Src);
5780 
5781   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5782   while (ExtraElts--)
5783     Elts.push_back(Undef);
5784 
5785   return DAG.getBuildVector(CastVT, DL, Elts);
5786 }
5787 
5788 // Re-construct the required return value for a image load intrinsic.
5789 // This is more complicated due to the optional use TexFailCtrl which means the required
5790 // return type is an aggregate
5791 static SDValue constructRetValue(SelectionDAG &DAG,
5792                                  MachineSDNode *Result,
5793                                  ArrayRef<EVT> ResultTypes,
5794                                  bool IsTexFail, bool Unpacked, bool IsD16,
5795                                  int DMaskPop, int NumVDataDwords,
5796                                  const SDLoc &DL, LLVMContext &Context) {
5797   // Determine the required return type. This is the same regardless of IsTexFail flag
5798   EVT ReqRetVT = ResultTypes[0];
5799   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5800   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5801     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5802 
5803   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5804     DMaskPop : (DMaskPop + 1) / 2;
5805 
5806   MVT DataDwordVT = NumDataDwords == 1 ?
5807     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5808 
5809   MVT MaskPopVT = MaskPopDwords == 1 ?
5810     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5811 
5812   SDValue Data(Result, 0);
5813   SDValue TexFail;
5814 
5815   if (IsTexFail) {
5816     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5817     if (MaskPopVT.isVector()) {
5818       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5819                          SDValue(Result, 0), ZeroIdx);
5820     } else {
5821       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5822                          SDValue(Result, 0), ZeroIdx);
5823     }
5824 
5825     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5826                           SDValue(Result, 0),
5827                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5828   }
5829 
5830   if (DataDwordVT.isVector())
5831     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5832                           NumDataDwords - MaskPopDwords);
5833 
5834   if (IsD16)
5835     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5836 
5837   if (!ReqRetVT.isVector())
5838     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5839 
5840   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5841 
5842   if (TexFail)
5843     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5844 
5845   if (Result->getNumValues() == 1)
5846     return Data;
5847 
5848   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5849 }
5850 
5851 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5852                          SDValue *LWE, bool &IsTexFail) {
5853   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5854 
5855   uint64_t Value = TexFailCtrlConst->getZExtValue();
5856   if (Value) {
5857     IsTexFail = true;
5858   }
5859 
5860   SDLoc DL(TexFailCtrlConst);
5861   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5862   Value &= ~(uint64_t)0x1;
5863   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5864   Value &= ~(uint64_t)0x2;
5865 
5866   return Value == 0;
5867 }
5868 
5869 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5870                                         MVT PackVectorVT,
5871                                         SmallVectorImpl<SDValue> &PackedAddrs,
5872                                         unsigned DimIdx, unsigned EndIdx,
5873                                         unsigned NumGradients) {
5874   SDLoc DL(Op);
5875   for (unsigned I = DimIdx; I < EndIdx; I++) {
5876     SDValue Addr = Op.getOperand(I);
5877 
5878     // Gradients are packed with undef for each coordinate.
5879     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5880     // 1D: undef,dx/dh; undef,dx/dv
5881     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5882     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5883     if (((I + 1) >= EndIdx) ||
5884         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5885                                          I == DimIdx + NumGradients - 1))) {
5886       if (Addr.getValueType() != MVT::i16)
5887         Addr = DAG.getBitcast(MVT::i16, Addr);
5888       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5889     } else {
5890       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5891       I++;
5892     }
5893     Addr = DAG.getBitcast(MVT::f32, Addr);
5894     PackedAddrs.push_back(Addr);
5895   }
5896 }
5897 
5898 SDValue SITargetLowering::lowerImage(SDValue Op,
5899                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5900                                      SelectionDAG &DAG) const {
5901   SDLoc DL(Op);
5902   MachineFunction &MF = DAG.getMachineFunction();
5903   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5904   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5905       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5906   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5907   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5908       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5909   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5910       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5911   unsigned IntrOpcode = Intr->BaseOpcode;
5912   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5913 
5914   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5915   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5916   bool IsD16 = false;
5917   bool IsG16 = false;
5918   bool IsA16 = false;
5919   SDValue VData;
5920   int NumVDataDwords;
5921   bool AdjustRetType = false;
5922 
5923   unsigned AddrIdx; // Index of first address argument
5924   unsigned DMask;
5925   unsigned DMaskLanes = 0;
5926 
5927   if (BaseOpcode->Atomic) {
5928     VData = Op.getOperand(2);
5929 
5930     bool Is64Bit = VData.getValueType() == MVT::i64;
5931     if (BaseOpcode->AtomicX2) {
5932       SDValue VData2 = Op.getOperand(3);
5933       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5934                                  {VData, VData2});
5935       if (Is64Bit)
5936         VData = DAG.getBitcast(MVT::v4i32, VData);
5937 
5938       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5939       DMask = Is64Bit ? 0xf : 0x3;
5940       NumVDataDwords = Is64Bit ? 4 : 2;
5941       AddrIdx = 4;
5942     } else {
5943       DMask = Is64Bit ? 0x3 : 0x1;
5944       NumVDataDwords = Is64Bit ? 2 : 1;
5945       AddrIdx = 3;
5946     }
5947   } else {
5948     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5949     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5950     DMask = DMaskConst->getZExtValue();
5951     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5952 
5953     if (BaseOpcode->Store) {
5954       VData = Op.getOperand(2);
5955 
5956       MVT StoreVT = VData.getSimpleValueType();
5957       if (StoreVT.getScalarType() == MVT::f16) {
5958         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5959           return Op; // D16 is unsupported for this instruction
5960 
5961         IsD16 = true;
5962         VData = handleD16VData(VData, DAG);
5963       }
5964 
5965       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5966     } else {
5967       // Work out the num dwords based on the dmask popcount and underlying type
5968       // and whether packing is supported.
5969       MVT LoadVT = ResultTypes[0].getSimpleVT();
5970       if (LoadVT.getScalarType() == MVT::f16) {
5971         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5972           return Op; // D16 is unsupported for this instruction
5973 
5974         IsD16 = true;
5975       }
5976 
5977       // Confirm that the return type is large enough for the dmask specified
5978       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5979           (!LoadVT.isVector() && DMaskLanes > 1))
5980           return Op;
5981 
5982       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5983         NumVDataDwords = (DMaskLanes + 1) / 2;
5984       else
5985         NumVDataDwords = DMaskLanes;
5986 
5987       AdjustRetType = true;
5988     }
5989 
5990     AddrIdx = DMaskIdx + 1;
5991   }
5992 
5993   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5994   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5995   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5996   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5997                        NumCoords + NumLCM;
5998   unsigned NumMIVAddrs = NumVAddrs;
5999 
6000   SmallVector<SDValue, 4> VAddrs;
6001 
6002   // Optimize _L to _LZ when _L is zero
6003   if (LZMappingInfo) {
6004     if (auto ConstantLod =
6005          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
6006       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6007         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6008         NumMIVAddrs--;               // remove 'lod'
6009       }
6010     }
6011   }
6012 
6013   // Optimize _mip away, when 'lod' is zero
6014   if (MIPMappingInfo) {
6015     if (auto ConstantLod =
6016          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
6017       if (ConstantLod->isNullValue()) {
6018         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6019         NumMIVAddrs--;               // remove 'lod'
6020       }
6021     }
6022   }
6023 
6024   // Push back extra arguments.
6025   for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++)
6026     VAddrs.push_back(Op.getOperand(AddrIdx + I));
6027 
6028   // Check for 16 bit addresses or derivatives and pack if true.
6029   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
6030   unsigned CoordIdx = DimIdx + NumGradients;
6031   unsigned CoordsEnd = AddrIdx + NumMIVAddrs;
6032 
6033   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
6034   MVT VAddrScalarVT = VAddrVT.getScalarType();
6035   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6036   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6037 
6038   VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType();
6039   VAddrScalarVT = VAddrVT.getScalarType();
6040   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6041   if (IsA16 || IsG16) {
6042     if (IsA16) {
6043       if (!ST->hasA16()) {
6044         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6045                              "support 16 bit addresses\n");
6046         return Op;
6047       }
6048       if (!IsG16) {
6049         LLVM_DEBUG(
6050             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6051                       "need 16 bit derivatives but got 32 bit derivatives\n");
6052         return Op;
6053       }
6054     } else if (!ST->hasG16()) {
6055       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6056                            "support 16 bit derivatives\n");
6057       return Op;
6058     }
6059 
6060     if (BaseOpcode->Gradients && !IsA16) {
6061       if (!ST->hasG16()) {
6062         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6063                              "support 16 bit derivatives\n");
6064         return Op;
6065       }
6066       // Activate g16
6067       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6068           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6069       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6070     }
6071 
6072     // Don't compress addresses for G16
6073     const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx;
6074     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx,
6075                                 PackEndIdx, NumGradients);
6076 
6077     if (!IsA16) {
6078       // Add uncompressed address
6079       for (unsigned I = CoordIdx; I < CoordsEnd; I++)
6080         VAddrs.push_back(Op.getOperand(I));
6081     }
6082   } else {
6083     for (unsigned I = DimIdx; I < CoordsEnd; I++)
6084       VAddrs.push_back(Op.getOperand(I));
6085   }
6086 
6087   // If the register allocator cannot place the address registers contiguously
6088   // without introducing moves, then using the non-sequential address encoding
6089   // is always preferable, since it saves VALU instructions and is usually a
6090   // wash in terms of code size or even better.
6091   //
6092   // However, we currently have no way of hinting to the register allocator that
6093   // MIMG addresses should be placed contiguously when it is possible to do so,
6094   // so force non-NSA for the common 2-address case as a heuristic.
6095   //
6096   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6097   // allocation when possible.
6098   bool UseNSA =
6099       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6100   SDValue VAddr;
6101   if (!UseNSA)
6102     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6103 
6104   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6105   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6106   unsigned CtrlIdx; // Index of texfailctrl argument
6107   SDValue Unorm;
6108   if (!BaseOpcode->Sampler) {
6109     Unorm = True;
6110     CtrlIdx = AddrIdx + NumVAddrs + 1;
6111   } else {
6112     auto UnormConst =
6113         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
6114 
6115     Unorm = UnormConst->getZExtValue() ? True : False;
6116     CtrlIdx = AddrIdx + NumVAddrs + 3;
6117   }
6118 
6119   SDValue TFE;
6120   SDValue LWE;
6121   SDValue TexFail = Op.getOperand(CtrlIdx);
6122   bool IsTexFail = false;
6123   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6124     return Op;
6125 
6126   if (IsTexFail) {
6127     if (!DMaskLanes) {
6128       // Expecting to get an error flag since TFC is on - and dmask is 0
6129       // Force dmask to be at least 1 otherwise the instruction will fail
6130       DMask = 0x1;
6131       DMaskLanes = 1;
6132       NumVDataDwords = 1;
6133     }
6134     NumVDataDwords += 1;
6135     AdjustRetType = true;
6136   }
6137 
6138   // Has something earlier tagged that the return type needs adjusting
6139   // This happens if the instruction is a load or has set TexFailCtrl flags
6140   if (AdjustRetType) {
6141     // NumVDataDwords reflects the true number of dwords required in the return type
6142     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6143       // This is a no-op load. This can be eliminated
6144       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6145       if (isa<MemSDNode>(Op))
6146         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6147       return Undef;
6148     }
6149 
6150     EVT NewVT = NumVDataDwords > 1 ?
6151                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6152                 : MVT::i32;
6153 
6154     ResultTypes[0] = NewVT;
6155     if (ResultTypes.size() == 3) {
6156       // Original result was aggregate type used for TexFailCtrl results
6157       // The actual instruction returns as a vector type which has now been
6158       // created. Remove the aggregate result.
6159       ResultTypes.erase(&ResultTypes[1]);
6160     }
6161   }
6162 
6163   SDValue GLC;
6164   SDValue SLC;
6165   SDValue DLC;
6166   if (BaseOpcode->Atomic) {
6167     GLC = True; // TODO no-return optimization
6168     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
6169                           IsGFX10 ? &DLC : nullptr))
6170       return Op;
6171   } else {
6172     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
6173                           IsGFX10 ? &DLC : nullptr))
6174       return Op;
6175   }
6176 
6177   SmallVector<SDValue, 26> Ops;
6178   if (BaseOpcode->Store || BaseOpcode->Atomic)
6179     Ops.push_back(VData); // vdata
6180   if (UseNSA) {
6181     for (const SDValue &Addr : VAddrs)
6182       Ops.push_back(Addr);
6183   } else {
6184     Ops.push_back(VAddr);
6185   }
6186   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
6187   if (BaseOpcode->Sampler)
6188     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
6189   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6190   if (IsGFX10)
6191     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6192   Ops.push_back(Unorm);
6193   if (IsGFX10)
6194     Ops.push_back(DLC);
6195   Ops.push_back(GLC);
6196   Ops.push_back(SLC);
6197   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6198                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6199   if (IsGFX10)
6200     Ops.push_back(IsA16 ? True : False);
6201   Ops.push_back(TFE);
6202   Ops.push_back(LWE);
6203   if (!IsGFX10)
6204     Ops.push_back(DimInfo->DA ? True : False);
6205   if (BaseOpcode->HasD16)
6206     Ops.push_back(IsD16 ? True : False);
6207   if (isa<MemSDNode>(Op))
6208     Ops.push_back(Op.getOperand(0)); // chain
6209 
6210   int NumVAddrDwords =
6211       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6212   int Opcode = -1;
6213 
6214   if (IsGFX10) {
6215     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6216                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6217                                           : AMDGPU::MIMGEncGfx10Default,
6218                                    NumVDataDwords, NumVAddrDwords);
6219   } else {
6220     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6221       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6222                                      NumVDataDwords, NumVAddrDwords);
6223     if (Opcode == -1)
6224       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6225                                      NumVDataDwords, NumVAddrDwords);
6226   }
6227   assert(Opcode != -1);
6228 
6229   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6230   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6231     MachineMemOperand *MemRef = MemOp->getMemOperand();
6232     DAG.setNodeMemRefs(NewNode, {MemRef});
6233   }
6234 
6235   if (BaseOpcode->AtomicX2) {
6236     SmallVector<SDValue, 1> Elt;
6237     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6238     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6239   } else if (!BaseOpcode->Store) {
6240     return constructRetValue(DAG, NewNode,
6241                              OrigResultTypes, IsTexFail,
6242                              Subtarget->hasUnpackedD16VMem(), IsD16,
6243                              DMaskLanes, NumVDataDwords, DL,
6244                              *DAG.getContext());
6245   }
6246 
6247   return SDValue(NewNode, 0);
6248 }
6249 
6250 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6251                                        SDValue Offset, SDValue CachePolicy,
6252                                        SelectionDAG &DAG) const {
6253   MachineFunction &MF = DAG.getMachineFunction();
6254 
6255   const DataLayout &DataLayout = DAG.getDataLayout();
6256   Align Alignment =
6257       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6258 
6259   MachineMemOperand *MMO = MF.getMachineMemOperand(
6260       MachinePointerInfo(),
6261       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6262           MachineMemOperand::MOInvariant,
6263       VT.getStoreSize(), Alignment);
6264 
6265   if (!Offset->isDivergent()) {
6266     SDValue Ops[] = {
6267         Rsrc,
6268         Offset, // Offset
6269         CachePolicy
6270     };
6271 
6272     // Widen vec3 load to vec4.
6273     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6274       EVT WidenedVT =
6275           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6276       auto WidenedOp = DAG.getMemIntrinsicNode(
6277           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6278           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6279       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6280                                    DAG.getVectorIdxConstant(0, DL));
6281       return Subvector;
6282     }
6283 
6284     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6285                                    DAG.getVTList(VT), Ops, VT, MMO);
6286   }
6287 
6288   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6289   // assume that the buffer is unswizzled.
6290   SmallVector<SDValue, 4> Loads;
6291   unsigned NumLoads = 1;
6292   MVT LoadVT = VT.getSimpleVT();
6293   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6294   assert((LoadVT.getScalarType() == MVT::i32 ||
6295           LoadVT.getScalarType() == MVT::f32));
6296 
6297   if (NumElts == 8 || NumElts == 16) {
6298     NumLoads = NumElts / 4;
6299     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6300   }
6301 
6302   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6303   SDValue Ops[] = {
6304       DAG.getEntryNode(),                               // Chain
6305       Rsrc,                                             // rsrc
6306       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6307       {},                                               // voffset
6308       {},                                               // soffset
6309       {},                                               // offset
6310       CachePolicy,                                      // cachepolicy
6311       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6312   };
6313 
6314   // Use the alignment to ensure that the required offsets will fit into the
6315   // immediate offsets.
6316   setBufferOffsets(Offset, DAG, &Ops[3],
6317                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6318 
6319   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6320   for (unsigned i = 0; i < NumLoads; ++i) {
6321     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6322     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6323                                         LoadVT, MMO, DAG));
6324   }
6325 
6326   if (NumElts == 8 || NumElts == 16)
6327     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6328 
6329   return Loads[0];
6330 }
6331 
6332 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6333                                                   SelectionDAG &DAG) const {
6334   MachineFunction &MF = DAG.getMachineFunction();
6335   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6336 
6337   EVT VT = Op.getValueType();
6338   SDLoc DL(Op);
6339   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6340 
6341   // TODO: Should this propagate fast-math-flags?
6342 
6343   switch (IntrinsicID) {
6344   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6345     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6346       return emitNonHSAIntrinsicError(DAG, DL, VT);
6347     return getPreloadedValue(DAG, *MFI, VT,
6348                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6349   }
6350   case Intrinsic::amdgcn_dispatch_ptr:
6351   case Intrinsic::amdgcn_queue_ptr: {
6352     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6353       DiagnosticInfoUnsupported BadIntrin(
6354           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6355           DL.getDebugLoc());
6356       DAG.getContext()->diagnose(BadIntrin);
6357       return DAG.getUNDEF(VT);
6358     }
6359 
6360     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6361       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6362     return getPreloadedValue(DAG, *MFI, VT, RegID);
6363   }
6364   case Intrinsic::amdgcn_implicitarg_ptr: {
6365     if (MFI->isEntryFunction())
6366       return getImplicitArgPtr(DAG, DL);
6367     return getPreloadedValue(DAG, *MFI, VT,
6368                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6369   }
6370   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6371     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6372       // This only makes sense to call in a kernel, so just lower to null.
6373       return DAG.getConstant(0, DL, VT);
6374     }
6375 
6376     return getPreloadedValue(DAG, *MFI, VT,
6377                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6378   }
6379   case Intrinsic::amdgcn_dispatch_id: {
6380     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6381   }
6382   case Intrinsic::amdgcn_rcp:
6383     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6384   case Intrinsic::amdgcn_rsq:
6385     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6386   case Intrinsic::amdgcn_rsq_legacy:
6387     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6388       return emitRemovedIntrinsicError(DAG, DL, VT);
6389     return SDValue();
6390   case Intrinsic::amdgcn_rcp_legacy:
6391     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6392       return emitRemovedIntrinsicError(DAG, DL, VT);
6393     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6394   case Intrinsic::amdgcn_rsq_clamp: {
6395     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6396       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6397 
6398     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6399     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6400     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6401 
6402     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6403     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6404                               DAG.getConstantFP(Max, DL, VT));
6405     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6406                        DAG.getConstantFP(Min, DL, VT));
6407   }
6408   case Intrinsic::r600_read_ngroups_x:
6409     if (Subtarget->isAmdHsaOS())
6410       return emitNonHSAIntrinsicError(DAG, DL, VT);
6411 
6412     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6413                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6414                                     false);
6415   case Intrinsic::r600_read_ngroups_y:
6416     if (Subtarget->isAmdHsaOS())
6417       return emitNonHSAIntrinsicError(DAG, DL, VT);
6418 
6419     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6420                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6421                                     false);
6422   case Intrinsic::r600_read_ngroups_z:
6423     if (Subtarget->isAmdHsaOS())
6424       return emitNonHSAIntrinsicError(DAG, DL, VT);
6425 
6426     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6427                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6428                                     false);
6429   case Intrinsic::r600_read_global_size_x:
6430     if (Subtarget->isAmdHsaOS())
6431       return emitNonHSAIntrinsicError(DAG, DL, VT);
6432 
6433     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6434                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6435                                     Align(4), false);
6436   case Intrinsic::r600_read_global_size_y:
6437     if (Subtarget->isAmdHsaOS())
6438       return emitNonHSAIntrinsicError(DAG, DL, VT);
6439 
6440     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6441                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6442                                     Align(4), false);
6443   case Intrinsic::r600_read_global_size_z:
6444     if (Subtarget->isAmdHsaOS())
6445       return emitNonHSAIntrinsicError(DAG, DL, VT);
6446 
6447     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6448                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6449                                     Align(4), false);
6450   case Intrinsic::r600_read_local_size_x:
6451     if (Subtarget->isAmdHsaOS())
6452       return emitNonHSAIntrinsicError(DAG, DL, VT);
6453 
6454     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6455                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6456   case Intrinsic::r600_read_local_size_y:
6457     if (Subtarget->isAmdHsaOS())
6458       return emitNonHSAIntrinsicError(DAG, DL, VT);
6459 
6460     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6461                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6462   case Intrinsic::r600_read_local_size_z:
6463     if (Subtarget->isAmdHsaOS())
6464       return emitNonHSAIntrinsicError(DAG, DL, VT);
6465 
6466     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6467                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6468   case Intrinsic::amdgcn_workgroup_id_x:
6469     return getPreloadedValue(DAG, *MFI, VT,
6470                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6471   case Intrinsic::amdgcn_workgroup_id_y:
6472     return getPreloadedValue(DAG, *MFI, VT,
6473                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6474   case Intrinsic::amdgcn_workgroup_id_z:
6475     return getPreloadedValue(DAG, *MFI, VT,
6476                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6477   case Intrinsic::amdgcn_workitem_id_x:
6478     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6479                           SDLoc(DAG.getEntryNode()),
6480                           MFI->getArgInfo().WorkItemIDX);
6481   case Intrinsic::amdgcn_workitem_id_y:
6482     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6483                           SDLoc(DAG.getEntryNode()),
6484                           MFI->getArgInfo().WorkItemIDY);
6485   case Intrinsic::amdgcn_workitem_id_z:
6486     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6487                           SDLoc(DAG.getEntryNode()),
6488                           MFI->getArgInfo().WorkItemIDZ);
6489   case Intrinsic::amdgcn_wavefrontsize:
6490     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6491                            SDLoc(Op), MVT::i32);
6492   case Intrinsic::amdgcn_s_buffer_load: {
6493     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6494     SDValue GLC;
6495     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6496     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6497                           IsGFX10 ? &DLC : nullptr))
6498       return Op;
6499     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6500                         DAG);
6501   }
6502   case Intrinsic::amdgcn_fdiv_fast:
6503     return lowerFDIV_FAST(Op, DAG);
6504   case Intrinsic::amdgcn_sin:
6505     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6506 
6507   case Intrinsic::amdgcn_cos:
6508     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6509 
6510   case Intrinsic::amdgcn_mul_u24:
6511     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6512   case Intrinsic::amdgcn_mul_i24:
6513     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6514 
6515   case Intrinsic::amdgcn_log_clamp: {
6516     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6517       return SDValue();
6518 
6519     DiagnosticInfoUnsupported BadIntrin(
6520       MF.getFunction(), "intrinsic not supported on subtarget",
6521       DL.getDebugLoc());
6522       DAG.getContext()->diagnose(BadIntrin);
6523       return DAG.getUNDEF(VT);
6524   }
6525   case Intrinsic::amdgcn_ldexp:
6526     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6527                        Op.getOperand(1), Op.getOperand(2));
6528 
6529   case Intrinsic::amdgcn_fract:
6530     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6531 
6532   case Intrinsic::amdgcn_class:
6533     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6534                        Op.getOperand(1), Op.getOperand(2));
6535   case Intrinsic::amdgcn_div_fmas:
6536     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6537                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6538                        Op.getOperand(4));
6539 
6540   case Intrinsic::amdgcn_div_fixup:
6541     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6542                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6543 
6544   case Intrinsic::amdgcn_div_scale: {
6545     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6546 
6547     // Translate to the operands expected by the machine instruction. The
6548     // first parameter must be the same as the first instruction.
6549     SDValue Numerator = Op.getOperand(1);
6550     SDValue Denominator = Op.getOperand(2);
6551 
6552     // Note this order is opposite of the machine instruction's operations,
6553     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6554     // intrinsic has the numerator as the first operand to match a normal
6555     // division operation.
6556 
6557     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6558 
6559     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6560                        Denominator, Numerator);
6561   }
6562   case Intrinsic::amdgcn_icmp: {
6563     // There is a Pat that handles this variant, so return it as-is.
6564     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6565         Op.getConstantOperandVal(2) == 0 &&
6566         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6567       return Op;
6568     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6569   }
6570   case Intrinsic::amdgcn_fcmp: {
6571     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6572   }
6573   case Intrinsic::amdgcn_ballot:
6574     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6575   case Intrinsic::amdgcn_fmed3:
6576     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6577                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6578   case Intrinsic::amdgcn_fdot2:
6579     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6580                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6581                        Op.getOperand(4));
6582   case Intrinsic::amdgcn_fmul_legacy:
6583     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6584                        Op.getOperand(1), Op.getOperand(2));
6585   case Intrinsic::amdgcn_sffbh:
6586     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6587   case Intrinsic::amdgcn_sbfe:
6588     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6589                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6590   case Intrinsic::amdgcn_ubfe:
6591     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6592                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6593   case Intrinsic::amdgcn_cvt_pkrtz:
6594   case Intrinsic::amdgcn_cvt_pknorm_i16:
6595   case Intrinsic::amdgcn_cvt_pknorm_u16:
6596   case Intrinsic::amdgcn_cvt_pk_i16:
6597   case Intrinsic::amdgcn_cvt_pk_u16: {
6598     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6599     EVT VT = Op.getValueType();
6600     unsigned Opcode;
6601 
6602     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6603       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6604     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6605       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6606     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6607       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6608     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6609       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6610     else
6611       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6612 
6613     if (isTypeLegal(VT))
6614       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6615 
6616     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6617                                Op.getOperand(1), Op.getOperand(2));
6618     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6619   }
6620   case Intrinsic::amdgcn_fmad_ftz:
6621     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6622                        Op.getOperand(2), Op.getOperand(3));
6623 
6624   case Intrinsic::amdgcn_if_break:
6625     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6626                                       Op->getOperand(1), Op->getOperand(2)), 0);
6627 
6628   case Intrinsic::amdgcn_groupstaticsize: {
6629     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6630     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6631       return Op;
6632 
6633     const Module *M = MF.getFunction().getParent();
6634     const GlobalValue *GV =
6635         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6636     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6637                                             SIInstrInfo::MO_ABS32_LO);
6638     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6639   }
6640   case Intrinsic::amdgcn_is_shared:
6641   case Intrinsic::amdgcn_is_private: {
6642     SDLoc SL(Op);
6643     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6644       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6645     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6646     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6647                                  Op.getOperand(1));
6648 
6649     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6650                                 DAG.getConstant(1, SL, MVT::i32));
6651     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6652   }
6653   case Intrinsic::amdgcn_alignbit:
6654     return DAG.getNode(ISD::FSHR, DL, VT,
6655                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6656   case Intrinsic::amdgcn_reloc_constant: {
6657     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6658     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6659     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6660     auto RelocSymbol = cast<GlobalVariable>(
6661         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6662     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6663                                             SIInstrInfo::MO_ABS32_LO);
6664     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6665   }
6666   default:
6667     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6668             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6669       return lowerImage(Op, ImageDimIntr, DAG);
6670 
6671     return Op;
6672   }
6673 }
6674 
6675 // This function computes an appropriate offset to pass to
6676 // MachineMemOperand::setOffset() based on the offset inputs to
6677 // an intrinsic.  If any of the offsets are non-contstant or
6678 // if VIndex is non-zero then this function returns 0.  Otherwise,
6679 // it returns the sum of VOffset, SOffset, and Offset.
6680 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6681                                       SDValue SOffset,
6682                                       SDValue Offset,
6683                                       SDValue VIndex = SDValue()) {
6684 
6685   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6686       !isa<ConstantSDNode>(Offset))
6687     return 0;
6688 
6689   if (VIndex) {
6690     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6691       return 0;
6692   }
6693 
6694   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6695          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6696          cast<ConstantSDNode>(Offset)->getSExtValue();
6697 }
6698 
6699 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6700                                                      SelectionDAG &DAG,
6701                                                      unsigned NewOpcode) const {
6702   SDLoc DL(Op);
6703 
6704   SDValue VData = Op.getOperand(2);
6705   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6706   SDValue Ops[] = {
6707     Op.getOperand(0), // Chain
6708     VData,            // vdata
6709     Op.getOperand(3), // rsrc
6710     DAG.getConstant(0, DL, MVT::i32), // vindex
6711     Offsets.first,    // voffset
6712     Op.getOperand(5), // soffset
6713     Offsets.second,   // offset
6714     Op.getOperand(6), // cachepolicy
6715     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6716   };
6717 
6718   auto *M = cast<MemSDNode>(Op);
6719   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6720 
6721   EVT MemVT = VData.getValueType();
6722   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6723                                  M->getMemOperand());
6724 }
6725 
6726 SDValue
6727 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6728                                                 unsigned NewOpcode) const {
6729   SDLoc DL(Op);
6730 
6731   SDValue VData = Op.getOperand(2);
6732   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6733   SDValue Ops[] = {
6734     Op.getOperand(0), // Chain
6735     VData,            // vdata
6736     Op.getOperand(3), // rsrc
6737     Op.getOperand(4), // vindex
6738     Offsets.first,    // voffset
6739     Op.getOperand(6), // soffset
6740     Offsets.second,   // offset
6741     Op.getOperand(7), // cachepolicy
6742     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6743   };
6744 
6745   auto *M = cast<MemSDNode>(Op);
6746   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6747                                                       Ops[3]));
6748 
6749   EVT MemVT = VData.getValueType();
6750   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6751                                  M->getMemOperand());
6752 }
6753 
6754 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6755                                                  SelectionDAG &DAG) const {
6756   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6757   SDLoc DL(Op);
6758 
6759   switch (IntrID) {
6760   case Intrinsic::amdgcn_ds_ordered_add:
6761   case Intrinsic::amdgcn_ds_ordered_swap: {
6762     MemSDNode *M = cast<MemSDNode>(Op);
6763     SDValue Chain = M->getOperand(0);
6764     SDValue M0 = M->getOperand(2);
6765     SDValue Value = M->getOperand(3);
6766     unsigned IndexOperand = M->getConstantOperandVal(7);
6767     unsigned WaveRelease = M->getConstantOperandVal(8);
6768     unsigned WaveDone = M->getConstantOperandVal(9);
6769 
6770     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6771     IndexOperand &= ~0x3f;
6772     unsigned CountDw = 0;
6773 
6774     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6775       CountDw = (IndexOperand >> 24) & 0xf;
6776       IndexOperand &= ~(0xf << 24);
6777 
6778       if (CountDw < 1 || CountDw > 4) {
6779         report_fatal_error(
6780             "ds_ordered_count: dword count must be between 1 and 4");
6781       }
6782     }
6783 
6784     if (IndexOperand)
6785       report_fatal_error("ds_ordered_count: bad index operand");
6786 
6787     if (WaveDone && !WaveRelease)
6788       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6789 
6790     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6791     unsigned ShaderType =
6792         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6793     unsigned Offset0 = OrderedCountIndex << 2;
6794     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6795                        (Instruction << 4);
6796 
6797     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6798       Offset1 |= (CountDw - 1) << 6;
6799 
6800     unsigned Offset = Offset0 | (Offset1 << 8);
6801 
6802     SDValue Ops[] = {
6803       Chain,
6804       Value,
6805       DAG.getTargetConstant(Offset, DL, MVT::i16),
6806       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6807     };
6808     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6809                                    M->getVTList(), Ops, M->getMemoryVT(),
6810                                    M->getMemOperand());
6811   }
6812   case Intrinsic::amdgcn_ds_fadd: {
6813     MemSDNode *M = cast<MemSDNode>(Op);
6814     unsigned Opc;
6815     switch (IntrID) {
6816     case Intrinsic::amdgcn_ds_fadd:
6817       Opc = ISD::ATOMIC_LOAD_FADD;
6818       break;
6819     }
6820 
6821     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6822                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6823                          M->getMemOperand());
6824   }
6825   case Intrinsic::amdgcn_atomic_inc:
6826   case Intrinsic::amdgcn_atomic_dec:
6827   case Intrinsic::amdgcn_ds_fmin:
6828   case Intrinsic::amdgcn_ds_fmax: {
6829     MemSDNode *M = cast<MemSDNode>(Op);
6830     unsigned Opc;
6831     switch (IntrID) {
6832     case Intrinsic::amdgcn_atomic_inc:
6833       Opc = AMDGPUISD::ATOMIC_INC;
6834       break;
6835     case Intrinsic::amdgcn_atomic_dec:
6836       Opc = AMDGPUISD::ATOMIC_DEC;
6837       break;
6838     case Intrinsic::amdgcn_ds_fmin:
6839       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6840       break;
6841     case Intrinsic::amdgcn_ds_fmax:
6842       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6843       break;
6844     default:
6845       llvm_unreachable("Unknown intrinsic!");
6846     }
6847     SDValue Ops[] = {
6848       M->getOperand(0), // Chain
6849       M->getOperand(2), // Ptr
6850       M->getOperand(3)  // Value
6851     };
6852 
6853     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6854                                    M->getMemoryVT(), M->getMemOperand());
6855   }
6856   case Intrinsic::amdgcn_buffer_load:
6857   case Intrinsic::amdgcn_buffer_load_format: {
6858     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6859     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6860     unsigned IdxEn = 1;
6861     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6862       IdxEn = Idx->getZExtValue() != 0;
6863     SDValue Ops[] = {
6864       Op.getOperand(0), // Chain
6865       Op.getOperand(2), // rsrc
6866       Op.getOperand(3), // vindex
6867       SDValue(),        // voffset -- will be set by setBufferOffsets
6868       SDValue(),        // soffset -- will be set by setBufferOffsets
6869       SDValue(),        // offset -- will be set by setBufferOffsets
6870       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6871       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6872     };
6873 
6874     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6875     // We don't know the offset if vindex is non-zero, so clear it.
6876     if (IdxEn)
6877       Offset = 0;
6878 
6879     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6880         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6881 
6882     EVT VT = Op.getValueType();
6883     EVT IntVT = VT.changeTypeToInteger();
6884     auto *M = cast<MemSDNode>(Op);
6885     M->getMemOperand()->setOffset(Offset);
6886     EVT LoadVT = Op.getValueType();
6887 
6888     if (LoadVT.getScalarType() == MVT::f16)
6889       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6890                                  M, DAG, Ops);
6891 
6892     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6893     if (LoadVT.getScalarType() == MVT::i8 ||
6894         LoadVT.getScalarType() == MVT::i16)
6895       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6896 
6897     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6898                                M->getMemOperand(), DAG);
6899   }
6900   case Intrinsic::amdgcn_raw_buffer_load:
6901   case Intrinsic::amdgcn_raw_buffer_load_format: {
6902     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6903 
6904     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6905     SDValue Ops[] = {
6906       Op.getOperand(0), // Chain
6907       Op.getOperand(2), // rsrc
6908       DAG.getConstant(0, DL, MVT::i32), // vindex
6909       Offsets.first,    // voffset
6910       Op.getOperand(4), // soffset
6911       Offsets.second,   // offset
6912       Op.getOperand(5), // cachepolicy, swizzled buffer
6913       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6914     };
6915 
6916     auto *M = cast<MemSDNode>(Op);
6917     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6918     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6919   }
6920   case Intrinsic::amdgcn_struct_buffer_load:
6921   case Intrinsic::amdgcn_struct_buffer_load_format: {
6922     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6923 
6924     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6925     SDValue Ops[] = {
6926       Op.getOperand(0), // Chain
6927       Op.getOperand(2), // rsrc
6928       Op.getOperand(3), // vindex
6929       Offsets.first,    // voffset
6930       Op.getOperand(5), // soffset
6931       Offsets.second,   // offset
6932       Op.getOperand(6), // cachepolicy, swizzled buffer
6933       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6934     };
6935 
6936     auto *M = cast<MemSDNode>(Op);
6937     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6938                                                         Ops[2]));
6939     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6940   }
6941   case Intrinsic::amdgcn_tbuffer_load: {
6942     MemSDNode *M = cast<MemSDNode>(Op);
6943     EVT LoadVT = Op.getValueType();
6944 
6945     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6946     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6947     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6948     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6949     unsigned IdxEn = 1;
6950     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6951       IdxEn = Idx->getZExtValue() != 0;
6952     SDValue Ops[] = {
6953       Op.getOperand(0),  // Chain
6954       Op.getOperand(2),  // rsrc
6955       Op.getOperand(3),  // vindex
6956       Op.getOperand(4),  // voffset
6957       Op.getOperand(5),  // soffset
6958       Op.getOperand(6),  // offset
6959       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6960       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6961       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6962     };
6963 
6964     if (LoadVT.getScalarType() == MVT::f16)
6965       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6966                                  M, DAG, Ops);
6967     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6968                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6969                                DAG);
6970   }
6971   case Intrinsic::amdgcn_raw_tbuffer_load: {
6972     MemSDNode *M = cast<MemSDNode>(Op);
6973     EVT LoadVT = Op.getValueType();
6974     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6975 
6976     SDValue Ops[] = {
6977       Op.getOperand(0),  // Chain
6978       Op.getOperand(2),  // rsrc
6979       DAG.getConstant(0, DL, MVT::i32), // vindex
6980       Offsets.first,     // voffset
6981       Op.getOperand(4),  // soffset
6982       Offsets.second,    // offset
6983       Op.getOperand(5),  // format
6984       Op.getOperand(6),  // cachepolicy, swizzled buffer
6985       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6986     };
6987 
6988     if (LoadVT.getScalarType() == MVT::f16)
6989       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6990                                  M, DAG, Ops);
6991     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6992                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6993                                DAG);
6994   }
6995   case Intrinsic::amdgcn_struct_tbuffer_load: {
6996     MemSDNode *M = cast<MemSDNode>(Op);
6997     EVT LoadVT = Op.getValueType();
6998     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6999 
7000     SDValue Ops[] = {
7001       Op.getOperand(0),  // Chain
7002       Op.getOperand(2),  // rsrc
7003       Op.getOperand(3),  // vindex
7004       Offsets.first,     // voffset
7005       Op.getOperand(5),  // soffset
7006       Offsets.second,    // offset
7007       Op.getOperand(6),  // format
7008       Op.getOperand(7),  // cachepolicy, swizzled buffer
7009       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7010     };
7011 
7012     if (LoadVT.getScalarType() == MVT::f16)
7013       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7014                                  M, DAG, Ops);
7015     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7016                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7017                                DAG);
7018   }
7019   case Intrinsic::amdgcn_buffer_atomic_swap:
7020   case Intrinsic::amdgcn_buffer_atomic_add:
7021   case Intrinsic::amdgcn_buffer_atomic_sub:
7022   case Intrinsic::amdgcn_buffer_atomic_csub:
7023   case Intrinsic::amdgcn_buffer_atomic_smin:
7024   case Intrinsic::amdgcn_buffer_atomic_umin:
7025   case Intrinsic::amdgcn_buffer_atomic_smax:
7026   case Intrinsic::amdgcn_buffer_atomic_umax:
7027   case Intrinsic::amdgcn_buffer_atomic_and:
7028   case Intrinsic::amdgcn_buffer_atomic_or:
7029   case Intrinsic::amdgcn_buffer_atomic_xor: {
7030     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7031     unsigned IdxEn = 1;
7032     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7033       IdxEn = Idx->getZExtValue() != 0;
7034     SDValue Ops[] = {
7035       Op.getOperand(0), // Chain
7036       Op.getOperand(2), // vdata
7037       Op.getOperand(3), // rsrc
7038       Op.getOperand(4), // vindex
7039       SDValue(),        // voffset -- will be set by setBufferOffsets
7040       SDValue(),        // soffset -- will be set by setBufferOffsets
7041       SDValue(),        // offset -- will be set by setBufferOffsets
7042       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7043       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7044     };
7045     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7046     // We don't know the offset if vindex is non-zero, so clear it.
7047     if (IdxEn)
7048       Offset = 0;
7049     EVT VT = Op.getValueType();
7050 
7051     auto *M = cast<MemSDNode>(Op);
7052     M->getMemOperand()->setOffset(Offset);
7053     unsigned Opcode = 0;
7054 
7055     switch (IntrID) {
7056     case Intrinsic::amdgcn_buffer_atomic_swap:
7057       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7058       break;
7059     case Intrinsic::amdgcn_buffer_atomic_add:
7060       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7061       break;
7062     case Intrinsic::amdgcn_buffer_atomic_sub:
7063       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7064       break;
7065     case Intrinsic::amdgcn_buffer_atomic_csub:
7066       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7067       break;
7068     case Intrinsic::amdgcn_buffer_atomic_smin:
7069       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7070       break;
7071     case Intrinsic::amdgcn_buffer_atomic_umin:
7072       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7073       break;
7074     case Intrinsic::amdgcn_buffer_atomic_smax:
7075       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7076       break;
7077     case Intrinsic::amdgcn_buffer_atomic_umax:
7078       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7079       break;
7080     case Intrinsic::amdgcn_buffer_atomic_and:
7081       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7082       break;
7083     case Intrinsic::amdgcn_buffer_atomic_or:
7084       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7085       break;
7086     case Intrinsic::amdgcn_buffer_atomic_xor:
7087       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7088       break;
7089     default:
7090       llvm_unreachable("unhandled atomic opcode");
7091     }
7092 
7093     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7094                                    M->getMemOperand());
7095   }
7096   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7097     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7098   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7099     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7100   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7101     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7102   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7103     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7104   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7105     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7106   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7107     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7108   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7109     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7110   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7111     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7112   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7113     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7114   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7115     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7116   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7117     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7118   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7119     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7120   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7121     return lowerStructBufferAtomicIntrin(Op, DAG,
7122                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7123   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7124     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7125   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7126     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7127   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7128     return lowerStructBufferAtomicIntrin(Op, DAG,
7129                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7130   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7131     return lowerStructBufferAtomicIntrin(Op, DAG,
7132                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7133   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7134     return lowerStructBufferAtomicIntrin(Op, DAG,
7135                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7136   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7137     return lowerStructBufferAtomicIntrin(Op, DAG,
7138                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7139   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7140     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7141   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7142     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7143   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7144     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7145   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7146     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7147   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7148     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7149 
7150   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7151     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7152     unsigned IdxEn = 1;
7153     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7154       IdxEn = Idx->getZExtValue() != 0;
7155     SDValue Ops[] = {
7156       Op.getOperand(0), // Chain
7157       Op.getOperand(2), // src
7158       Op.getOperand(3), // cmp
7159       Op.getOperand(4), // rsrc
7160       Op.getOperand(5), // vindex
7161       SDValue(),        // voffset -- will be set by setBufferOffsets
7162       SDValue(),        // soffset -- will be set by setBufferOffsets
7163       SDValue(),        // offset -- will be set by setBufferOffsets
7164       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7165       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7166     };
7167     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7168     // We don't know the offset if vindex is non-zero, so clear it.
7169     if (IdxEn)
7170       Offset = 0;
7171     EVT VT = Op.getValueType();
7172     auto *M = cast<MemSDNode>(Op);
7173     M->getMemOperand()->setOffset(Offset);
7174 
7175     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7176                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7177   }
7178   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7179     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7180     SDValue Ops[] = {
7181       Op.getOperand(0), // Chain
7182       Op.getOperand(2), // src
7183       Op.getOperand(3), // cmp
7184       Op.getOperand(4), // rsrc
7185       DAG.getConstant(0, DL, MVT::i32), // vindex
7186       Offsets.first,    // voffset
7187       Op.getOperand(6), // soffset
7188       Offsets.second,   // offset
7189       Op.getOperand(7), // cachepolicy
7190       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7191     };
7192     EVT VT = Op.getValueType();
7193     auto *M = cast<MemSDNode>(Op);
7194     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7195 
7196     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7197                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7198   }
7199   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7200     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7201     SDValue Ops[] = {
7202       Op.getOperand(0), // Chain
7203       Op.getOperand(2), // src
7204       Op.getOperand(3), // cmp
7205       Op.getOperand(4), // rsrc
7206       Op.getOperand(5), // vindex
7207       Offsets.first,    // voffset
7208       Op.getOperand(7), // soffset
7209       Offsets.second,   // offset
7210       Op.getOperand(8), // cachepolicy
7211       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7212     };
7213     EVT VT = Op.getValueType();
7214     auto *M = cast<MemSDNode>(Op);
7215     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7216                                                         Ops[4]));
7217 
7218     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7219                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7220   }
7221   default:
7222     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7223             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7224       return lowerImage(Op, ImageDimIntr, DAG);
7225 
7226     return SDValue();
7227   }
7228 }
7229 
7230 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7231 // dwordx4 if on SI.
7232 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7233                                               SDVTList VTList,
7234                                               ArrayRef<SDValue> Ops, EVT MemVT,
7235                                               MachineMemOperand *MMO,
7236                                               SelectionDAG &DAG) const {
7237   EVT VT = VTList.VTs[0];
7238   EVT WidenedVT = VT;
7239   EVT WidenedMemVT = MemVT;
7240   if (!Subtarget->hasDwordx3LoadStores() &&
7241       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7242     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7243                                  WidenedVT.getVectorElementType(), 4);
7244     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7245                                     WidenedMemVT.getVectorElementType(), 4);
7246     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7247   }
7248 
7249   assert(VTList.NumVTs == 2);
7250   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7251 
7252   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7253                                        WidenedMemVT, MMO);
7254   if (WidenedVT != VT) {
7255     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7256                                DAG.getVectorIdxConstant(0, DL));
7257     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7258   }
7259   return NewOp;
7260 }
7261 
7262 SDValue SITargetLowering::handleD16VData(SDValue VData,
7263                                          SelectionDAG &DAG) const {
7264   EVT StoreVT = VData.getValueType();
7265 
7266   // No change for f16 and legal vector D16 types.
7267   if (!StoreVT.isVector())
7268     return VData;
7269 
7270   SDLoc DL(VData);
7271   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
7272 
7273   if (Subtarget->hasUnpackedD16VMem()) {
7274     // We need to unpack the packed data to store.
7275     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7276     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7277 
7278     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
7279                                         StoreVT.getVectorNumElements());
7280     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7281     return DAG.UnrollVectorOp(ZExt.getNode());
7282   }
7283 
7284   assert(isTypeLegal(StoreVT));
7285   return VData;
7286 }
7287 
7288 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7289                                               SelectionDAG &DAG) const {
7290   SDLoc DL(Op);
7291   SDValue Chain = Op.getOperand(0);
7292   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7293   MachineFunction &MF = DAG.getMachineFunction();
7294 
7295   switch (IntrinsicID) {
7296   case Intrinsic::amdgcn_exp_compr: {
7297     SDValue Src0 = Op.getOperand(4);
7298     SDValue Src1 = Op.getOperand(5);
7299     // Hack around illegal type on SI by directly selecting it.
7300     if (isTypeLegal(Src0.getValueType()))
7301       return SDValue();
7302 
7303     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7304     SDValue Undef = DAG.getUNDEF(MVT::f32);
7305     const SDValue Ops[] = {
7306       Op.getOperand(2), // tgt
7307       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7308       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7309       Undef, // src2
7310       Undef, // src3
7311       Op.getOperand(7), // vm
7312       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7313       Op.getOperand(3), // en
7314       Op.getOperand(0) // Chain
7315     };
7316 
7317     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7318     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7319   }
7320   case Intrinsic::amdgcn_s_barrier: {
7321     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7322       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7323       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7324       if (WGSize <= ST.getWavefrontSize())
7325         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7326                                           Op.getOperand(0)), 0);
7327     }
7328     return SDValue();
7329   };
7330   case Intrinsic::amdgcn_tbuffer_store: {
7331     SDValue VData = Op.getOperand(2);
7332     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7333     if (IsD16)
7334       VData = handleD16VData(VData, DAG);
7335     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7336     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7337     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7338     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7339     unsigned IdxEn = 1;
7340     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7341       IdxEn = Idx->getZExtValue() != 0;
7342     SDValue Ops[] = {
7343       Chain,
7344       VData,             // vdata
7345       Op.getOperand(3),  // rsrc
7346       Op.getOperand(4),  // vindex
7347       Op.getOperand(5),  // voffset
7348       Op.getOperand(6),  // soffset
7349       Op.getOperand(7),  // offset
7350       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7351       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7352       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7353     };
7354     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7355                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7356     MemSDNode *M = cast<MemSDNode>(Op);
7357     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7358                                    M->getMemoryVT(), M->getMemOperand());
7359   }
7360 
7361   case Intrinsic::amdgcn_struct_tbuffer_store: {
7362     SDValue VData = Op.getOperand(2);
7363     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7364     if (IsD16)
7365       VData = handleD16VData(VData, DAG);
7366     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7367     SDValue Ops[] = {
7368       Chain,
7369       VData,             // vdata
7370       Op.getOperand(3),  // rsrc
7371       Op.getOperand(4),  // vindex
7372       Offsets.first,     // voffset
7373       Op.getOperand(6),  // soffset
7374       Offsets.second,    // offset
7375       Op.getOperand(7),  // format
7376       Op.getOperand(8),  // cachepolicy, swizzled buffer
7377       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7378     };
7379     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7380                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7381     MemSDNode *M = cast<MemSDNode>(Op);
7382     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7383                                    M->getMemoryVT(), M->getMemOperand());
7384   }
7385 
7386   case Intrinsic::amdgcn_raw_tbuffer_store: {
7387     SDValue VData = Op.getOperand(2);
7388     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7389     if (IsD16)
7390       VData = handleD16VData(VData, DAG);
7391     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7392     SDValue Ops[] = {
7393       Chain,
7394       VData,             // vdata
7395       Op.getOperand(3),  // rsrc
7396       DAG.getConstant(0, DL, MVT::i32), // vindex
7397       Offsets.first,     // voffset
7398       Op.getOperand(5),  // soffset
7399       Offsets.second,    // offset
7400       Op.getOperand(6),  // format
7401       Op.getOperand(7),  // cachepolicy, swizzled buffer
7402       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7403     };
7404     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7405                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7406     MemSDNode *M = cast<MemSDNode>(Op);
7407     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7408                                    M->getMemoryVT(), M->getMemOperand());
7409   }
7410 
7411   case Intrinsic::amdgcn_buffer_store:
7412   case Intrinsic::amdgcn_buffer_store_format: {
7413     SDValue VData = Op.getOperand(2);
7414     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7415     if (IsD16)
7416       VData = handleD16VData(VData, DAG);
7417     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7418     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7419     unsigned IdxEn = 1;
7420     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7421       IdxEn = Idx->getZExtValue() != 0;
7422     SDValue Ops[] = {
7423       Chain,
7424       VData,
7425       Op.getOperand(3), // rsrc
7426       Op.getOperand(4), // vindex
7427       SDValue(), // voffset -- will be set by setBufferOffsets
7428       SDValue(), // soffset -- will be set by setBufferOffsets
7429       SDValue(), // offset -- will be set by setBufferOffsets
7430       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7431       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7432     };
7433     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7434     // We don't know the offset if vindex is non-zero, so clear it.
7435     if (IdxEn)
7436       Offset = 0;
7437     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7438                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7439     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7440     MemSDNode *M = cast<MemSDNode>(Op);
7441     M->getMemOperand()->setOffset(Offset);
7442 
7443     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7444     EVT VDataType = VData.getValueType().getScalarType();
7445     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7446       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7447 
7448     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7449                                    M->getMemoryVT(), M->getMemOperand());
7450   }
7451 
7452   case Intrinsic::amdgcn_raw_buffer_store:
7453   case Intrinsic::amdgcn_raw_buffer_store_format: {
7454     const bool IsFormat =
7455         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7456 
7457     SDValue VData = Op.getOperand(2);
7458     EVT VDataVT = VData.getValueType();
7459     EVT EltType = VDataVT.getScalarType();
7460     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7461     if (IsD16)
7462       VData = handleD16VData(VData, DAG);
7463 
7464     if (!isTypeLegal(VDataVT)) {
7465       VData =
7466           DAG.getNode(ISD::BITCAST, DL,
7467                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7468     }
7469 
7470     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7471     SDValue Ops[] = {
7472       Chain,
7473       VData,
7474       Op.getOperand(3), // rsrc
7475       DAG.getConstant(0, DL, MVT::i32), // vindex
7476       Offsets.first,    // voffset
7477       Op.getOperand(5), // soffset
7478       Offsets.second,   // offset
7479       Op.getOperand(6), // cachepolicy, swizzled buffer
7480       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7481     };
7482     unsigned Opc =
7483         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7484     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7485     MemSDNode *M = cast<MemSDNode>(Op);
7486     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7487 
7488     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7489     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7490       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7491 
7492     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7493                                    M->getMemoryVT(), M->getMemOperand());
7494   }
7495 
7496   case Intrinsic::amdgcn_struct_buffer_store:
7497   case Intrinsic::amdgcn_struct_buffer_store_format: {
7498     const bool IsFormat =
7499         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7500 
7501     SDValue VData = Op.getOperand(2);
7502     EVT VDataVT = VData.getValueType();
7503     EVT EltType = VDataVT.getScalarType();
7504     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7505 
7506     if (IsD16)
7507       VData = handleD16VData(VData, DAG);
7508 
7509     if (!isTypeLegal(VDataVT)) {
7510       VData =
7511           DAG.getNode(ISD::BITCAST, DL,
7512                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7513     }
7514 
7515     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7516     SDValue Ops[] = {
7517       Chain,
7518       VData,
7519       Op.getOperand(3), // rsrc
7520       Op.getOperand(4), // vindex
7521       Offsets.first,    // voffset
7522       Op.getOperand(6), // soffset
7523       Offsets.second,   // offset
7524       Op.getOperand(7), // cachepolicy, swizzled buffer
7525       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7526     };
7527     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7528                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7529     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7530     MemSDNode *M = cast<MemSDNode>(Op);
7531     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7532                                                         Ops[3]));
7533 
7534     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7535     EVT VDataType = VData.getValueType().getScalarType();
7536     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7537       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7538 
7539     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7540                                    M->getMemoryVT(), M->getMemOperand());
7541   }
7542   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7543     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7544   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7545     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7546   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7547     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7548     unsigned IdxEn = 1;
7549     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7550       IdxEn = Idx->getZExtValue() != 0;
7551     SDValue Ops[] = {
7552       Chain,
7553       Op.getOperand(2), // vdata
7554       Op.getOperand(3), // rsrc
7555       Op.getOperand(4), // vindex
7556       SDValue(),        // voffset -- will be set by setBufferOffsets
7557       SDValue(),        // soffset -- will be set by setBufferOffsets
7558       SDValue(),        // offset -- will be set by setBufferOffsets
7559       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7560       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7561     };
7562     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7563     // We don't know the offset if vindex is non-zero, so clear it.
7564     if (IdxEn)
7565       Offset = 0;
7566     EVT VT = Op.getOperand(2).getValueType();
7567 
7568     auto *M = cast<MemSDNode>(Op);
7569     M->getMemOperand()->setOffset(Offset);
7570 
7571     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_FADD, DL,
7572                                    Op->getVTList(), Ops, VT,
7573                                    M->getMemOperand());
7574   }
7575   case Intrinsic::amdgcn_end_cf:
7576     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7577                                       Op->getOperand(2), Chain), 0);
7578 
7579   default: {
7580     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7581             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7582       return lowerImage(Op, ImageDimIntr, DAG);
7583 
7584     return Op;
7585   }
7586   }
7587 }
7588 
7589 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7590 // offset (the offset that is included in bounds checking and swizzling, to be
7591 // split between the instruction's voffset and immoffset fields) and soffset
7592 // (the offset that is excluded from bounds checking and swizzling, to go in
7593 // the instruction's soffset field).  This function takes the first kind of
7594 // offset and figures out how to split it between voffset and immoffset.
7595 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7596     SDValue Offset, SelectionDAG &DAG) const {
7597   SDLoc DL(Offset);
7598   const unsigned MaxImm = 4095;
7599   SDValue N0 = Offset;
7600   ConstantSDNode *C1 = nullptr;
7601 
7602   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7603     N0 = SDValue();
7604   else if (DAG.isBaseWithConstantOffset(N0)) {
7605     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7606     N0 = N0.getOperand(0);
7607   }
7608 
7609   if (C1) {
7610     unsigned ImmOffset = C1->getZExtValue();
7611     // If the immediate value is too big for the immoffset field, put the value
7612     // and -4096 into the immoffset field so that the value that is copied/added
7613     // for the voffset field is a multiple of 4096, and it stands more chance
7614     // of being CSEd with the copy/add for another similar load/store.
7615     // However, do not do that rounding down to a multiple of 4096 if that is a
7616     // negative number, as it appears to be illegal to have a negative offset
7617     // in the vgpr, even if adding the immediate offset makes it positive.
7618     unsigned Overflow = ImmOffset & ~MaxImm;
7619     ImmOffset -= Overflow;
7620     if ((int32_t)Overflow < 0) {
7621       Overflow += ImmOffset;
7622       ImmOffset = 0;
7623     }
7624     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7625     if (Overflow) {
7626       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7627       if (!N0)
7628         N0 = OverflowVal;
7629       else {
7630         SDValue Ops[] = { N0, OverflowVal };
7631         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7632       }
7633     }
7634   }
7635   if (!N0)
7636     N0 = DAG.getConstant(0, DL, MVT::i32);
7637   if (!C1)
7638     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7639   return {N0, SDValue(C1, 0)};
7640 }
7641 
7642 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7643 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7644 // pointed to by Offsets.
7645 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7646                                             SelectionDAG &DAG, SDValue *Offsets,
7647                                             Align Alignment) const {
7648   SDLoc DL(CombinedOffset);
7649   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7650     uint32_t Imm = C->getZExtValue();
7651     uint32_t SOffset, ImmOffset;
7652     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7653                                  Alignment)) {
7654       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7655       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7656       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7657       return SOffset + ImmOffset;
7658     }
7659   }
7660   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7661     SDValue N0 = CombinedOffset.getOperand(0);
7662     SDValue N1 = CombinedOffset.getOperand(1);
7663     uint32_t SOffset, ImmOffset;
7664     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7665     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7666                                                 Subtarget, Alignment)) {
7667       Offsets[0] = N0;
7668       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7669       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7670       return 0;
7671     }
7672   }
7673   Offsets[0] = CombinedOffset;
7674   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7675   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7676   return 0;
7677 }
7678 
7679 // Handle 8 bit and 16 bit buffer loads
7680 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7681                                                      EVT LoadVT, SDLoc DL,
7682                                                      ArrayRef<SDValue> Ops,
7683                                                      MemSDNode *M) const {
7684   EVT IntVT = LoadVT.changeTypeToInteger();
7685   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7686          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7687 
7688   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7689   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7690                                                Ops, IntVT,
7691                                                M->getMemOperand());
7692   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7693   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7694 
7695   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7696 }
7697 
7698 // Handle 8 bit and 16 bit buffer stores
7699 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7700                                                       EVT VDataType, SDLoc DL,
7701                                                       SDValue Ops[],
7702                                                       MemSDNode *M) const {
7703   if (VDataType == MVT::f16)
7704     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7705 
7706   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7707   Ops[1] = BufferStoreExt;
7708   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7709                                  AMDGPUISD::BUFFER_STORE_SHORT;
7710   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7711   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7712                                      M->getMemOperand());
7713 }
7714 
7715 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7716                                  ISD::LoadExtType ExtType, SDValue Op,
7717                                  const SDLoc &SL, EVT VT) {
7718   if (VT.bitsLT(Op.getValueType()))
7719     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7720 
7721   switch (ExtType) {
7722   case ISD::SEXTLOAD:
7723     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7724   case ISD::ZEXTLOAD:
7725     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7726   case ISD::EXTLOAD:
7727     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7728   case ISD::NON_EXTLOAD:
7729     return Op;
7730   }
7731 
7732   llvm_unreachable("invalid ext type");
7733 }
7734 
7735 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7736   SelectionDAG &DAG = DCI.DAG;
7737   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7738     return SDValue();
7739 
7740   // FIXME: Constant loads should all be marked invariant.
7741   unsigned AS = Ld->getAddressSpace();
7742   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7743       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7744       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7745     return SDValue();
7746 
7747   // Don't do this early, since it may interfere with adjacent load merging for
7748   // illegal types. We can avoid losing alignment information for exotic types
7749   // pre-legalize.
7750   EVT MemVT = Ld->getMemoryVT();
7751   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7752       MemVT.getSizeInBits() >= 32)
7753     return SDValue();
7754 
7755   SDLoc SL(Ld);
7756 
7757   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7758          "unexpected vector extload");
7759 
7760   // TODO: Drop only high part of range.
7761   SDValue Ptr = Ld->getBasePtr();
7762   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7763                                 MVT::i32, SL, Ld->getChain(), Ptr,
7764                                 Ld->getOffset(),
7765                                 Ld->getPointerInfo(), MVT::i32,
7766                                 Ld->getAlignment(),
7767                                 Ld->getMemOperand()->getFlags(),
7768                                 Ld->getAAInfo(),
7769                                 nullptr); // Drop ranges
7770 
7771   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7772   if (MemVT.isFloatingPoint()) {
7773     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7774            "unexpected fp extload");
7775     TruncVT = MemVT.changeTypeToInteger();
7776   }
7777 
7778   SDValue Cvt = NewLoad;
7779   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7780     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7781                       DAG.getValueType(TruncVT));
7782   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7783              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7784     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7785   } else {
7786     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7787   }
7788 
7789   EVT VT = Ld->getValueType(0);
7790   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7791 
7792   DCI.AddToWorklist(Cvt.getNode());
7793 
7794   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7795   // the appropriate extension from the 32-bit load.
7796   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7797   DCI.AddToWorklist(Cvt.getNode());
7798 
7799   // Handle conversion back to floating point if necessary.
7800   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7801 
7802   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7803 }
7804 
7805 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7806   SDLoc DL(Op);
7807   LoadSDNode *Load = cast<LoadSDNode>(Op);
7808   ISD::LoadExtType ExtType = Load->getExtensionType();
7809   EVT MemVT = Load->getMemoryVT();
7810 
7811   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7812     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7813       return SDValue();
7814 
7815     // FIXME: Copied from PPC
7816     // First, load into 32 bits, then truncate to 1 bit.
7817 
7818     SDValue Chain = Load->getChain();
7819     SDValue BasePtr = Load->getBasePtr();
7820     MachineMemOperand *MMO = Load->getMemOperand();
7821 
7822     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7823 
7824     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7825                                    BasePtr, RealMemVT, MMO);
7826 
7827     if (!MemVT.isVector()) {
7828       SDValue Ops[] = {
7829         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7830         NewLD.getValue(1)
7831       };
7832 
7833       return DAG.getMergeValues(Ops, DL);
7834     }
7835 
7836     SmallVector<SDValue, 3> Elts;
7837     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7838       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7839                                 DAG.getConstant(I, DL, MVT::i32));
7840 
7841       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7842     }
7843 
7844     SDValue Ops[] = {
7845       DAG.getBuildVector(MemVT, DL, Elts),
7846       NewLD.getValue(1)
7847     };
7848 
7849     return DAG.getMergeValues(Ops, DL);
7850   }
7851 
7852   if (!MemVT.isVector())
7853     return SDValue();
7854 
7855   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7856          "Custom lowering for non-i32 vectors hasn't been implemented.");
7857 
7858   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7859                                       MemVT, *Load->getMemOperand())) {
7860     SDValue Ops[2];
7861     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7862     return DAG.getMergeValues(Ops, DL);
7863   }
7864 
7865   unsigned Alignment = Load->getAlignment();
7866   unsigned AS = Load->getAddressSpace();
7867   if (Subtarget->hasLDSMisalignedBug() &&
7868       AS == AMDGPUAS::FLAT_ADDRESS &&
7869       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7870     return SplitVectorLoad(Op, DAG);
7871   }
7872 
7873   MachineFunction &MF = DAG.getMachineFunction();
7874   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7875   // If there is a possibilty that flat instruction access scratch memory
7876   // then we need to use the same legalization rules we use for private.
7877   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7878       !Subtarget->hasMultiDwordFlatScratchAddressing())
7879     AS = MFI->hasFlatScratchInit() ?
7880          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7881 
7882   unsigned NumElements = MemVT.getVectorNumElements();
7883 
7884   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7885       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7886     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7887       if (MemVT.isPow2VectorType())
7888         return SDValue();
7889       if (NumElements == 3)
7890         return WidenVectorLoad(Op, DAG);
7891       return SplitVectorLoad(Op, DAG);
7892     }
7893     // Non-uniform loads will be selected to MUBUF instructions, so they
7894     // have the same legalization requirements as global and private
7895     // loads.
7896     //
7897   }
7898 
7899   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7900       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7901       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7902     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7903         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7904         Alignment >= 4 && NumElements < 32) {
7905       if (MemVT.isPow2VectorType())
7906         return SDValue();
7907       if (NumElements == 3)
7908         return WidenVectorLoad(Op, DAG);
7909       return SplitVectorLoad(Op, DAG);
7910     }
7911     // Non-uniform loads will be selected to MUBUF instructions, so they
7912     // have the same legalization requirements as global and private
7913     // loads.
7914     //
7915   }
7916   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7917       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7918       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7919       AS == AMDGPUAS::FLAT_ADDRESS) {
7920     if (NumElements > 4)
7921       return SplitVectorLoad(Op, DAG);
7922     // v3 loads not supported on SI.
7923     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7924       return WidenVectorLoad(Op, DAG);
7925     // v3 and v4 loads are supported for private and global memory.
7926     return SDValue();
7927   }
7928   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7929     // Depending on the setting of the private_element_size field in the
7930     // resource descriptor, we can only make private accesses up to a certain
7931     // size.
7932     switch (Subtarget->getMaxPrivateElementSize()) {
7933     case 4: {
7934       SDValue Ops[2];
7935       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7936       return DAG.getMergeValues(Ops, DL);
7937     }
7938     case 8:
7939       if (NumElements > 2)
7940         return SplitVectorLoad(Op, DAG);
7941       return SDValue();
7942     case 16:
7943       // Same as global/flat
7944       if (NumElements > 4)
7945         return SplitVectorLoad(Op, DAG);
7946       // v3 loads not supported on SI.
7947       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7948         return WidenVectorLoad(Op, DAG);
7949       return SDValue();
7950     default:
7951       llvm_unreachable("unsupported private_element_size");
7952     }
7953   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7954     // Use ds_read_b128 or ds_read_b96 when possible.
7955     if (Subtarget->hasDS96AndDS128() &&
7956         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
7957          MemVT.getStoreSize() == 12) &&
7958         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
7959                                            Load->getAlign()))
7960       return SDValue();
7961 
7962     if (NumElements > 2)
7963       return SplitVectorLoad(Op, DAG);
7964 
7965     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7966     // address is negative, then the instruction is incorrectly treated as
7967     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7968     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7969     // load later in the SILoadStoreOptimizer.
7970     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7971         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7972         Load->getAlignment() < 8) {
7973       return SplitVectorLoad(Op, DAG);
7974     }
7975   }
7976   return SDValue();
7977 }
7978 
7979 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7980   EVT VT = Op.getValueType();
7981   assert(VT.getSizeInBits() == 64);
7982 
7983   SDLoc DL(Op);
7984   SDValue Cond = Op.getOperand(0);
7985 
7986   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7987   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7988 
7989   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7990   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7991 
7992   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7993   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7994 
7995   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7996 
7997   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7998   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7999 
8000   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8001 
8002   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8003   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8004 }
8005 
8006 // Catch division cases where we can use shortcuts with rcp and rsq
8007 // instructions.
8008 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8009                                               SelectionDAG &DAG) const {
8010   SDLoc SL(Op);
8011   SDValue LHS = Op.getOperand(0);
8012   SDValue RHS = Op.getOperand(1);
8013   EVT VT = Op.getValueType();
8014   const SDNodeFlags Flags = Op->getFlags();
8015 
8016   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
8017                             Flags.hasApproximateFuncs();
8018 
8019   // Without !fpmath accuracy information, we can't do more because we don't
8020   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8021   if (!AllowInaccurateRcp)
8022     return SDValue();
8023 
8024   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8025     if (CLHS->isExactlyValue(1.0)) {
8026       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8027       // the CI documentation has a worst case error of 1 ulp.
8028       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8029       // use it as long as we aren't trying to use denormals.
8030       //
8031       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8032 
8033       // 1.0 / sqrt(x) -> rsq(x)
8034 
8035       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8036       // error seems really high at 2^29 ULP.
8037       if (RHS.getOpcode() == ISD::FSQRT)
8038         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8039 
8040       // 1.0 / x -> rcp(x)
8041       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8042     }
8043 
8044     // Same as for 1.0, but expand the sign out of the constant.
8045     if (CLHS->isExactlyValue(-1.0)) {
8046       // -1.0 / x -> rcp (fneg x)
8047       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8048       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8049     }
8050   }
8051 
8052   // Turn into multiply by the reciprocal.
8053   // x / y -> x * (1.0 / y)
8054   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8055   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8056 }
8057 
8058 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8059                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8060                           SDNodeFlags Flags) {
8061   if (GlueChain->getNumValues() <= 1) {
8062     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8063   }
8064 
8065   assert(GlueChain->getNumValues() == 3);
8066 
8067   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8068   switch (Opcode) {
8069   default: llvm_unreachable("no chain equivalent for opcode");
8070   case ISD::FMUL:
8071     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8072     break;
8073   }
8074 
8075   return DAG.getNode(Opcode, SL, VTList,
8076                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8077                      Flags);
8078 }
8079 
8080 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8081                            EVT VT, SDValue A, SDValue B, SDValue C,
8082                            SDValue GlueChain, SDNodeFlags Flags) {
8083   if (GlueChain->getNumValues() <= 1) {
8084     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8085   }
8086 
8087   assert(GlueChain->getNumValues() == 3);
8088 
8089   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8090   switch (Opcode) {
8091   default: llvm_unreachable("no chain equivalent for opcode");
8092   case ISD::FMA:
8093     Opcode = AMDGPUISD::FMA_W_CHAIN;
8094     break;
8095   }
8096 
8097   return DAG.getNode(Opcode, SL, VTList,
8098                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8099                      Flags);
8100 }
8101 
8102 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8103   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8104     return FastLowered;
8105 
8106   SDLoc SL(Op);
8107   SDValue Src0 = Op.getOperand(0);
8108   SDValue Src1 = Op.getOperand(1);
8109 
8110   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8111   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8112 
8113   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8114   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8115 
8116   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8117   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8118 
8119   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8120 }
8121 
8122 // Faster 2.5 ULP division that does not support denormals.
8123 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8124   SDLoc SL(Op);
8125   SDValue LHS = Op.getOperand(1);
8126   SDValue RHS = Op.getOperand(2);
8127 
8128   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8129 
8130   const APFloat K0Val(BitsToFloat(0x6f800000));
8131   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8132 
8133   const APFloat K1Val(BitsToFloat(0x2f800000));
8134   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8135 
8136   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8137 
8138   EVT SetCCVT =
8139     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8140 
8141   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8142 
8143   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8144 
8145   // TODO: Should this propagate fast-math-flags?
8146   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8147 
8148   // rcp does not support denormals.
8149   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8150 
8151   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8152 
8153   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8154 }
8155 
8156 // Returns immediate value for setting the F32 denorm mode when using the
8157 // S_DENORM_MODE instruction.
8158 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8159                                           const SDLoc &SL, const GCNSubtarget *ST) {
8160   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8161   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8162                                 ? FP_DENORM_FLUSH_NONE
8163                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8164 
8165   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8166   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8167 }
8168 
8169 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8170   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8171     return FastLowered;
8172 
8173   // The selection matcher assumes anything with a chain selecting to a
8174   // mayRaiseFPException machine instruction. Since we're introducing a chain
8175   // here, we need to explicitly report nofpexcept for the regular fdiv
8176   // lowering.
8177   SDNodeFlags Flags = Op->getFlags();
8178   Flags.setNoFPExcept(true);
8179 
8180   SDLoc SL(Op);
8181   SDValue LHS = Op.getOperand(0);
8182   SDValue RHS = Op.getOperand(1);
8183 
8184   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8185 
8186   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8187 
8188   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8189                                           {RHS, RHS, LHS}, Flags);
8190   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8191                                         {LHS, RHS, LHS}, Flags);
8192 
8193   // Denominator is scaled to not be denormal, so using rcp is ok.
8194   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8195                                   DenominatorScaled, Flags);
8196   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8197                                      DenominatorScaled, Flags);
8198 
8199   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8200                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8201                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8202   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8203 
8204   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8205 
8206   if (!HasFP32Denormals) {
8207     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8208     // lowering. The chain dependence is insufficient, and we need glue. We do
8209     // not need the glue variants in a strictfp function.
8210 
8211     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8212 
8213     SDNode *EnableDenorm;
8214     if (Subtarget->hasDenormModeInst()) {
8215       const SDValue EnableDenormValue =
8216           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8217 
8218       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8219                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8220     } else {
8221       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8222                                                         SL, MVT::i32);
8223       EnableDenorm =
8224           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8225                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8226     }
8227 
8228     SDValue Ops[3] = {
8229       NegDivScale0,
8230       SDValue(EnableDenorm, 0),
8231       SDValue(EnableDenorm, 1)
8232     };
8233 
8234     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8235   }
8236 
8237   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8238                              ApproxRcp, One, NegDivScale0, Flags);
8239 
8240   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8241                              ApproxRcp, Fma0, Flags);
8242 
8243   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8244                            Fma1, Fma1, Flags);
8245 
8246   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8247                              NumeratorScaled, Mul, Flags);
8248 
8249   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8250                              Fma2, Fma1, Mul, Fma2, Flags);
8251 
8252   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8253                              NumeratorScaled, Fma3, Flags);
8254 
8255   if (!HasFP32Denormals) {
8256     SDNode *DisableDenorm;
8257     if (Subtarget->hasDenormModeInst()) {
8258       const SDValue DisableDenormValue =
8259           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8260 
8261       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8262                                   Fma4.getValue(1), DisableDenormValue,
8263                                   Fma4.getValue(2)).getNode();
8264     } else {
8265       const SDValue DisableDenormValue =
8266           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8267 
8268       DisableDenorm = DAG.getMachineNode(
8269           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8270           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8271     }
8272 
8273     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8274                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8275     DAG.setRoot(OutputChain);
8276   }
8277 
8278   SDValue Scale = NumeratorScaled.getValue(1);
8279   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8280                              {Fma4, Fma1, Fma3, Scale}, Flags);
8281 
8282   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8283 }
8284 
8285 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8286   if (DAG.getTarget().Options.UnsafeFPMath)
8287     return lowerFastUnsafeFDIV(Op, DAG);
8288 
8289   SDLoc SL(Op);
8290   SDValue X = Op.getOperand(0);
8291   SDValue Y = Op.getOperand(1);
8292 
8293   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8294 
8295   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8296 
8297   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8298 
8299   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8300 
8301   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8302 
8303   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8304 
8305   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8306 
8307   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8308 
8309   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8310 
8311   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8312   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8313 
8314   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8315                              NegDivScale0, Mul, DivScale1);
8316 
8317   SDValue Scale;
8318 
8319   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8320     // Workaround a hardware bug on SI where the condition output from div_scale
8321     // is not usable.
8322 
8323     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8324 
8325     // Figure out if the scale to use for div_fmas.
8326     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8327     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8328     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8329     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8330 
8331     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8332     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8333 
8334     SDValue Scale0Hi
8335       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8336     SDValue Scale1Hi
8337       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8338 
8339     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8340     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8341     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8342   } else {
8343     Scale = DivScale1.getValue(1);
8344   }
8345 
8346   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8347                              Fma4, Fma3, Mul, Scale);
8348 
8349   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8350 }
8351 
8352 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8353   EVT VT = Op.getValueType();
8354 
8355   if (VT == MVT::f32)
8356     return LowerFDIV32(Op, DAG);
8357 
8358   if (VT == MVT::f64)
8359     return LowerFDIV64(Op, DAG);
8360 
8361   if (VT == MVT::f16)
8362     return LowerFDIV16(Op, DAG);
8363 
8364   llvm_unreachable("Unexpected type for fdiv");
8365 }
8366 
8367 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8368   SDLoc DL(Op);
8369   StoreSDNode *Store = cast<StoreSDNode>(Op);
8370   EVT VT = Store->getMemoryVT();
8371 
8372   if (VT == MVT::i1) {
8373     return DAG.getTruncStore(Store->getChain(), DL,
8374        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8375        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8376   }
8377 
8378   assert(VT.isVector() &&
8379          Store->getValue().getValueType().getScalarType() == MVT::i32);
8380 
8381   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8382                                       VT, *Store->getMemOperand())) {
8383     return expandUnalignedStore(Store, DAG);
8384   }
8385 
8386   unsigned AS = Store->getAddressSpace();
8387   if (Subtarget->hasLDSMisalignedBug() &&
8388       AS == AMDGPUAS::FLAT_ADDRESS &&
8389       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8390     return SplitVectorStore(Op, DAG);
8391   }
8392 
8393   MachineFunction &MF = DAG.getMachineFunction();
8394   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8395   // If there is a possibilty that flat instruction access scratch memory
8396   // then we need to use the same legalization rules we use for private.
8397   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8398       !Subtarget->hasMultiDwordFlatScratchAddressing())
8399     AS = MFI->hasFlatScratchInit() ?
8400          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8401 
8402   unsigned NumElements = VT.getVectorNumElements();
8403   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8404       AS == AMDGPUAS::FLAT_ADDRESS) {
8405     if (NumElements > 4)
8406       return SplitVectorStore(Op, DAG);
8407     // v3 stores not supported on SI.
8408     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8409       return SplitVectorStore(Op, DAG);
8410     return SDValue();
8411   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8412     switch (Subtarget->getMaxPrivateElementSize()) {
8413     case 4:
8414       return scalarizeVectorStore(Store, DAG);
8415     case 8:
8416       if (NumElements > 2)
8417         return SplitVectorStore(Op, DAG);
8418       return SDValue();
8419     case 16:
8420       if (NumElements > 4 || NumElements == 3)
8421         return SplitVectorStore(Op, DAG);
8422       return SDValue();
8423     default:
8424       llvm_unreachable("unsupported private_element_size");
8425     }
8426   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8427     // Use ds_write_b128 or ds_write_b96 when possible.
8428     if (Subtarget->hasDS96AndDS128() &&
8429         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8430          (VT.getStoreSize() == 12)) &&
8431         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8432                                            Store->getAlign()))
8433       return SDValue();
8434 
8435     if (NumElements > 2)
8436       return SplitVectorStore(Op, DAG);
8437 
8438     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8439     // address is negative, then the instruction is incorrectly treated as
8440     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8441     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8442     // store later in the SILoadStoreOptimizer.
8443     if (!Subtarget->hasUsableDSOffset() &&
8444         NumElements == 2 && VT.getStoreSize() == 8 &&
8445         Store->getAlignment() < 8) {
8446       return SplitVectorStore(Op, DAG);
8447     }
8448 
8449     return SDValue();
8450   } else {
8451     llvm_unreachable("unhandled address space");
8452   }
8453 }
8454 
8455 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8456   SDLoc DL(Op);
8457   EVT VT = Op.getValueType();
8458   SDValue Arg = Op.getOperand(0);
8459   SDValue TrigVal;
8460 
8461   // Propagate fast-math flags so that the multiply we introduce can be folded
8462   // if Arg is already the result of a multiply by constant.
8463   auto Flags = Op->getFlags();
8464 
8465   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8466 
8467   if (Subtarget->hasTrigReducedRange()) {
8468     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8469     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8470   } else {
8471     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8472   }
8473 
8474   switch (Op.getOpcode()) {
8475   case ISD::FCOS:
8476     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8477   case ISD::FSIN:
8478     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8479   default:
8480     llvm_unreachable("Wrong trig opcode");
8481   }
8482 }
8483 
8484 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8485   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8486   assert(AtomicNode->isCompareAndSwap());
8487   unsigned AS = AtomicNode->getAddressSpace();
8488 
8489   // No custom lowering required for local address space
8490   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8491     return Op;
8492 
8493   // Non-local address space requires custom lowering for atomic compare
8494   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8495   SDLoc DL(Op);
8496   SDValue ChainIn = Op.getOperand(0);
8497   SDValue Addr = Op.getOperand(1);
8498   SDValue Old = Op.getOperand(2);
8499   SDValue New = Op.getOperand(3);
8500   EVT VT = Op.getValueType();
8501   MVT SimpleVT = VT.getSimpleVT();
8502   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8503 
8504   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8505   SDValue Ops[] = { ChainIn, Addr, NewOld };
8506 
8507   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8508                                  Ops, VT, AtomicNode->getMemOperand());
8509 }
8510 
8511 //===----------------------------------------------------------------------===//
8512 // Custom DAG optimizations
8513 //===----------------------------------------------------------------------===//
8514 
8515 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8516                                                      DAGCombinerInfo &DCI) const {
8517   EVT VT = N->getValueType(0);
8518   EVT ScalarVT = VT.getScalarType();
8519   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8520     return SDValue();
8521 
8522   SelectionDAG &DAG = DCI.DAG;
8523   SDLoc DL(N);
8524 
8525   SDValue Src = N->getOperand(0);
8526   EVT SrcVT = Src.getValueType();
8527 
8528   // TODO: We could try to match extracting the higher bytes, which would be
8529   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8530   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8531   // about in practice.
8532   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8533     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8534       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8535       DCI.AddToWorklist(Cvt.getNode());
8536 
8537       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8538       if (ScalarVT != MVT::f32) {
8539         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8540                           DAG.getTargetConstant(0, DL, MVT::i32));
8541       }
8542       return Cvt;
8543     }
8544   }
8545 
8546   return SDValue();
8547 }
8548 
8549 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8550 
8551 // This is a variant of
8552 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8553 //
8554 // The normal DAG combiner will do this, but only if the add has one use since
8555 // that would increase the number of instructions.
8556 //
8557 // This prevents us from seeing a constant offset that can be folded into a
8558 // memory instruction's addressing mode. If we know the resulting add offset of
8559 // a pointer can be folded into an addressing offset, we can replace the pointer
8560 // operand with the add of new constant offset. This eliminates one of the uses,
8561 // and may allow the remaining use to also be simplified.
8562 //
8563 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8564                                                unsigned AddrSpace,
8565                                                EVT MemVT,
8566                                                DAGCombinerInfo &DCI) const {
8567   SDValue N0 = N->getOperand(0);
8568   SDValue N1 = N->getOperand(1);
8569 
8570   // We only do this to handle cases where it's profitable when there are
8571   // multiple uses of the add, so defer to the standard combine.
8572   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8573       N0->hasOneUse())
8574     return SDValue();
8575 
8576   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8577   if (!CN1)
8578     return SDValue();
8579 
8580   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8581   if (!CAdd)
8582     return SDValue();
8583 
8584   // If the resulting offset is too large, we can't fold it into the addressing
8585   // mode offset.
8586   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8587   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8588 
8589   AddrMode AM;
8590   AM.HasBaseReg = true;
8591   AM.BaseOffs = Offset.getSExtValue();
8592   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8593     return SDValue();
8594 
8595   SelectionDAG &DAG = DCI.DAG;
8596   SDLoc SL(N);
8597   EVT VT = N->getValueType(0);
8598 
8599   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8600   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8601 
8602   SDNodeFlags Flags;
8603   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8604                           (N0.getOpcode() == ISD::OR ||
8605                            N0->getFlags().hasNoUnsignedWrap()));
8606 
8607   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8608 }
8609 
8610 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8611 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8612 /// specific intrinsic, but they all place the pointer operand first.
8613 static unsigned getBasePtrIndex(const MemSDNode *N) {
8614   switch (N->getOpcode()) {
8615   case ISD::STORE:
8616   case ISD::INTRINSIC_W_CHAIN:
8617   case ISD::INTRINSIC_VOID:
8618     return 2;
8619   default:
8620     return 1;
8621   }
8622 }
8623 
8624 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8625                                                   DAGCombinerInfo &DCI) const {
8626   SelectionDAG &DAG = DCI.DAG;
8627   SDLoc SL(N);
8628 
8629   unsigned PtrIdx = getBasePtrIndex(N);
8630   SDValue Ptr = N->getOperand(PtrIdx);
8631 
8632   // TODO: We could also do this for multiplies.
8633   if (Ptr.getOpcode() == ISD::SHL) {
8634     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8635                                           N->getMemoryVT(), DCI);
8636     if (NewPtr) {
8637       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8638 
8639       NewOps[PtrIdx] = NewPtr;
8640       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8641     }
8642   }
8643 
8644   return SDValue();
8645 }
8646 
8647 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8648   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8649          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8650          (Opc == ISD::XOR && Val == 0);
8651 }
8652 
8653 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8654 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8655 // integer combine opportunities since most 64-bit operations are decomposed
8656 // this way.  TODO: We won't want this for SALU especially if it is an inline
8657 // immediate.
8658 SDValue SITargetLowering::splitBinaryBitConstantOp(
8659   DAGCombinerInfo &DCI,
8660   const SDLoc &SL,
8661   unsigned Opc, SDValue LHS,
8662   const ConstantSDNode *CRHS) const {
8663   uint64_t Val = CRHS->getZExtValue();
8664   uint32_t ValLo = Lo_32(Val);
8665   uint32_t ValHi = Hi_32(Val);
8666   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8667 
8668     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8669          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8670         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8671     // If we need to materialize a 64-bit immediate, it will be split up later
8672     // anyway. Avoid creating the harder to understand 64-bit immediate
8673     // materialization.
8674     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8675   }
8676 
8677   return SDValue();
8678 }
8679 
8680 // Returns true if argument is a boolean value which is not serialized into
8681 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8682 static bool isBoolSGPR(SDValue V) {
8683   if (V.getValueType() != MVT::i1)
8684     return false;
8685   switch (V.getOpcode()) {
8686   default: break;
8687   case ISD::SETCC:
8688   case ISD::AND:
8689   case ISD::OR:
8690   case ISD::XOR:
8691   case AMDGPUISD::FP_CLASS:
8692     return true;
8693   }
8694   return false;
8695 }
8696 
8697 // If a constant has all zeroes or all ones within each byte return it.
8698 // Otherwise return 0.
8699 static uint32_t getConstantPermuteMask(uint32_t C) {
8700   // 0xff for any zero byte in the mask
8701   uint32_t ZeroByteMask = 0;
8702   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8703   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8704   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8705   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8706   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8707   if ((NonZeroByteMask & C) != NonZeroByteMask)
8708     return 0; // Partial bytes selected.
8709   return C;
8710 }
8711 
8712 // Check if a node selects whole bytes from its operand 0 starting at a byte
8713 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8714 // or -1 if not succeeded.
8715 // Note byte select encoding:
8716 // value 0-3 selects corresponding source byte;
8717 // value 0xc selects zero;
8718 // value 0xff selects 0xff.
8719 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8720   assert(V.getValueSizeInBits() == 32);
8721 
8722   if (V.getNumOperands() != 2)
8723     return ~0;
8724 
8725   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8726   if (!N1)
8727     return ~0;
8728 
8729   uint32_t C = N1->getZExtValue();
8730 
8731   switch (V.getOpcode()) {
8732   default:
8733     break;
8734   case ISD::AND:
8735     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8736       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8737     }
8738     break;
8739 
8740   case ISD::OR:
8741     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8742       return (0x03020100 & ~ConstMask) | ConstMask;
8743     }
8744     break;
8745 
8746   case ISD::SHL:
8747     if (C % 8)
8748       return ~0;
8749 
8750     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8751 
8752   case ISD::SRL:
8753     if (C % 8)
8754       return ~0;
8755 
8756     return uint32_t(0x0c0c0c0c03020100ull >> C);
8757   }
8758 
8759   return ~0;
8760 }
8761 
8762 SDValue SITargetLowering::performAndCombine(SDNode *N,
8763                                             DAGCombinerInfo &DCI) const {
8764   if (DCI.isBeforeLegalize())
8765     return SDValue();
8766 
8767   SelectionDAG &DAG = DCI.DAG;
8768   EVT VT = N->getValueType(0);
8769   SDValue LHS = N->getOperand(0);
8770   SDValue RHS = N->getOperand(1);
8771 
8772 
8773   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8774   if (VT == MVT::i64 && CRHS) {
8775     if (SDValue Split
8776         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8777       return Split;
8778   }
8779 
8780   if (CRHS && VT == MVT::i32) {
8781     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8782     // nb = number of trailing zeroes in mask
8783     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8784     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8785     uint64_t Mask = CRHS->getZExtValue();
8786     unsigned Bits = countPopulation(Mask);
8787     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8788         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8789       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8790         unsigned Shift = CShift->getZExtValue();
8791         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8792         unsigned Offset = NB + Shift;
8793         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8794           SDLoc SL(N);
8795           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8796                                     LHS->getOperand(0),
8797                                     DAG.getConstant(Offset, SL, MVT::i32),
8798                                     DAG.getConstant(Bits, SL, MVT::i32));
8799           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8800           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8801                                     DAG.getValueType(NarrowVT));
8802           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8803                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8804           return Shl;
8805         }
8806       }
8807     }
8808 
8809     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8810     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8811         isa<ConstantSDNode>(LHS.getOperand(2))) {
8812       uint32_t Sel = getConstantPermuteMask(Mask);
8813       if (!Sel)
8814         return SDValue();
8815 
8816       // Select 0xc for all zero bytes
8817       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8818       SDLoc DL(N);
8819       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8820                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8821     }
8822   }
8823 
8824   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8825   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8826   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8827     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8828     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8829 
8830     SDValue X = LHS.getOperand(0);
8831     SDValue Y = RHS.getOperand(0);
8832     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8833       return SDValue();
8834 
8835     if (LCC == ISD::SETO) {
8836       if (X != LHS.getOperand(1))
8837         return SDValue();
8838 
8839       if (RCC == ISD::SETUNE) {
8840         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8841         if (!C1 || !C1->isInfinity() || C1->isNegative())
8842           return SDValue();
8843 
8844         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8845                               SIInstrFlags::N_SUBNORMAL |
8846                               SIInstrFlags::N_ZERO |
8847                               SIInstrFlags::P_ZERO |
8848                               SIInstrFlags::P_SUBNORMAL |
8849                               SIInstrFlags::P_NORMAL;
8850 
8851         static_assert(((~(SIInstrFlags::S_NAN |
8852                           SIInstrFlags::Q_NAN |
8853                           SIInstrFlags::N_INFINITY |
8854                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8855                       "mask not equal");
8856 
8857         SDLoc DL(N);
8858         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8859                            X, DAG.getConstant(Mask, DL, MVT::i32));
8860       }
8861     }
8862   }
8863 
8864   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8865     std::swap(LHS, RHS);
8866 
8867   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8868       RHS.hasOneUse()) {
8869     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8870     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8871     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8872     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8873     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8874         (RHS.getOperand(0) == LHS.getOperand(0) &&
8875          LHS.getOperand(0) == LHS.getOperand(1))) {
8876       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8877       unsigned NewMask = LCC == ISD::SETO ?
8878         Mask->getZExtValue() & ~OrdMask :
8879         Mask->getZExtValue() & OrdMask;
8880 
8881       SDLoc DL(N);
8882       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8883                          DAG.getConstant(NewMask, DL, MVT::i32));
8884     }
8885   }
8886 
8887   if (VT == MVT::i32 &&
8888       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8889     // and x, (sext cc from i1) => select cc, x, 0
8890     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8891       std::swap(LHS, RHS);
8892     if (isBoolSGPR(RHS.getOperand(0)))
8893       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8894                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8895   }
8896 
8897   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8898   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8899   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8900       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8901     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8902     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8903     if (LHSMask != ~0u && RHSMask != ~0u) {
8904       // Canonicalize the expression in an attempt to have fewer unique masks
8905       // and therefore fewer registers used to hold the masks.
8906       if (LHSMask > RHSMask) {
8907         std::swap(LHSMask, RHSMask);
8908         std::swap(LHS, RHS);
8909       }
8910 
8911       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8912       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8913       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8914       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8915 
8916       // Check of we need to combine values from two sources within a byte.
8917       if (!(LHSUsedLanes & RHSUsedLanes) &&
8918           // If we select high and lower word keep it for SDWA.
8919           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8920           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8921         // Each byte in each mask is either selector mask 0-3, or has higher
8922         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8923         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8924         // mask which is not 0xff wins. By anding both masks we have a correct
8925         // result except that 0x0c shall be corrected to give 0x0c only.
8926         uint32_t Mask = LHSMask & RHSMask;
8927         for (unsigned I = 0; I < 32; I += 8) {
8928           uint32_t ByteSel = 0xff << I;
8929           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8930             Mask &= (0x0c << I) & 0xffffffff;
8931         }
8932 
8933         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8934         // or 0x0c.
8935         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8936         SDLoc DL(N);
8937 
8938         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8939                            LHS.getOperand(0), RHS.getOperand(0),
8940                            DAG.getConstant(Sel, DL, MVT::i32));
8941       }
8942     }
8943   }
8944 
8945   return SDValue();
8946 }
8947 
8948 SDValue SITargetLowering::performOrCombine(SDNode *N,
8949                                            DAGCombinerInfo &DCI) const {
8950   SelectionDAG &DAG = DCI.DAG;
8951   SDValue LHS = N->getOperand(0);
8952   SDValue RHS = N->getOperand(1);
8953 
8954   EVT VT = N->getValueType(0);
8955   if (VT == MVT::i1) {
8956     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8957     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8958         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8959       SDValue Src = LHS.getOperand(0);
8960       if (Src != RHS.getOperand(0))
8961         return SDValue();
8962 
8963       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8964       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8965       if (!CLHS || !CRHS)
8966         return SDValue();
8967 
8968       // Only 10 bits are used.
8969       static const uint32_t MaxMask = 0x3ff;
8970 
8971       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8972       SDLoc DL(N);
8973       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8974                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8975     }
8976 
8977     return SDValue();
8978   }
8979 
8980   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8981   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8982       LHS.getOpcode() == AMDGPUISD::PERM &&
8983       isa<ConstantSDNode>(LHS.getOperand(2))) {
8984     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8985     if (!Sel)
8986       return SDValue();
8987 
8988     Sel |= LHS.getConstantOperandVal(2);
8989     SDLoc DL(N);
8990     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8991                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8992   }
8993 
8994   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8995   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8996   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8997       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8998     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8999     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9000     if (LHSMask != ~0u && RHSMask != ~0u) {
9001       // Canonicalize the expression in an attempt to have fewer unique masks
9002       // and therefore fewer registers used to hold the masks.
9003       if (LHSMask > RHSMask) {
9004         std::swap(LHSMask, RHSMask);
9005         std::swap(LHS, RHS);
9006       }
9007 
9008       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9009       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9010       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9011       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9012 
9013       // Check of we need to combine values from two sources within a byte.
9014       if (!(LHSUsedLanes & RHSUsedLanes) &&
9015           // If we select high and lower word keep it for SDWA.
9016           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9017           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9018         // Kill zero bytes selected by other mask. Zero value is 0xc.
9019         LHSMask &= ~RHSUsedLanes;
9020         RHSMask &= ~LHSUsedLanes;
9021         // Add 4 to each active LHS lane
9022         LHSMask |= LHSUsedLanes & 0x04040404;
9023         // Combine masks
9024         uint32_t Sel = LHSMask | RHSMask;
9025         SDLoc DL(N);
9026 
9027         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9028                            LHS.getOperand(0), RHS.getOperand(0),
9029                            DAG.getConstant(Sel, DL, MVT::i32));
9030       }
9031     }
9032   }
9033 
9034   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9035     return SDValue();
9036 
9037   // TODO: This could be a generic combine with a predicate for extracting the
9038   // high half of an integer being free.
9039 
9040   // (or i64:x, (zero_extend i32:y)) ->
9041   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9042   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9043       RHS.getOpcode() != ISD::ZERO_EXTEND)
9044     std::swap(LHS, RHS);
9045 
9046   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9047     SDValue ExtSrc = RHS.getOperand(0);
9048     EVT SrcVT = ExtSrc.getValueType();
9049     if (SrcVT == MVT::i32) {
9050       SDLoc SL(N);
9051       SDValue LowLHS, HiBits;
9052       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9053       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9054 
9055       DCI.AddToWorklist(LowOr.getNode());
9056       DCI.AddToWorklist(HiBits.getNode());
9057 
9058       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9059                                 LowOr, HiBits);
9060       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9061     }
9062   }
9063 
9064   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9065   if (CRHS) {
9066     if (SDValue Split
9067           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9068       return Split;
9069   }
9070 
9071   return SDValue();
9072 }
9073 
9074 SDValue SITargetLowering::performXorCombine(SDNode *N,
9075                                             DAGCombinerInfo &DCI) const {
9076   EVT VT = N->getValueType(0);
9077   if (VT != MVT::i64)
9078     return SDValue();
9079 
9080   SDValue LHS = N->getOperand(0);
9081   SDValue RHS = N->getOperand(1);
9082 
9083   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9084   if (CRHS) {
9085     if (SDValue Split
9086           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9087       return Split;
9088   }
9089 
9090   return SDValue();
9091 }
9092 
9093 // Instructions that will be lowered with a final instruction that zeros the
9094 // high result bits.
9095 // XXX - probably only need to list legal operations.
9096 static bool fp16SrcZerosHighBits(unsigned Opc) {
9097   switch (Opc) {
9098   case ISD::FADD:
9099   case ISD::FSUB:
9100   case ISD::FMUL:
9101   case ISD::FDIV:
9102   case ISD::FREM:
9103   case ISD::FMA:
9104   case ISD::FMAD:
9105   case ISD::FCANONICALIZE:
9106   case ISD::FP_ROUND:
9107   case ISD::UINT_TO_FP:
9108   case ISD::SINT_TO_FP:
9109   case ISD::FABS:
9110     // Fabs is lowered to a bit operation, but it's an and which will clear the
9111     // high bits anyway.
9112   case ISD::FSQRT:
9113   case ISD::FSIN:
9114   case ISD::FCOS:
9115   case ISD::FPOWI:
9116   case ISD::FPOW:
9117   case ISD::FLOG:
9118   case ISD::FLOG2:
9119   case ISD::FLOG10:
9120   case ISD::FEXP:
9121   case ISD::FEXP2:
9122   case ISD::FCEIL:
9123   case ISD::FTRUNC:
9124   case ISD::FRINT:
9125   case ISD::FNEARBYINT:
9126   case ISD::FROUND:
9127   case ISD::FFLOOR:
9128   case ISD::FMINNUM:
9129   case ISD::FMAXNUM:
9130   case AMDGPUISD::FRACT:
9131   case AMDGPUISD::CLAMP:
9132   case AMDGPUISD::COS_HW:
9133   case AMDGPUISD::SIN_HW:
9134   case AMDGPUISD::FMIN3:
9135   case AMDGPUISD::FMAX3:
9136   case AMDGPUISD::FMED3:
9137   case AMDGPUISD::FMAD_FTZ:
9138   case AMDGPUISD::RCP:
9139   case AMDGPUISD::RSQ:
9140   case AMDGPUISD::RCP_IFLAG:
9141   case AMDGPUISD::LDEXP:
9142     return true;
9143   default:
9144     // fcopysign, select and others may be lowered to 32-bit bit operations
9145     // which don't zero the high bits.
9146     return false;
9147   }
9148 }
9149 
9150 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9151                                                    DAGCombinerInfo &DCI) const {
9152   if (!Subtarget->has16BitInsts() ||
9153       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9154     return SDValue();
9155 
9156   EVT VT = N->getValueType(0);
9157   if (VT != MVT::i32)
9158     return SDValue();
9159 
9160   SDValue Src = N->getOperand(0);
9161   if (Src.getValueType() != MVT::i16)
9162     return SDValue();
9163 
9164   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9165   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9166   if (Src.getOpcode() == ISD::BITCAST) {
9167     SDValue BCSrc = Src.getOperand(0);
9168     if (BCSrc.getValueType() == MVT::f16 &&
9169         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9170       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9171   }
9172 
9173   return SDValue();
9174 }
9175 
9176 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9177                                                         DAGCombinerInfo &DCI)
9178                                                         const {
9179   SDValue Src = N->getOperand(0);
9180   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9181 
9182   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9183       VTSign->getVT() == MVT::i8) ||
9184       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9185       VTSign->getVT() == MVT::i16)) &&
9186       Src.hasOneUse()) {
9187     auto *M = cast<MemSDNode>(Src);
9188     SDValue Ops[] = {
9189       Src.getOperand(0), // Chain
9190       Src.getOperand(1), // rsrc
9191       Src.getOperand(2), // vindex
9192       Src.getOperand(3), // voffset
9193       Src.getOperand(4), // soffset
9194       Src.getOperand(5), // offset
9195       Src.getOperand(6),
9196       Src.getOperand(7)
9197     };
9198     // replace with BUFFER_LOAD_BYTE/SHORT
9199     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9200                                          Src.getOperand(0).getValueType());
9201     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9202                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9203     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9204                                                           ResList,
9205                                                           Ops, M->getMemoryVT(),
9206                                                           M->getMemOperand());
9207     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9208                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9209   }
9210   return SDValue();
9211 }
9212 
9213 SDValue SITargetLowering::performClassCombine(SDNode *N,
9214                                               DAGCombinerInfo &DCI) const {
9215   SelectionDAG &DAG = DCI.DAG;
9216   SDValue Mask = N->getOperand(1);
9217 
9218   // fp_class x, 0 -> false
9219   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9220     if (CMask->isNullValue())
9221       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9222   }
9223 
9224   if (N->getOperand(0).isUndef())
9225     return DAG.getUNDEF(MVT::i1);
9226 
9227   return SDValue();
9228 }
9229 
9230 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9231                                             DAGCombinerInfo &DCI) const {
9232   EVT VT = N->getValueType(0);
9233   SDValue N0 = N->getOperand(0);
9234 
9235   if (N0.isUndef())
9236     return N0;
9237 
9238   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9239                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9240     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9241                            N->getFlags());
9242   }
9243 
9244   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9245     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9246                            N0.getOperand(0), N->getFlags());
9247   }
9248 
9249   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9250 }
9251 
9252 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9253                                        unsigned MaxDepth) const {
9254   unsigned Opcode = Op.getOpcode();
9255   if (Opcode == ISD::FCANONICALIZE)
9256     return true;
9257 
9258   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9259     auto F = CFP->getValueAPF();
9260     if (F.isNaN() && F.isSignaling())
9261       return false;
9262     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9263   }
9264 
9265   // If source is a result of another standard FP operation it is already in
9266   // canonical form.
9267   if (MaxDepth == 0)
9268     return false;
9269 
9270   switch (Opcode) {
9271   // These will flush denorms if required.
9272   case ISD::FADD:
9273   case ISD::FSUB:
9274   case ISD::FMUL:
9275   case ISD::FCEIL:
9276   case ISD::FFLOOR:
9277   case ISD::FMA:
9278   case ISD::FMAD:
9279   case ISD::FSQRT:
9280   case ISD::FDIV:
9281   case ISD::FREM:
9282   case ISD::FP_ROUND:
9283   case ISD::FP_EXTEND:
9284   case AMDGPUISD::FMUL_LEGACY:
9285   case AMDGPUISD::FMAD_FTZ:
9286   case AMDGPUISD::RCP:
9287   case AMDGPUISD::RSQ:
9288   case AMDGPUISD::RSQ_CLAMP:
9289   case AMDGPUISD::RCP_LEGACY:
9290   case AMDGPUISD::RCP_IFLAG:
9291   case AMDGPUISD::DIV_SCALE:
9292   case AMDGPUISD::DIV_FMAS:
9293   case AMDGPUISD::DIV_FIXUP:
9294   case AMDGPUISD::FRACT:
9295   case AMDGPUISD::LDEXP:
9296   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9297   case AMDGPUISD::CVT_F32_UBYTE0:
9298   case AMDGPUISD::CVT_F32_UBYTE1:
9299   case AMDGPUISD::CVT_F32_UBYTE2:
9300   case AMDGPUISD::CVT_F32_UBYTE3:
9301     return true;
9302 
9303   // It can/will be lowered or combined as a bit operation.
9304   // Need to check their input recursively to handle.
9305   case ISD::FNEG:
9306   case ISD::FABS:
9307   case ISD::FCOPYSIGN:
9308     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9309 
9310   case ISD::FSIN:
9311   case ISD::FCOS:
9312   case ISD::FSINCOS:
9313     return Op.getValueType().getScalarType() != MVT::f16;
9314 
9315   case ISD::FMINNUM:
9316   case ISD::FMAXNUM:
9317   case ISD::FMINNUM_IEEE:
9318   case ISD::FMAXNUM_IEEE:
9319   case AMDGPUISD::CLAMP:
9320   case AMDGPUISD::FMED3:
9321   case AMDGPUISD::FMAX3:
9322   case AMDGPUISD::FMIN3: {
9323     // FIXME: Shouldn't treat the generic operations different based these.
9324     // However, we aren't really required to flush the result from
9325     // minnum/maxnum..
9326 
9327     // snans will be quieted, so we only need to worry about denormals.
9328     if (Subtarget->supportsMinMaxDenormModes() ||
9329         denormalsEnabledForType(DAG, Op.getValueType()))
9330       return true;
9331 
9332     // Flushing may be required.
9333     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9334     // targets need to check their input recursively.
9335 
9336     // FIXME: Does this apply with clamp? It's implemented with max.
9337     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9338       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9339         return false;
9340     }
9341 
9342     return true;
9343   }
9344   case ISD::SELECT: {
9345     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9346            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9347   }
9348   case ISD::BUILD_VECTOR: {
9349     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9350       SDValue SrcOp = Op.getOperand(i);
9351       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9352         return false;
9353     }
9354 
9355     return true;
9356   }
9357   case ISD::EXTRACT_VECTOR_ELT:
9358   case ISD::EXTRACT_SUBVECTOR: {
9359     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9360   }
9361   case ISD::INSERT_VECTOR_ELT: {
9362     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9363            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9364   }
9365   case ISD::UNDEF:
9366     // Could be anything.
9367     return false;
9368 
9369   case ISD::BITCAST: {
9370     // Hack round the mess we make when legalizing extract_vector_elt
9371     SDValue Src = Op.getOperand(0);
9372     if (Src.getValueType() == MVT::i16 &&
9373         Src.getOpcode() == ISD::TRUNCATE) {
9374       SDValue TruncSrc = Src.getOperand(0);
9375       if (TruncSrc.getValueType() == MVT::i32 &&
9376           TruncSrc.getOpcode() == ISD::BITCAST &&
9377           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9378         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9379       }
9380     }
9381 
9382     return false;
9383   }
9384   case ISD::INTRINSIC_WO_CHAIN: {
9385     unsigned IntrinsicID
9386       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9387     // TODO: Handle more intrinsics
9388     switch (IntrinsicID) {
9389     case Intrinsic::amdgcn_cvt_pkrtz:
9390     case Intrinsic::amdgcn_cubeid:
9391     case Intrinsic::amdgcn_frexp_mant:
9392     case Intrinsic::amdgcn_fdot2:
9393     case Intrinsic::amdgcn_rcp:
9394     case Intrinsic::amdgcn_rsq:
9395     case Intrinsic::amdgcn_rsq_clamp:
9396     case Intrinsic::amdgcn_rcp_legacy:
9397     case Intrinsic::amdgcn_rsq_legacy:
9398     case Intrinsic::amdgcn_trig_preop:
9399       return true;
9400     default:
9401       break;
9402     }
9403 
9404     LLVM_FALLTHROUGH;
9405   }
9406   default:
9407     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9408            DAG.isKnownNeverSNaN(Op);
9409   }
9410 
9411   llvm_unreachable("invalid operation");
9412 }
9413 
9414 // Constant fold canonicalize.
9415 SDValue SITargetLowering::getCanonicalConstantFP(
9416   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9417   // Flush denormals to 0 if not enabled.
9418   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9419     return DAG.getConstantFP(0.0, SL, VT);
9420 
9421   if (C.isNaN()) {
9422     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9423     if (C.isSignaling()) {
9424       // Quiet a signaling NaN.
9425       // FIXME: Is this supposed to preserve payload bits?
9426       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9427     }
9428 
9429     // Make sure it is the canonical NaN bitpattern.
9430     //
9431     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9432     // immediate?
9433     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9434       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9435   }
9436 
9437   // Already canonical.
9438   return DAG.getConstantFP(C, SL, VT);
9439 }
9440 
9441 static bool vectorEltWillFoldAway(SDValue Op) {
9442   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9443 }
9444 
9445 SDValue SITargetLowering::performFCanonicalizeCombine(
9446   SDNode *N,
9447   DAGCombinerInfo &DCI) const {
9448   SelectionDAG &DAG = DCI.DAG;
9449   SDValue N0 = N->getOperand(0);
9450   EVT VT = N->getValueType(0);
9451 
9452   // fcanonicalize undef -> qnan
9453   if (N0.isUndef()) {
9454     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9455     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9456   }
9457 
9458   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9459     EVT VT = N->getValueType(0);
9460     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9461   }
9462 
9463   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9464   //                                                   (fcanonicalize k)
9465   //
9466   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9467 
9468   // TODO: This could be better with wider vectors that will be split to v2f16,
9469   // and to consider uses since there aren't that many packed operations.
9470   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9471       isTypeLegal(MVT::v2f16)) {
9472     SDLoc SL(N);
9473     SDValue NewElts[2];
9474     SDValue Lo = N0.getOperand(0);
9475     SDValue Hi = N0.getOperand(1);
9476     EVT EltVT = Lo.getValueType();
9477 
9478     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9479       for (unsigned I = 0; I != 2; ++I) {
9480         SDValue Op = N0.getOperand(I);
9481         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9482           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9483                                               CFP->getValueAPF());
9484         } else if (Op.isUndef()) {
9485           // Handled below based on what the other operand is.
9486           NewElts[I] = Op;
9487         } else {
9488           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9489         }
9490       }
9491 
9492       // If one half is undef, and one is constant, perfer a splat vector rather
9493       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9494       // cheaper to use and may be free with a packed operation.
9495       if (NewElts[0].isUndef()) {
9496         if (isa<ConstantFPSDNode>(NewElts[1]))
9497           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9498             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9499       }
9500 
9501       if (NewElts[1].isUndef()) {
9502         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9503           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9504       }
9505 
9506       return DAG.getBuildVector(VT, SL, NewElts);
9507     }
9508   }
9509 
9510   unsigned SrcOpc = N0.getOpcode();
9511 
9512   // If it's free to do so, push canonicalizes further up the source, which may
9513   // find a canonical source.
9514   //
9515   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9516   // sNaNs.
9517   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9518     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9519     if (CRHS && N0.hasOneUse()) {
9520       SDLoc SL(N);
9521       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9522                                    N0.getOperand(0));
9523       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9524       DCI.AddToWorklist(Canon0.getNode());
9525 
9526       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9527     }
9528   }
9529 
9530   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9531 }
9532 
9533 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9534   switch (Opc) {
9535   case ISD::FMAXNUM:
9536   case ISD::FMAXNUM_IEEE:
9537     return AMDGPUISD::FMAX3;
9538   case ISD::SMAX:
9539     return AMDGPUISD::SMAX3;
9540   case ISD::UMAX:
9541     return AMDGPUISD::UMAX3;
9542   case ISD::FMINNUM:
9543   case ISD::FMINNUM_IEEE:
9544     return AMDGPUISD::FMIN3;
9545   case ISD::SMIN:
9546     return AMDGPUISD::SMIN3;
9547   case ISD::UMIN:
9548     return AMDGPUISD::UMIN3;
9549   default:
9550     llvm_unreachable("Not a min/max opcode");
9551   }
9552 }
9553 
9554 SDValue SITargetLowering::performIntMed3ImmCombine(
9555   SelectionDAG &DAG, const SDLoc &SL,
9556   SDValue Op0, SDValue Op1, bool Signed) const {
9557   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9558   if (!K1)
9559     return SDValue();
9560 
9561   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9562   if (!K0)
9563     return SDValue();
9564 
9565   if (Signed) {
9566     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9567       return SDValue();
9568   } else {
9569     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9570       return SDValue();
9571   }
9572 
9573   EVT VT = K0->getValueType(0);
9574   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9575   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9576     return DAG.getNode(Med3Opc, SL, VT,
9577                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9578   }
9579 
9580   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9581   MVT NVT = MVT::i32;
9582   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9583 
9584   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9585   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9586   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9587 
9588   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9589   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9590 }
9591 
9592 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9593   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9594     return C;
9595 
9596   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9597     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9598       return C;
9599   }
9600 
9601   return nullptr;
9602 }
9603 
9604 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9605                                                   const SDLoc &SL,
9606                                                   SDValue Op0,
9607                                                   SDValue Op1) const {
9608   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9609   if (!K1)
9610     return SDValue();
9611 
9612   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9613   if (!K0)
9614     return SDValue();
9615 
9616   // Ordered >= (although NaN inputs should have folded away by now).
9617   if (K0->getValueAPF() > K1->getValueAPF())
9618     return SDValue();
9619 
9620   const MachineFunction &MF = DAG.getMachineFunction();
9621   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9622 
9623   // TODO: Check IEEE bit enabled?
9624   EVT VT = Op0.getValueType();
9625   if (Info->getMode().DX10Clamp) {
9626     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9627     // hardware fmed3 behavior converting to a min.
9628     // FIXME: Should this be allowing -0.0?
9629     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9630       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9631   }
9632 
9633   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9634   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9635     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9636     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9637     // then give the other result, which is different from med3 with a NaN
9638     // input.
9639     SDValue Var = Op0.getOperand(0);
9640     if (!DAG.isKnownNeverSNaN(Var))
9641       return SDValue();
9642 
9643     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9644 
9645     if ((!K0->hasOneUse() ||
9646          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9647         (!K1->hasOneUse() ||
9648          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9649       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9650                          Var, SDValue(K0, 0), SDValue(K1, 0));
9651     }
9652   }
9653 
9654   return SDValue();
9655 }
9656 
9657 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9658                                                DAGCombinerInfo &DCI) const {
9659   SelectionDAG &DAG = DCI.DAG;
9660 
9661   EVT VT = N->getValueType(0);
9662   unsigned Opc = N->getOpcode();
9663   SDValue Op0 = N->getOperand(0);
9664   SDValue Op1 = N->getOperand(1);
9665 
9666   // Only do this if the inner op has one use since this will just increases
9667   // register pressure for no benefit.
9668 
9669   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9670       !VT.isVector() &&
9671       (VT == MVT::i32 || VT == MVT::f32 ||
9672        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9673     // max(max(a, b), c) -> max3(a, b, c)
9674     // min(min(a, b), c) -> min3(a, b, c)
9675     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9676       SDLoc DL(N);
9677       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9678                          DL,
9679                          N->getValueType(0),
9680                          Op0.getOperand(0),
9681                          Op0.getOperand(1),
9682                          Op1);
9683     }
9684 
9685     // Try commuted.
9686     // max(a, max(b, c)) -> max3(a, b, c)
9687     // min(a, min(b, c)) -> min3(a, b, c)
9688     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9689       SDLoc DL(N);
9690       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9691                          DL,
9692                          N->getValueType(0),
9693                          Op0,
9694                          Op1.getOperand(0),
9695                          Op1.getOperand(1));
9696     }
9697   }
9698 
9699   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9700   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9701     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9702       return Med3;
9703   }
9704 
9705   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9706     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9707       return Med3;
9708   }
9709 
9710   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9711   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9712        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9713        (Opc == AMDGPUISD::FMIN_LEGACY &&
9714         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9715       (VT == MVT::f32 || VT == MVT::f64 ||
9716        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9717        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9718       Op0.hasOneUse()) {
9719     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9720       return Res;
9721   }
9722 
9723   return SDValue();
9724 }
9725 
9726 static bool isClampZeroToOne(SDValue A, SDValue B) {
9727   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9728     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9729       // FIXME: Should this be allowing -0.0?
9730       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9731              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9732     }
9733   }
9734 
9735   return false;
9736 }
9737 
9738 // FIXME: Should only worry about snans for version with chain.
9739 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9740                                               DAGCombinerInfo &DCI) const {
9741   EVT VT = N->getValueType(0);
9742   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9743   // NaNs. With a NaN input, the order of the operands may change the result.
9744 
9745   SelectionDAG &DAG = DCI.DAG;
9746   SDLoc SL(N);
9747 
9748   SDValue Src0 = N->getOperand(0);
9749   SDValue Src1 = N->getOperand(1);
9750   SDValue Src2 = N->getOperand(2);
9751 
9752   if (isClampZeroToOne(Src0, Src1)) {
9753     // const_a, const_b, x -> clamp is safe in all cases including signaling
9754     // nans.
9755     // FIXME: Should this be allowing -0.0?
9756     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9757   }
9758 
9759   const MachineFunction &MF = DAG.getMachineFunction();
9760   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9761 
9762   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9763   // handling no dx10-clamp?
9764   if (Info->getMode().DX10Clamp) {
9765     // If NaNs is clamped to 0, we are free to reorder the inputs.
9766 
9767     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9768       std::swap(Src0, Src1);
9769 
9770     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9771       std::swap(Src1, Src2);
9772 
9773     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9774       std::swap(Src0, Src1);
9775 
9776     if (isClampZeroToOne(Src1, Src2))
9777       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9778   }
9779 
9780   return SDValue();
9781 }
9782 
9783 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9784                                                  DAGCombinerInfo &DCI) const {
9785   SDValue Src0 = N->getOperand(0);
9786   SDValue Src1 = N->getOperand(1);
9787   if (Src0.isUndef() && Src1.isUndef())
9788     return DCI.DAG.getUNDEF(N->getValueType(0));
9789   return SDValue();
9790 }
9791 
9792 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9793 // expanded into a set of cmp/select instructions.
9794 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9795                                                 unsigned NumElem,
9796                                                 bool IsDivergentIdx) {
9797   if (UseDivergentRegisterIndexing)
9798     return false;
9799 
9800   unsigned VecSize = EltSize * NumElem;
9801 
9802   // Sub-dword vectors of size 2 dword or less have better implementation.
9803   if (VecSize <= 64 && EltSize < 32)
9804     return false;
9805 
9806   // Always expand the rest of sub-dword instructions, otherwise it will be
9807   // lowered via memory.
9808   if (EltSize < 32)
9809     return true;
9810 
9811   // Always do this if var-idx is divergent, otherwise it will become a loop.
9812   if (IsDivergentIdx)
9813     return true;
9814 
9815   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9816   unsigned NumInsts = NumElem /* Number of compares */ +
9817                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9818   return NumInsts <= 16;
9819 }
9820 
9821 static bool shouldExpandVectorDynExt(SDNode *N) {
9822   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9823   if (isa<ConstantSDNode>(Idx))
9824     return false;
9825 
9826   SDValue Vec = N->getOperand(0);
9827   EVT VecVT = Vec.getValueType();
9828   EVT EltVT = VecVT.getVectorElementType();
9829   unsigned EltSize = EltVT.getSizeInBits();
9830   unsigned NumElem = VecVT.getVectorNumElements();
9831 
9832   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9833                                                     Idx->isDivergent());
9834 }
9835 
9836 SDValue SITargetLowering::performExtractVectorEltCombine(
9837   SDNode *N, DAGCombinerInfo &DCI) const {
9838   SDValue Vec = N->getOperand(0);
9839   SelectionDAG &DAG = DCI.DAG;
9840 
9841   EVT VecVT = Vec.getValueType();
9842   EVT EltVT = VecVT.getVectorElementType();
9843 
9844   if ((Vec.getOpcode() == ISD::FNEG ||
9845        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9846     SDLoc SL(N);
9847     EVT EltVT = N->getValueType(0);
9848     SDValue Idx = N->getOperand(1);
9849     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9850                               Vec.getOperand(0), Idx);
9851     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9852   }
9853 
9854   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9855   //    =>
9856   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9857   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9858   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9859   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9860     SDLoc SL(N);
9861     EVT EltVT = N->getValueType(0);
9862     SDValue Idx = N->getOperand(1);
9863     unsigned Opc = Vec.getOpcode();
9864 
9865     switch(Opc) {
9866     default:
9867       break;
9868       // TODO: Support other binary operations.
9869     case ISD::FADD:
9870     case ISD::FSUB:
9871     case ISD::FMUL:
9872     case ISD::ADD:
9873     case ISD::UMIN:
9874     case ISD::UMAX:
9875     case ISD::SMIN:
9876     case ISD::SMAX:
9877     case ISD::FMAXNUM:
9878     case ISD::FMINNUM:
9879     case ISD::FMAXNUM_IEEE:
9880     case ISD::FMINNUM_IEEE: {
9881       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9882                                  Vec.getOperand(0), Idx);
9883       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9884                                  Vec.getOperand(1), Idx);
9885 
9886       DCI.AddToWorklist(Elt0.getNode());
9887       DCI.AddToWorklist(Elt1.getNode());
9888       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9889     }
9890     }
9891   }
9892 
9893   unsigned VecSize = VecVT.getSizeInBits();
9894   unsigned EltSize = EltVT.getSizeInBits();
9895 
9896   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9897   if (::shouldExpandVectorDynExt(N)) {
9898     SDLoc SL(N);
9899     SDValue Idx = N->getOperand(1);
9900     SDValue V;
9901     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9902       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9903       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9904       if (I == 0)
9905         V = Elt;
9906       else
9907         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9908     }
9909     return V;
9910   }
9911 
9912   if (!DCI.isBeforeLegalize())
9913     return SDValue();
9914 
9915   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9916   // elements. This exposes more load reduction opportunities by replacing
9917   // multiple small extract_vector_elements with a single 32-bit extract.
9918   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9919   if (isa<MemSDNode>(Vec) &&
9920       EltSize <= 16 &&
9921       EltVT.isByteSized() &&
9922       VecSize > 32 &&
9923       VecSize % 32 == 0 &&
9924       Idx) {
9925     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9926 
9927     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9928     unsigned EltIdx = BitIndex / 32;
9929     unsigned LeftoverBitIdx = BitIndex % 32;
9930     SDLoc SL(N);
9931 
9932     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9933     DCI.AddToWorklist(Cast.getNode());
9934 
9935     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9936                               DAG.getConstant(EltIdx, SL, MVT::i32));
9937     DCI.AddToWorklist(Elt.getNode());
9938     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9939                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9940     DCI.AddToWorklist(Srl.getNode());
9941 
9942     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9943     DCI.AddToWorklist(Trunc.getNode());
9944     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9945   }
9946 
9947   return SDValue();
9948 }
9949 
9950 SDValue
9951 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9952                                                 DAGCombinerInfo &DCI) const {
9953   SDValue Vec = N->getOperand(0);
9954   SDValue Idx = N->getOperand(2);
9955   EVT VecVT = Vec.getValueType();
9956   EVT EltVT = VecVT.getVectorElementType();
9957 
9958   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9959   // => BUILD_VECTOR n x select (e, const-idx)
9960   if (!::shouldExpandVectorDynExt(N))
9961     return SDValue();
9962 
9963   SelectionDAG &DAG = DCI.DAG;
9964   SDLoc SL(N);
9965   SDValue Ins = N->getOperand(1);
9966   EVT IdxVT = Idx.getValueType();
9967 
9968   SmallVector<SDValue, 16> Ops;
9969   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9970     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9971     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9972     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9973     Ops.push_back(V);
9974   }
9975 
9976   return DAG.getBuildVector(VecVT, SL, Ops);
9977 }
9978 
9979 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9980                                           const SDNode *N0,
9981                                           const SDNode *N1) const {
9982   EVT VT = N0->getValueType(0);
9983 
9984   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9985   // support denormals ever.
9986   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9987        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9988         getSubtarget()->hasMadF16())) &&
9989        isOperationLegal(ISD::FMAD, VT))
9990     return ISD::FMAD;
9991 
9992   const TargetOptions &Options = DAG.getTarget().Options;
9993   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9994        (N0->getFlags().hasAllowContract() &&
9995         N1->getFlags().hasAllowContract())) &&
9996       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9997     return ISD::FMA;
9998   }
9999 
10000   return 0;
10001 }
10002 
10003 // For a reassociatable opcode perform:
10004 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10005 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10006                                                SelectionDAG &DAG) const {
10007   EVT VT = N->getValueType(0);
10008   if (VT != MVT::i32 && VT != MVT::i64)
10009     return SDValue();
10010 
10011   unsigned Opc = N->getOpcode();
10012   SDValue Op0 = N->getOperand(0);
10013   SDValue Op1 = N->getOperand(1);
10014 
10015   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10016     return SDValue();
10017 
10018   if (Op0->isDivergent())
10019     std::swap(Op0, Op1);
10020 
10021   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10022     return SDValue();
10023 
10024   SDValue Op2 = Op1.getOperand(1);
10025   Op1 = Op1.getOperand(0);
10026   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10027     return SDValue();
10028 
10029   if (Op1->isDivergent())
10030     std::swap(Op1, Op2);
10031 
10032   // If either operand is constant this will conflict with
10033   // DAGCombiner::ReassociateOps().
10034   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10035       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10036     return SDValue();
10037 
10038   SDLoc SL(N);
10039   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10040   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10041 }
10042 
10043 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10044                            EVT VT,
10045                            SDValue N0, SDValue N1, SDValue N2,
10046                            bool Signed) {
10047   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10048   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10049   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10050   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10051 }
10052 
10053 SDValue SITargetLowering::performAddCombine(SDNode *N,
10054                                             DAGCombinerInfo &DCI) const {
10055   SelectionDAG &DAG = DCI.DAG;
10056   EVT VT = N->getValueType(0);
10057   SDLoc SL(N);
10058   SDValue LHS = N->getOperand(0);
10059   SDValue RHS = N->getOperand(1);
10060 
10061   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10062       && Subtarget->hasMad64_32() &&
10063       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10064       VT.getScalarSizeInBits() <= 64) {
10065     if (LHS.getOpcode() != ISD::MUL)
10066       std::swap(LHS, RHS);
10067 
10068     SDValue MulLHS = LHS.getOperand(0);
10069     SDValue MulRHS = LHS.getOperand(1);
10070     SDValue AddRHS = RHS;
10071 
10072     // TODO: Maybe restrict if SGPR inputs.
10073     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10074         numBitsUnsigned(MulRHS, DAG) <= 32) {
10075       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10076       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10077       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10078       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10079     }
10080 
10081     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10082       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10083       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10084       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10085       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10086     }
10087 
10088     return SDValue();
10089   }
10090 
10091   if (SDValue V = reassociateScalarOps(N, DAG)) {
10092     return V;
10093   }
10094 
10095   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10096     return SDValue();
10097 
10098   // add x, zext (setcc) => addcarry x, 0, setcc
10099   // add x, sext (setcc) => subcarry x, 0, setcc
10100   unsigned Opc = LHS.getOpcode();
10101   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10102       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10103     std::swap(RHS, LHS);
10104 
10105   Opc = RHS.getOpcode();
10106   switch (Opc) {
10107   default: break;
10108   case ISD::ZERO_EXTEND:
10109   case ISD::SIGN_EXTEND:
10110   case ISD::ANY_EXTEND: {
10111     auto Cond = RHS.getOperand(0);
10112     // If this won't be a real VOPC output, we would still need to insert an
10113     // extra instruction anyway.
10114     if (!isBoolSGPR(Cond))
10115       break;
10116     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10117     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10118     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10119     return DAG.getNode(Opc, SL, VTList, Args);
10120   }
10121   case ISD::ADDCARRY: {
10122     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10123     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10124     if (!C || C->getZExtValue() != 0) break;
10125     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10126     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10127   }
10128   }
10129   return SDValue();
10130 }
10131 
10132 SDValue SITargetLowering::performSubCombine(SDNode *N,
10133                                             DAGCombinerInfo &DCI) const {
10134   SelectionDAG &DAG = DCI.DAG;
10135   EVT VT = N->getValueType(0);
10136 
10137   if (VT != MVT::i32)
10138     return SDValue();
10139 
10140   SDLoc SL(N);
10141   SDValue LHS = N->getOperand(0);
10142   SDValue RHS = N->getOperand(1);
10143 
10144   // sub x, zext (setcc) => subcarry x, 0, setcc
10145   // sub x, sext (setcc) => addcarry x, 0, setcc
10146   unsigned Opc = RHS.getOpcode();
10147   switch (Opc) {
10148   default: break;
10149   case ISD::ZERO_EXTEND:
10150   case ISD::SIGN_EXTEND:
10151   case ISD::ANY_EXTEND: {
10152     auto Cond = RHS.getOperand(0);
10153     // If this won't be a real VOPC output, we would still need to insert an
10154     // extra instruction anyway.
10155     if (!isBoolSGPR(Cond))
10156       break;
10157     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10158     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10159     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10160     return DAG.getNode(Opc, SL, VTList, Args);
10161   }
10162   }
10163 
10164   if (LHS.getOpcode() == ISD::SUBCARRY) {
10165     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10166     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10167     if (!C || !C->isNullValue())
10168       return SDValue();
10169     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10170     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10171   }
10172   return SDValue();
10173 }
10174 
10175 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10176   DAGCombinerInfo &DCI) const {
10177 
10178   if (N->getValueType(0) != MVT::i32)
10179     return SDValue();
10180 
10181   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10182   if (!C || C->getZExtValue() != 0)
10183     return SDValue();
10184 
10185   SelectionDAG &DAG = DCI.DAG;
10186   SDValue LHS = N->getOperand(0);
10187 
10188   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10189   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10190   unsigned LHSOpc = LHS.getOpcode();
10191   unsigned Opc = N->getOpcode();
10192   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10193       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10194     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10195     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10196   }
10197   return SDValue();
10198 }
10199 
10200 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10201                                              DAGCombinerInfo &DCI) const {
10202   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10203     return SDValue();
10204 
10205   SelectionDAG &DAG = DCI.DAG;
10206   EVT VT = N->getValueType(0);
10207 
10208   SDLoc SL(N);
10209   SDValue LHS = N->getOperand(0);
10210   SDValue RHS = N->getOperand(1);
10211 
10212   // These should really be instruction patterns, but writing patterns with
10213   // source modiifiers is a pain.
10214 
10215   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10216   if (LHS.getOpcode() == ISD::FADD) {
10217     SDValue A = LHS.getOperand(0);
10218     if (A == LHS.getOperand(1)) {
10219       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10220       if (FusedOp != 0) {
10221         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10222         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10223       }
10224     }
10225   }
10226 
10227   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10228   if (RHS.getOpcode() == ISD::FADD) {
10229     SDValue A = RHS.getOperand(0);
10230     if (A == RHS.getOperand(1)) {
10231       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10232       if (FusedOp != 0) {
10233         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10234         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10235       }
10236     }
10237   }
10238 
10239   return SDValue();
10240 }
10241 
10242 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10243                                              DAGCombinerInfo &DCI) const {
10244   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10245     return SDValue();
10246 
10247   SelectionDAG &DAG = DCI.DAG;
10248   SDLoc SL(N);
10249   EVT VT = N->getValueType(0);
10250   assert(!VT.isVector());
10251 
10252   // Try to get the fneg to fold into the source modifier. This undoes generic
10253   // DAG combines and folds them into the mad.
10254   //
10255   // Only do this if we are not trying to support denormals. v_mad_f32 does
10256   // not support denormals ever.
10257   SDValue LHS = N->getOperand(0);
10258   SDValue RHS = N->getOperand(1);
10259   if (LHS.getOpcode() == ISD::FADD) {
10260     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10261     SDValue A = LHS.getOperand(0);
10262     if (A == LHS.getOperand(1)) {
10263       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10264       if (FusedOp != 0){
10265         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10266         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10267 
10268         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10269       }
10270     }
10271   }
10272 
10273   if (RHS.getOpcode() == ISD::FADD) {
10274     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10275 
10276     SDValue A = RHS.getOperand(0);
10277     if (A == RHS.getOperand(1)) {
10278       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10279       if (FusedOp != 0){
10280         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10281         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10282       }
10283     }
10284   }
10285 
10286   return SDValue();
10287 }
10288 
10289 SDValue SITargetLowering::performFMACombine(SDNode *N,
10290                                             DAGCombinerInfo &DCI) const {
10291   SelectionDAG &DAG = DCI.DAG;
10292   EVT VT = N->getValueType(0);
10293   SDLoc SL(N);
10294 
10295   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10296     return SDValue();
10297 
10298   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10299   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10300   SDValue Op1 = N->getOperand(0);
10301   SDValue Op2 = N->getOperand(1);
10302   SDValue FMA = N->getOperand(2);
10303 
10304   if (FMA.getOpcode() != ISD::FMA ||
10305       Op1.getOpcode() != ISD::FP_EXTEND ||
10306       Op2.getOpcode() != ISD::FP_EXTEND)
10307     return SDValue();
10308 
10309   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10310   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10311   // is sufficient to allow generaing fdot2.
10312   const TargetOptions &Options = DAG.getTarget().Options;
10313   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10314       (N->getFlags().hasAllowContract() &&
10315        FMA->getFlags().hasAllowContract())) {
10316     Op1 = Op1.getOperand(0);
10317     Op2 = Op2.getOperand(0);
10318     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10319         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10320       return SDValue();
10321 
10322     SDValue Vec1 = Op1.getOperand(0);
10323     SDValue Idx1 = Op1.getOperand(1);
10324     SDValue Vec2 = Op2.getOperand(0);
10325 
10326     SDValue FMAOp1 = FMA.getOperand(0);
10327     SDValue FMAOp2 = FMA.getOperand(1);
10328     SDValue FMAAcc = FMA.getOperand(2);
10329 
10330     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10331         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10332       return SDValue();
10333 
10334     FMAOp1 = FMAOp1.getOperand(0);
10335     FMAOp2 = FMAOp2.getOperand(0);
10336     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10337         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10338       return SDValue();
10339 
10340     SDValue Vec3 = FMAOp1.getOperand(0);
10341     SDValue Vec4 = FMAOp2.getOperand(0);
10342     SDValue Idx2 = FMAOp1.getOperand(1);
10343 
10344     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10345         // Idx1 and Idx2 cannot be the same.
10346         Idx1 == Idx2)
10347       return SDValue();
10348 
10349     if (Vec1 == Vec2 || Vec3 == Vec4)
10350       return SDValue();
10351 
10352     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10353       return SDValue();
10354 
10355     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10356         (Vec1 == Vec4 && Vec2 == Vec3)) {
10357       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10358                          DAG.getTargetConstant(0, SL, MVT::i1));
10359     }
10360   }
10361   return SDValue();
10362 }
10363 
10364 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10365                                               DAGCombinerInfo &DCI) const {
10366   SelectionDAG &DAG = DCI.DAG;
10367   SDLoc SL(N);
10368 
10369   SDValue LHS = N->getOperand(0);
10370   SDValue RHS = N->getOperand(1);
10371   EVT VT = LHS.getValueType();
10372   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10373 
10374   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10375   if (!CRHS) {
10376     CRHS = dyn_cast<ConstantSDNode>(LHS);
10377     if (CRHS) {
10378       std::swap(LHS, RHS);
10379       CC = getSetCCSwappedOperands(CC);
10380     }
10381   }
10382 
10383   if (CRHS) {
10384     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10385         isBoolSGPR(LHS.getOperand(0))) {
10386       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10387       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10388       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10389       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10390       if ((CRHS->isAllOnesValue() &&
10391            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10392           (CRHS->isNullValue() &&
10393            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10394         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10395                            DAG.getConstant(-1, SL, MVT::i1));
10396       if ((CRHS->isAllOnesValue() &&
10397            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10398           (CRHS->isNullValue() &&
10399            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10400         return LHS.getOperand(0);
10401     }
10402 
10403     uint64_t CRHSVal = CRHS->getZExtValue();
10404     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10405         LHS.getOpcode() == ISD::SELECT &&
10406         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10407         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10408         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10409         isBoolSGPR(LHS.getOperand(0))) {
10410       // Given CT != FT:
10411       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10412       // setcc (select cc, CT, CF), CF, ne => cc
10413       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10414       // setcc (select cc, CT, CF), CT, eq => cc
10415       uint64_t CT = LHS.getConstantOperandVal(1);
10416       uint64_t CF = LHS.getConstantOperandVal(2);
10417 
10418       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10419           (CT == CRHSVal && CC == ISD::SETNE))
10420         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10421                            DAG.getConstant(-1, SL, MVT::i1));
10422       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10423           (CT == CRHSVal && CC == ISD::SETEQ))
10424         return LHS.getOperand(0);
10425     }
10426   }
10427 
10428   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10429                                            VT != MVT::f16))
10430     return SDValue();
10431 
10432   // Match isinf/isfinite pattern
10433   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10434   // (fcmp one (fabs x), inf) -> (fp_class x,
10435   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10436   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10437     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10438     if (!CRHS)
10439       return SDValue();
10440 
10441     const APFloat &APF = CRHS->getValueAPF();
10442     if (APF.isInfinity() && !APF.isNegative()) {
10443       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10444                                  SIInstrFlags::N_INFINITY;
10445       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10446                                     SIInstrFlags::P_ZERO |
10447                                     SIInstrFlags::N_NORMAL |
10448                                     SIInstrFlags::P_NORMAL |
10449                                     SIInstrFlags::N_SUBNORMAL |
10450                                     SIInstrFlags::P_SUBNORMAL;
10451       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10452       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10453                          DAG.getConstant(Mask, SL, MVT::i32));
10454     }
10455   }
10456 
10457   return SDValue();
10458 }
10459 
10460 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10461                                                      DAGCombinerInfo &DCI) const {
10462   SelectionDAG &DAG = DCI.DAG;
10463   SDLoc SL(N);
10464   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10465 
10466   SDValue Src = N->getOperand(0);
10467   SDValue Shift = N->getOperand(0);
10468 
10469   // TODO: Extend type shouldn't matter (assuming legal types).
10470   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10471     Shift = Shift.getOperand(0);
10472 
10473   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10474     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10475     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10476     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10477     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10478     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10479     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10480       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10481                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10482 
10483       unsigned ShiftOffset = 8 * Offset;
10484       if (Shift.getOpcode() == ISD::SHL)
10485         ShiftOffset -= C->getZExtValue();
10486       else
10487         ShiftOffset += C->getZExtValue();
10488 
10489       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10490         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10491                            MVT::f32, Shift);
10492       }
10493     }
10494   }
10495 
10496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10497   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10498   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10499     // We simplified Src. If this node is not dead, visit it again so it is
10500     // folded properly.
10501     if (N->getOpcode() != ISD::DELETED_NODE)
10502       DCI.AddToWorklist(N);
10503     return SDValue(N, 0);
10504   }
10505 
10506   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10507   if (SDValue DemandedSrc =
10508           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10509     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10510 
10511   return SDValue();
10512 }
10513 
10514 SDValue SITargetLowering::performClampCombine(SDNode *N,
10515                                               DAGCombinerInfo &DCI) const {
10516   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10517   if (!CSrc)
10518     return SDValue();
10519 
10520   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10521   const APFloat &F = CSrc->getValueAPF();
10522   APFloat Zero = APFloat::getZero(F.getSemantics());
10523   if (F < Zero ||
10524       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10525     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10526   }
10527 
10528   APFloat One(F.getSemantics(), "1.0");
10529   if (F > One)
10530     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10531 
10532   return SDValue(CSrc, 0);
10533 }
10534 
10535 
10536 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10537                                             DAGCombinerInfo &DCI) const {
10538   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10539     return SDValue();
10540   switch (N->getOpcode()) {
10541   case ISD::ADD:
10542     return performAddCombine(N, DCI);
10543   case ISD::SUB:
10544     return performSubCombine(N, DCI);
10545   case ISD::ADDCARRY:
10546   case ISD::SUBCARRY:
10547     return performAddCarrySubCarryCombine(N, DCI);
10548   case ISD::FADD:
10549     return performFAddCombine(N, DCI);
10550   case ISD::FSUB:
10551     return performFSubCombine(N, DCI);
10552   case ISD::SETCC:
10553     return performSetCCCombine(N, DCI);
10554   case ISD::FMAXNUM:
10555   case ISD::FMINNUM:
10556   case ISD::FMAXNUM_IEEE:
10557   case ISD::FMINNUM_IEEE:
10558   case ISD::SMAX:
10559   case ISD::SMIN:
10560   case ISD::UMAX:
10561   case ISD::UMIN:
10562   case AMDGPUISD::FMIN_LEGACY:
10563   case AMDGPUISD::FMAX_LEGACY:
10564     return performMinMaxCombine(N, DCI);
10565   case ISD::FMA:
10566     return performFMACombine(N, DCI);
10567   case ISD::AND:
10568     return performAndCombine(N, DCI);
10569   case ISD::OR:
10570     return performOrCombine(N, DCI);
10571   case ISD::XOR:
10572     return performXorCombine(N, DCI);
10573   case ISD::ZERO_EXTEND:
10574     return performZeroExtendCombine(N, DCI);
10575   case ISD::SIGN_EXTEND_INREG:
10576     return performSignExtendInRegCombine(N , DCI);
10577   case AMDGPUISD::FP_CLASS:
10578     return performClassCombine(N, DCI);
10579   case ISD::FCANONICALIZE:
10580     return performFCanonicalizeCombine(N, DCI);
10581   case AMDGPUISD::RCP:
10582     return performRcpCombine(N, DCI);
10583   case AMDGPUISD::FRACT:
10584   case AMDGPUISD::RSQ:
10585   case AMDGPUISD::RCP_LEGACY:
10586   case AMDGPUISD::RCP_IFLAG:
10587   case AMDGPUISD::RSQ_CLAMP:
10588   case AMDGPUISD::LDEXP: {
10589     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10590     SDValue Src = N->getOperand(0);
10591     if (Src.isUndef())
10592       return Src;
10593     break;
10594   }
10595   case ISD::SINT_TO_FP:
10596   case ISD::UINT_TO_FP:
10597     return performUCharToFloatCombine(N, DCI);
10598   case AMDGPUISD::CVT_F32_UBYTE0:
10599   case AMDGPUISD::CVT_F32_UBYTE1:
10600   case AMDGPUISD::CVT_F32_UBYTE2:
10601   case AMDGPUISD::CVT_F32_UBYTE3:
10602     return performCvtF32UByteNCombine(N, DCI);
10603   case AMDGPUISD::FMED3:
10604     return performFMed3Combine(N, DCI);
10605   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10606     return performCvtPkRTZCombine(N, DCI);
10607   case AMDGPUISD::CLAMP:
10608     return performClampCombine(N, DCI);
10609   case ISD::SCALAR_TO_VECTOR: {
10610     SelectionDAG &DAG = DCI.DAG;
10611     EVT VT = N->getValueType(0);
10612 
10613     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10614     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10615       SDLoc SL(N);
10616       SDValue Src = N->getOperand(0);
10617       EVT EltVT = Src.getValueType();
10618       if (EltVT == MVT::f16)
10619         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10620 
10621       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10622       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10623     }
10624 
10625     break;
10626   }
10627   case ISD::EXTRACT_VECTOR_ELT:
10628     return performExtractVectorEltCombine(N, DCI);
10629   case ISD::INSERT_VECTOR_ELT:
10630     return performInsertVectorEltCombine(N, DCI);
10631   case ISD::LOAD: {
10632     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10633       return Widended;
10634     LLVM_FALLTHROUGH;
10635   }
10636   default: {
10637     if (!DCI.isBeforeLegalize()) {
10638       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10639         return performMemSDNodeCombine(MemNode, DCI);
10640     }
10641 
10642     break;
10643   }
10644   }
10645 
10646   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10647 }
10648 
10649 /// Helper function for adjustWritemask
10650 static unsigned SubIdx2Lane(unsigned Idx) {
10651   switch (Idx) {
10652   default: return 0;
10653   case AMDGPU::sub0: return 0;
10654   case AMDGPU::sub1: return 1;
10655   case AMDGPU::sub2: return 2;
10656   case AMDGPU::sub3: return 3;
10657   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10658   }
10659 }
10660 
10661 /// Adjust the writemask of MIMG instructions
10662 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10663                                           SelectionDAG &DAG) const {
10664   unsigned Opcode = Node->getMachineOpcode();
10665 
10666   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10667   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10668   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10669     return Node; // not implemented for D16
10670 
10671   SDNode *Users[5] = { nullptr };
10672   unsigned Lane = 0;
10673   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10674   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10675   unsigned NewDmask = 0;
10676   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10677   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10678   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10679                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10680   unsigned TFCLane = 0;
10681   bool HasChain = Node->getNumValues() > 1;
10682 
10683   if (OldDmask == 0) {
10684     // These are folded out, but on the chance it happens don't assert.
10685     return Node;
10686   }
10687 
10688   unsigned OldBitsSet = countPopulation(OldDmask);
10689   // Work out which is the TFE/LWE lane if that is enabled.
10690   if (UsesTFC) {
10691     TFCLane = OldBitsSet;
10692   }
10693 
10694   // Try to figure out the used register components
10695   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10696        I != E; ++I) {
10697 
10698     // Don't look at users of the chain.
10699     if (I.getUse().getResNo() != 0)
10700       continue;
10701 
10702     // Abort if we can't understand the usage
10703     if (!I->isMachineOpcode() ||
10704         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10705       return Node;
10706 
10707     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10708     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10709     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10710     // set, etc.
10711     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10712 
10713     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10714     if (UsesTFC && Lane == TFCLane) {
10715       Users[Lane] = *I;
10716     } else {
10717       // Set which texture component corresponds to the lane.
10718       unsigned Comp;
10719       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10720         Comp = countTrailingZeros(Dmask);
10721         Dmask &= ~(1 << Comp);
10722       }
10723 
10724       // Abort if we have more than one user per component.
10725       if (Users[Lane])
10726         return Node;
10727 
10728       Users[Lane] = *I;
10729       NewDmask |= 1 << Comp;
10730     }
10731   }
10732 
10733   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10734   bool NoChannels = !NewDmask;
10735   if (NoChannels) {
10736     if (!UsesTFC) {
10737       // No uses of the result and not using TFC. Then do nothing.
10738       return Node;
10739     }
10740     // If the original dmask has one channel - then nothing to do
10741     if (OldBitsSet == 1)
10742       return Node;
10743     // Use an arbitrary dmask - required for the instruction to work
10744     NewDmask = 1;
10745   }
10746   // Abort if there's no change
10747   if (NewDmask == OldDmask)
10748     return Node;
10749 
10750   unsigned BitsSet = countPopulation(NewDmask);
10751 
10752   // Check for TFE or LWE - increase the number of channels by one to account
10753   // for the extra return value
10754   // This will need adjustment for D16 if this is also included in
10755   // adjustWriteMask (this function) but at present D16 are excluded.
10756   unsigned NewChannels = BitsSet + UsesTFC;
10757 
10758   int NewOpcode =
10759       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10760   assert(NewOpcode != -1 &&
10761          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10762          "failed to find equivalent MIMG op");
10763 
10764   // Adjust the writemask in the node
10765   SmallVector<SDValue, 12> Ops;
10766   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10767   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10768   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10769 
10770   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10771 
10772   MVT ResultVT = NewChannels == 1 ?
10773     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10774                            NewChannels == 5 ? 8 : NewChannels);
10775   SDVTList NewVTList = HasChain ?
10776     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10777 
10778 
10779   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10780                                               NewVTList, Ops);
10781 
10782   if (HasChain) {
10783     // Update chain.
10784     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10785     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10786   }
10787 
10788   if (NewChannels == 1) {
10789     assert(Node->hasNUsesOfValue(1, 0));
10790     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10791                                       SDLoc(Node), Users[Lane]->getValueType(0),
10792                                       SDValue(NewNode, 0));
10793     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10794     return nullptr;
10795   }
10796 
10797   // Update the users of the node with the new indices
10798   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10799     SDNode *User = Users[i];
10800     if (!User) {
10801       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10802       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10803       if (i || !NoChannels)
10804         continue;
10805     } else {
10806       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10807       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10808     }
10809 
10810     switch (Idx) {
10811     default: break;
10812     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10813     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10814     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10815     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10816     }
10817   }
10818 
10819   DAG.RemoveDeadNode(Node);
10820   return nullptr;
10821 }
10822 
10823 static bool isFrameIndexOp(SDValue Op) {
10824   if (Op.getOpcode() == ISD::AssertZext)
10825     Op = Op.getOperand(0);
10826 
10827   return isa<FrameIndexSDNode>(Op);
10828 }
10829 
10830 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10831 /// with frame index operands.
10832 /// LLVM assumes that inputs are to these instructions are registers.
10833 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10834                                                         SelectionDAG &DAG) const {
10835   if (Node->getOpcode() == ISD::CopyToReg) {
10836     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10837     SDValue SrcVal = Node->getOperand(2);
10838 
10839     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10840     // to try understanding copies to physical registers.
10841     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
10842       SDLoc SL(Node);
10843       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10844       SDValue VReg = DAG.getRegister(
10845         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10846 
10847       SDNode *Glued = Node->getGluedNode();
10848       SDValue ToVReg
10849         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10850                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10851       SDValue ToResultReg
10852         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10853                            VReg, ToVReg.getValue(1));
10854       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10855       DAG.RemoveDeadNode(Node);
10856       return ToResultReg.getNode();
10857     }
10858   }
10859 
10860   SmallVector<SDValue, 8> Ops;
10861   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10862     if (!isFrameIndexOp(Node->getOperand(i))) {
10863       Ops.push_back(Node->getOperand(i));
10864       continue;
10865     }
10866 
10867     SDLoc DL(Node);
10868     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10869                                      Node->getOperand(i).getValueType(),
10870                                      Node->getOperand(i)), 0));
10871   }
10872 
10873   return DAG.UpdateNodeOperands(Node, Ops);
10874 }
10875 
10876 /// Fold the instructions after selecting them.
10877 /// Returns null if users were already updated.
10878 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10879                                           SelectionDAG &DAG) const {
10880   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10881   unsigned Opcode = Node->getMachineOpcode();
10882 
10883   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10884       !TII->isGather4(Opcode)) {
10885     return adjustWritemask(Node, DAG);
10886   }
10887 
10888   if (Opcode == AMDGPU::INSERT_SUBREG ||
10889       Opcode == AMDGPU::REG_SEQUENCE) {
10890     legalizeTargetIndependentNode(Node, DAG);
10891     return Node;
10892   }
10893 
10894   switch (Opcode) {
10895   case AMDGPU::V_DIV_SCALE_F32:
10896   case AMDGPU::V_DIV_SCALE_F64: {
10897     // Satisfy the operand register constraint when one of the inputs is
10898     // undefined. Ordinarily each undef value will have its own implicit_def of
10899     // a vreg, so force these to use a single register.
10900     SDValue Src0 = Node->getOperand(0);
10901     SDValue Src1 = Node->getOperand(1);
10902     SDValue Src2 = Node->getOperand(2);
10903 
10904     if ((Src0.isMachineOpcode() &&
10905          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10906         (Src0 == Src1 || Src0 == Src2))
10907       break;
10908 
10909     MVT VT = Src0.getValueType().getSimpleVT();
10910     const TargetRegisterClass *RC =
10911         getRegClassFor(VT, Src0.getNode()->isDivergent());
10912 
10913     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10914     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10915 
10916     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10917                                       UndefReg, Src0, SDValue());
10918 
10919     // src0 must be the same register as src1 or src2, even if the value is
10920     // undefined, so make sure we don't violate this constraint.
10921     if (Src0.isMachineOpcode() &&
10922         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10923       if (Src1.isMachineOpcode() &&
10924           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10925         Src0 = Src1;
10926       else if (Src2.isMachineOpcode() &&
10927                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10928         Src0 = Src2;
10929       else {
10930         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10931         Src0 = UndefReg;
10932         Src1 = UndefReg;
10933       }
10934     } else
10935       break;
10936 
10937     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10938     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10939       Ops.push_back(Node->getOperand(I));
10940 
10941     Ops.push_back(ImpDef.getValue(1));
10942     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10943   }
10944   default:
10945     break;
10946   }
10947 
10948   return Node;
10949 }
10950 
10951 /// Assign the register class depending on the number of
10952 /// bits set in the writemask
10953 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10954                                                      SDNode *Node) const {
10955   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10956 
10957   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10958 
10959   if (TII->isVOP3(MI.getOpcode())) {
10960     // Make sure constant bus requirements are respected.
10961     TII->legalizeOperandsVOP3(MRI, MI);
10962 
10963     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10964     // This saves a chain-copy of registers and better ballance register
10965     // use between vgpr and agpr as agpr tuples tend to be big.
10966     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10967       unsigned Opc = MI.getOpcode();
10968       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10969       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10970                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10971         if (I == -1)
10972           break;
10973         MachineOperand &Op = MI.getOperand(I);
10974         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10975              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10976             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
10977           continue;
10978         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10979         if (!Src || !Src->isCopy() ||
10980             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10981           continue;
10982         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10983         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10984         // All uses of agpr64 and agpr32 can also accept vgpr except for
10985         // v_accvgpr_read, but we do not produce agpr reads during selection,
10986         // so no use checks are needed.
10987         MRI.setRegClass(Op.getReg(), NewRC);
10988       }
10989     }
10990 
10991     return;
10992   }
10993 
10994   // Replace unused atomics with the no return version.
10995   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10996   if (NoRetAtomicOp != -1) {
10997     if (!Node->hasAnyUseOfValue(0)) {
10998       MI.setDesc(TII->get(NoRetAtomicOp));
10999       MI.RemoveOperand(0);
11000       return;
11001     }
11002 
11003     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11004     // instruction, because the return type of these instructions is a vec2 of
11005     // the memory type, so it can be tied to the input operand.
11006     // This means these instructions always have a use, so we need to add a
11007     // special case to check if the atomic has only one extract_subreg use,
11008     // which itself has no uses.
11009     if ((Node->hasNUsesOfValue(1, 0) &&
11010          Node->use_begin()->isMachineOpcode() &&
11011          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11012          !Node->use_begin()->hasAnyUseOfValue(0))) {
11013       Register Def = MI.getOperand(0).getReg();
11014 
11015       // Change this into a noret atomic.
11016       MI.setDesc(TII->get(NoRetAtomicOp));
11017       MI.RemoveOperand(0);
11018 
11019       // If we only remove the def operand from the atomic instruction, the
11020       // extract_subreg will be left with a use of a vreg without a def.
11021       // So we need to insert an implicit_def to avoid machine verifier
11022       // errors.
11023       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11024               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11025     }
11026     return;
11027   }
11028 }
11029 
11030 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11031                               uint64_t Val) {
11032   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11033   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11034 }
11035 
11036 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11037                                                 const SDLoc &DL,
11038                                                 SDValue Ptr) const {
11039   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11040 
11041   // Build the half of the subregister with the constants before building the
11042   // full 128-bit register. If we are building multiple resource descriptors,
11043   // this will allow CSEing of the 2-component register.
11044   const SDValue Ops0[] = {
11045     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11046     buildSMovImm32(DAG, DL, 0),
11047     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11048     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11049     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11050   };
11051 
11052   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11053                                                 MVT::v2i32, Ops0), 0);
11054 
11055   // Combine the constants and the pointer.
11056   const SDValue Ops1[] = {
11057     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11058     Ptr,
11059     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11060     SubRegHi,
11061     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11062   };
11063 
11064   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11065 }
11066 
11067 /// Return a resource descriptor with the 'Add TID' bit enabled
11068 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11069 ///        of the resource descriptor) to create an offset, which is added to
11070 ///        the resource pointer.
11071 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11072                                            SDValue Ptr, uint32_t RsrcDword1,
11073                                            uint64_t RsrcDword2And3) const {
11074   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11075   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11076   if (RsrcDword1) {
11077     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11078                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11079                     0);
11080   }
11081 
11082   SDValue DataLo = buildSMovImm32(DAG, DL,
11083                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11084   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11085 
11086   const SDValue Ops[] = {
11087     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11088     PtrLo,
11089     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11090     PtrHi,
11091     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11092     DataLo,
11093     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11094     DataHi,
11095     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11096   };
11097 
11098   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11099 }
11100 
11101 //===----------------------------------------------------------------------===//
11102 //                         SI Inline Assembly Support
11103 //===----------------------------------------------------------------------===//
11104 
11105 std::pair<unsigned, const TargetRegisterClass *>
11106 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11107                                                StringRef Constraint,
11108                                                MVT VT) const {
11109   const TargetRegisterClass *RC = nullptr;
11110   if (Constraint.size() == 1) {
11111     const unsigned BitWidth = VT.getSizeInBits();
11112     switch (Constraint[0]) {
11113     default:
11114       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11115     case 's':
11116     case 'r':
11117       switch (BitWidth) {
11118       case 16:
11119         RC = &AMDGPU::SReg_32RegClass;
11120         break;
11121       case 64:
11122         RC = &AMDGPU::SGPR_64RegClass;
11123         break;
11124       default:
11125         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11126         if (!RC)
11127           return std::make_pair(0U, nullptr);
11128         break;
11129       }
11130       break;
11131     case 'v':
11132       switch (BitWidth) {
11133       case 16:
11134         RC = &AMDGPU::VGPR_32RegClass;
11135         break;
11136       default:
11137         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11138         if (!RC)
11139           return std::make_pair(0U, nullptr);
11140         break;
11141       }
11142       break;
11143     case 'a':
11144       if (!Subtarget->hasMAIInsts())
11145         break;
11146       switch (BitWidth) {
11147       case 16:
11148         RC = &AMDGPU::AGPR_32RegClass;
11149         break;
11150       default:
11151         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11152         if (!RC)
11153           return std::make_pair(0U, nullptr);
11154         break;
11155       }
11156       break;
11157     }
11158     // We actually support i128, i16 and f16 as inline parameters
11159     // even if they are not reported as legal
11160     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11161                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11162       return std::make_pair(0U, RC);
11163   }
11164 
11165   if (Constraint.size() > 1) {
11166     if (Constraint[1] == 'v') {
11167       RC = &AMDGPU::VGPR_32RegClass;
11168     } else if (Constraint[1] == 's') {
11169       RC = &AMDGPU::SGPR_32RegClass;
11170     } else if (Constraint[1] == 'a') {
11171       RC = &AMDGPU::AGPR_32RegClass;
11172     }
11173 
11174     if (RC) {
11175       uint32_t Idx;
11176       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11177       if (!Failed && Idx < RC->getNumRegs())
11178         return std::make_pair(RC->getRegister(Idx), RC);
11179     }
11180   }
11181 
11182   // FIXME: Returns VS_32 for physical SGPR constraints
11183   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11184 }
11185 
11186 static bool isImmConstraint(StringRef Constraint) {
11187   if (Constraint.size() == 1) {
11188     switch (Constraint[0]) {
11189     default: break;
11190     case 'I':
11191     case 'J':
11192     case 'A':
11193     case 'B':
11194     case 'C':
11195       return true;
11196     }
11197   } else if (Constraint == "DA" ||
11198              Constraint == "DB") {
11199     return true;
11200   }
11201   return false;
11202 }
11203 
11204 SITargetLowering::ConstraintType
11205 SITargetLowering::getConstraintType(StringRef Constraint) const {
11206   if (Constraint.size() == 1) {
11207     switch (Constraint[0]) {
11208     default: break;
11209     case 's':
11210     case 'v':
11211     case 'a':
11212       return C_RegisterClass;
11213     }
11214   }
11215   if (isImmConstraint(Constraint)) {
11216     return C_Other;
11217   }
11218   return TargetLowering::getConstraintType(Constraint);
11219 }
11220 
11221 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11222   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11223     Val = Val & maskTrailingOnes<uint64_t>(Size);
11224   }
11225   return Val;
11226 }
11227 
11228 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11229                                                     std::string &Constraint,
11230                                                     std::vector<SDValue> &Ops,
11231                                                     SelectionDAG &DAG) const {
11232   if (isImmConstraint(Constraint)) {
11233     uint64_t Val;
11234     if (getAsmOperandConstVal(Op, Val) &&
11235         checkAsmConstraintVal(Op, Constraint, Val)) {
11236       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11237       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11238     }
11239   } else {
11240     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11241   }
11242 }
11243 
11244 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11245   unsigned Size = Op.getScalarValueSizeInBits();
11246   if (Size > 64)
11247     return false;
11248 
11249   if (Size == 16 && !Subtarget->has16BitInsts())
11250     return false;
11251 
11252   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11253     Val = C->getSExtValue();
11254     return true;
11255   }
11256   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11257     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11258     return true;
11259   }
11260   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11261     if (Size != 16 || Op.getNumOperands() != 2)
11262       return false;
11263     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11264       return false;
11265     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11266       Val = C->getSExtValue();
11267       return true;
11268     }
11269     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11270       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11271       return true;
11272     }
11273   }
11274 
11275   return false;
11276 }
11277 
11278 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11279                                              const std::string &Constraint,
11280                                              uint64_t Val) const {
11281   if (Constraint.size() == 1) {
11282     switch (Constraint[0]) {
11283     case 'I':
11284       return AMDGPU::isInlinableIntLiteral(Val);
11285     case 'J':
11286       return isInt<16>(Val);
11287     case 'A':
11288       return checkAsmConstraintValA(Op, Val);
11289     case 'B':
11290       return isInt<32>(Val);
11291     case 'C':
11292       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11293              AMDGPU::isInlinableIntLiteral(Val);
11294     default:
11295       break;
11296     }
11297   } else if (Constraint.size() == 2) {
11298     if (Constraint == "DA") {
11299       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11300       int64_t LoBits = static_cast<int32_t>(Val);
11301       return checkAsmConstraintValA(Op, HiBits, 32) &&
11302              checkAsmConstraintValA(Op, LoBits, 32);
11303     }
11304     if (Constraint == "DB") {
11305       return true;
11306     }
11307   }
11308   llvm_unreachable("Invalid asm constraint");
11309 }
11310 
11311 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11312                                               uint64_t Val,
11313                                               unsigned MaxSize) const {
11314   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11315   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11316   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11317       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11318       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11319     return true;
11320   }
11321   return false;
11322 }
11323 
11324 // Figure out which registers should be reserved for stack access. Only after
11325 // the function is legalized do we know all of the non-spill stack objects or if
11326 // calls are present.
11327 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11328   MachineRegisterInfo &MRI = MF.getRegInfo();
11329   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11330   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11331   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11332 
11333   if (Info->isEntryFunction()) {
11334     // Callable functions have fixed registers used for stack access.
11335     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11336   }
11337 
11338   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11339                              Info->getStackPtrOffsetReg()));
11340   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11341     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11342 
11343   // We need to worry about replacing the default register with itself in case
11344   // of MIR testcases missing the MFI.
11345   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11346     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11347 
11348   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11349     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11350 
11351   Info->limitOccupancy(MF);
11352 
11353   if (ST.isWave32() && !MF.empty()) {
11354     // Add VCC_HI def because many instructions marked as imp-use VCC where
11355     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11356     // having a use of undef.
11357 
11358     const SIInstrInfo *TII = ST.getInstrInfo();
11359     DebugLoc DL;
11360 
11361     MachineBasicBlock &MBB = MF.front();
11362     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11363     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11364 
11365     for (auto &MBB : MF) {
11366       for (auto &MI : MBB) {
11367         TII->fixImplicitOperands(MI);
11368       }
11369     }
11370   }
11371 
11372   TargetLoweringBase::finalizeLowering(MF);
11373 
11374   // Allocate a VGPR for future SGPR Spill if
11375   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11376   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11377   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11378       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11379     Info->reserveVGPRforSGPRSpills(MF);
11380 }
11381 
11382 void SITargetLowering::computeKnownBitsForFrameIndex(
11383   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11384   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11385 
11386   // Set the high bits to zero based on the maximum allowed scratch size per
11387   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11388   // calculation won't overflow, so assume the sign bit is never set.
11389   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11390 }
11391 
11392 Align SITargetLowering::computeKnownAlignForTargetInstr(
11393   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11394   unsigned Depth) const {
11395   const MachineInstr *MI = MRI.getVRegDef(R);
11396   switch (MI->getOpcode()) {
11397   case AMDGPU::G_INTRINSIC:
11398   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11399     // FIXME: Can this move to generic code? What about the case where the call
11400     // site specifies a lower alignment?
11401     Intrinsic::ID IID = MI->getIntrinsicID();
11402     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11403     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11404     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11405       return *RetAlign;
11406     return Align(1);
11407   }
11408   default:
11409     return Align(1);
11410   }
11411 }
11412 
11413 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11414   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11415   const Align CacheLineAlign = Align(64);
11416 
11417   // Pre-GFX10 target did not benefit from loop alignment
11418   if (!ML || DisableLoopAlignment ||
11419       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11420       getSubtarget()->hasInstFwdPrefetchBug())
11421     return PrefAlign;
11422 
11423   // On GFX10 I$ is 4 x 64 bytes cache lines.
11424   // By default prefetcher keeps one cache line behind and reads two ahead.
11425   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11426   // behind and one ahead.
11427   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11428   // If loop fits 64 bytes it always spans no more than two cache lines and
11429   // does not need an alignment.
11430   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11431   // Else if loop is less or equal 192 bytes we need two lines behind.
11432 
11433   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11434   const MachineBasicBlock *Header = ML->getHeader();
11435   if (Header->getAlignment() != PrefAlign)
11436     return Header->getAlignment(); // Already processed.
11437 
11438   unsigned LoopSize = 0;
11439   for (const MachineBasicBlock *MBB : ML->blocks()) {
11440     // If inner loop block is aligned assume in average half of the alignment
11441     // size to be added as nops.
11442     if (MBB != Header)
11443       LoopSize += MBB->getAlignment().value() / 2;
11444 
11445     for (const MachineInstr &MI : *MBB) {
11446       LoopSize += TII->getInstSizeInBytes(MI);
11447       if (LoopSize > 192)
11448         return PrefAlign;
11449     }
11450   }
11451 
11452   if (LoopSize <= 64)
11453     return PrefAlign;
11454 
11455   if (LoopSize <= 128)
11456     return CacheLineAlign;
11457 
11458   // If any of parent loops is surrounded by prefetch instructions do not
11459   // insert new for inner loop, which would reset parent's settings.
11460   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11461     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11462       auto I = Exit->getFirstNonDebugInstr();
11463       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11464         return CacheLineAlign;
11465     }
11466   }
11467 
11468   MachineBasicBlock *Pre = ML->getLoopPreheader();
11469   MachineBasicBlock *Exit = ML->getExitBlock();
11470 
11471   if (Pre && Exit) {
11472     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11473             TII->get(AMDGPU::S_INST_PREFETCH))
11474       .addImm(1); // prefetch 2 lines behind PC
11475 
11476     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11477             TII->get(AMDGPU::S_INST_PREFETCH))
11478       .addImm(2); // prefetch 1 line behind PC
11479   }
11480 
11481   return CacheLineAlign;
11482 }
11483 
11484 LLVM_ATTRIBUTE_UNUSED
11485 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11486   assert(N->getOpcode() == ISD::CopyFromReg);
11487   do {
11488     // Follow the chain until we find an INLINEASM node.
11489     N = N->getOperand(0).getNode();
11490     if (N->getOpcode() == ISD::INLINEASM ||
11491         N->getOpcode() == ISD::INLINEASM_BR)
11492       return true;
11493   } while (N->getOpcode() == ISD::CopyFromReg);
11494   return false;
11495 }
11496 
11497 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11498   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11499 {
11500   switch (N->getOpcode()) {
11501     case ISD::CopyFromReg:
11502     {
11503       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11504       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11505       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11506       Register Reg = R->getReg();
11507 
11508       // FIXME: Why does this need to consider isLiveIn?
11509       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11510         return !TRI->isSGPRReg(MRI, Reg);
11511 
11512       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11513         return KDA->isDivergent(V);
11514 
11515       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11516       return !TRI->isSGPRReg(MRI, Reg);
11517     }
11518     break;
11519     case ISD::LOAD: {
11520       const LoadSDNode *L = cast<LoadSDNode>(N);
11521       unsigned AS = L->getAddressSpace();
11522       // A flat load may access private memory.
11523       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11524     } break;
11525     case ISD::CALLSEQ_END:
11526     return true;
11527     break;
11528     case ISD::INTRINSIC_WO_CHAIN:
11529     {
11530 
11531     }
11532       return AMDGPU::isIntrinsicSourceOfDivergence(
11533       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11534     case ISD::INTRINSIC_W_CHAIN:
11535       return AMDGPU::isIntrinsicSourceOfDivergence(
11536       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11537   }
11538   return false;
11539 }
11540 
11541 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11542                                                EVT VT) const {
11543   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11544   case MVT::f32:
11545     return hasFP32Denormals(DAG.getMachineFunction());
11546   case MVT::f64:
11547   case MVT::f16:
11548     return hasFP64FP16Denormals(DAG.getMachineFunction());
11549   default:
11550     return false;
11551   }
11552 }
11553 
11554 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11555                                                     const SelectionDAG &DAG,
11556                                                     bool SNaN,
11557                                                     unsigned Depth) const {
11558   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11559     const MachineFunction &MF = DAG.getMachineFunction();
11560     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11561 
11562     if (Info->getMode().DX10Clamp)
11563       return true; // Clamped to 0.
11564     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11565   }
11566 
11567   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11568                                                             SNaN, Depth);
11569 }
11570 
11571 TargetLowering::AtomicExpansionKind
11572 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11573   switch (RMW->getOperation()) {
11574   case AtomicRMWInst::FAdd: {
11575     Type *Ty = RMW->getType();
11576 
11577     // We don't have a way to support 16-bit atomics now, so just leave them
11578     // as-is.
11579     if (Ty->isHalfTy())
11580       return AtomicExpansionKind::None;
11581 
11582     if (!Ty->isFloatTy())
11583       return AtomicExpansionKind::CmpXChg;
11584 
11585     // TODO: Do have these for flat. Older targets also had them for buffers.
11586     unsigned AS = RMW->getPointerAddressSpace();
11587 
11588     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11589       return RMW->use_empty() ? AtomicExpansionKind::None :
11590                                 AtomicExpansionKind::CmpXChg;
11591     }
11592 
11593     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11594       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11595   }
11596   default:
11597     break;
11598   }
11599 
11600   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11601 }
11602 
11603 const TargetRegisterClass *
11604 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11605   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11606   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11607   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11608     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11609                                                : &AMDGPU::SReg_32RegClass;
11610   if (!TRI->isSGPRClass(RC) && !isDivergent)
11611     return TRI->getEquivalentSGPRClass(RC);
11612   else if (TRI->isSGPRClass(RC) && isDivergent)
11613     return TRI->getEquivalentVGPRClass(RC);
11614 
11615   return RC;
11616 }
11617 
11618 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11619 // uniform values (as produced by the mask results of control flow intrinsics)
11620 // used outside of divergent blocks. The phi users need to also be treated as
11621 // always uniform.
11622 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11623                       unsigned WaveSize) {
11624   // FIXME: We asssume we never cast the mask results of a control flow
11625   // intrinsic.
11626   // Early exit if the type won't be consistent as a compile time hack.
11627   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11628   if (!IT || IT->getBitWidth() != WaveSize)
11629     return false;
11630 
11631   if (!isa<Instruction>(V))
11632     return false;
11633   if (!Visited.insert(V).second)
11634     return false;
11635   bool Result = false;
11636   for (auto U : V->users()) {
11637     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11638       if (V == U->getOperand(1)) {
11639         switch (Intrinsic->getIntrinsicID()) {
11640         default:
11641           Result = false;
11642           break;
11643         case Intrinsic::amdgcn_if_break:
11644         case Intrinsic::amdgcn_if:
11645         case Intrinsic::amdgcn_else:
11646           Result = true;
11647           break;
11648         }
11649       }
11650       if (V == U->getOperand(0)) {
11651         switch (Intrinsic->getIntrinsicID()) {
11652         default:
11653           Result = false;
11654           break;
11655         case Intrinsic::amdgcn_end_cf:
11656         case Intrinsic::amdgcn_loop:
11657           Result = true;
11658           break;
11659         }
11660       }
11661     } else {
11662       Result = hasCFUser(U, Visited, WaveSize);
11663     }
11664     if (Result)
11665       break;
11666   }
11667   return Result;
11668 }
11669 
11670 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11671                                                const Value *V) const {
11672   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11673     if (CI->isInlineAsm()) {
11674       // FIXME: This cannot give a correct answer. This should only trigger in
11675       // the case where inline asm returns mixed SGPR and VGPR results, used
11676       // outside the defining block. We don't have a specific result to
11677       // consider, so this assumes if any value is SGPR, the overall register
11678       // also needs to be SGPR.
11679       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11680       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11681           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11682       for (auto &TC : TargetConstraints) {
11683         if (TC.Type == InlineAsm::isOutput) {
11684           ComputeConstraintToUse(TC, SDValue());
11685           unsigned AssignedReg;
11686           const TargetRegisterClass *RC;
11687           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11688               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11689           if (RC) {
11690             MachineRegisterInfo &MRI = MF.getRegInfo();
11691             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11692               return true;
11693             else if (SIRI->isSGPRClass(RC))
11694               return true;
11695           }
11696         }
11697       }
11698     }
11699   }
11700   SmallPtrSet<const Value *, 16> Visited;
11701   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11702 }
11703 
11704 std::pair<int, MVT>
11705 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11706                                           Type *Ty) const {
11707   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11708   auto Size = DL.getTypeSizeInBits(Ty);
11709   // Maximum load or store can handle 8 dwords for scalar and 4 for
11710   // vector ALU. Let's assume anything above 8 dwords is expensive
11711   // even if legal.
11712   if (Size <= 256)
11713     return Cost;
11714 
11715   Cost.first = (Size + 255) / 256;
11716   return Cost;
11717 }
11718