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/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstr.h"
42 #include "llvm/CodeGen/MachineInstrBuilder.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineMemOperand.h"
45 #include "llvm/CodeGen/MachineModuleInfo.h"
46 #include "llvm/CodeGen/MachineOperand.h"
47 #include "llvm/CodeGen/MachineRegisterInfo.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGNodes.h"
50 #include "llvm/CodeGen/TargetCallingConv.h"
51 #include "llvm/CodeGen/TargetRegisterInfo.h"
52 #include "llvm/CodeGen/ValueTypes.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DebugLoc.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/DiagnosticInfo.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/GlobalValue.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Type.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CodeGen.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/KnownBits.h"
71 #include "llvm/Support/MachineValueType.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Target/TargetOptions.h"
74 #include <cassert>
75 #include <cmath>
76 #include <cstdint>
77 #include <iterator>
78 #include <tuple>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 #define DEBUG_TYPE "si-lower"
85 
86 STATISTIC(NumTailCalls, "Number of tail calls");
87 
88 static cl::opt<bool> DisableLoopAlignment(
89   "amdgpu-disable-loop-alignment",
90   cl::desc("Do not align and prefetch loops"),
91   cl::init(false));
92 
93 static cl::opt<bool> VGPRReserveforSGPRSpill(
94     "amdgpu-reserve-vgpr-for-sgpr-spill",
95     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
96 
97 static cl::opt<bool> UseDivergentRegisterIndexing(
98   "amdgpu-use-divergent-register-indexing",
99   cl::Hidden,
100   cl::desc("Use indirect register addressing for divergent indexes"),
101   cl::init(false));
102 
103 static bool hasFP32Denormals(const MachineFunction &MF) {
104   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
105   return Info->getMode().allFP32Denormals();
106 }
107 
108 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
109   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
110   return Info->getMode().allFP64FP16Denormals();
111 }
112 
113 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
114   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
115   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
116     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
117       return AMDGPU::SGPR0 + Reg;
118     }
119   }
120   llvm_unreachable("Cannot allocate sgpr");
121 }
122 
123 SITargetLowering::SITargetLowering(const TargetMachine &TM,
124                                    const GCNSubtarget &STI)
125     : AMDGPUTargetLowering(TM, STI),
126       Subtarget(&STI) {
127   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
128   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
129 
130   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
131   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
132 
133   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
134   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
135   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
136 
137   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
138   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
139 
140   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
141   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
142 
143   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
144   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
145 
146   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
147   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
148 
149   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
150   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
151 
152   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
153   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
154 
155   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
156   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
157 
158   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
159   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
160 
161   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
162   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
163 
164   if (Subtarget->has16BitInsts()) {
165     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
166     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
167 
168     // Unless there are also VOP3P operations, not operations are really legal.
169     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
170     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
171     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
172     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
173   }
174 
175   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
176   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
177 
178   computeRegisterProperties(Subtarget->getRegisterInfo());
179 
180   // The boolean content concept here is too inflexible. Compares only ever
181   // really produce a 1-bit result. Any copy/extend from these will turn into a
182   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
183   // it's what most targets use.
184   setBooleanContents(ZeroOrOneBooleanContent);
185   setBooleanVectorContents(ZeroOrOneBooleanContent);
186 
187   // We need to custom lower vector stores from local memory
188   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
189   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
190   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::i1, Custom);
195   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
196 
197   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
198   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
199   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
203   setOperationAction(ISD::STORE, MVT::i1, Custom);
204   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
205 
206   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
207   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
208   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
209   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
210   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
211   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
212   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
213   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
214   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
215   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
216   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
217   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
218   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
219   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
220   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
221   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
222 
223   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
224   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
225   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
227   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
228 
229   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
230   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
231 
232   setOperationAction(ISD::SELECT, MVT::i1, Promote);
233   setOperationAction(ISD::SELECT, MVT::i64, Custom);
234   setOperationAction(ISD::SELECT, MVT::f64, Promote);
235   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
236 
237   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
238   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
239   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
242 
243   setOperationAction(ISD::SETCC, MVT::i1, Promote);
244   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
245   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
246   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
247 
248   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
249   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
250   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
251   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
252   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
253   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
254   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
255   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
256 
257   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
258   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
265 
266   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
267   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
268   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
269   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
270   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
271   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
272 
273   setOperationAction(ISD::UADDO, MVT::i32, Legal);
274   setOperationAction(ISD::USUBO, MVT::i32, Legal);
275 
276   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
277   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
278 
279   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
280   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
281   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
282 
283 #if 0
284   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
285   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
286 #endif
287 
288   // We only support LOAD/STORE and vector manipulation ops for vectors
289   // with > 4 elements.
290   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
291                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
292                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
293                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
294     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
295       switch (Op) {
296       case ISD::LOAD:
297       case ISD::STORE:
298       case ISD::BUILD_VECTOR:
299       case ISD::BITCAST:
300       case ISD::EXTRACT_VECTOR_ELT:
301       case ISD::INSERT_VECTOR_ELT:
302       case ISD::INSERT_SUBVECTOR:
303       case ISD::EXTRACT_SUBVECTOR:
304       case ISD::SCALAR_TO_VECTOR:
305         break;
306       case ISD::CONCAT_VECTORS:
307         setOperationAction(Op, VT, Custom);
308         break;
309       default:
310         setOperationAction(Op, VT, Expand);
311         break;
312       }
313     }
314   }
315 
316   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
317 
318   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
319   // is expanded to avoid having two separate loops in case the index is a VGPR.
320 
321   // Most operations are naturally 32-bit vector operations. We only support
322   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
323   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
324     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
325     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
326 
327     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
328     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
329 
330     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
331     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
332 
333     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
334     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
335   }
336 
337   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
338     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
339     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
340 
341     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
342     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
343 
344     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
345     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
346 
347     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
348     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
349   }
350 
351   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
352     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
353     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
354 
355     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
356     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
357 
358     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
359     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
360 
361     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
362     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
363   }
364 
365   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
366     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
367     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
368 
369     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
370     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
371 
372     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
373     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
374 
375     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
376     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
377   }
378 
379   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
383 
384   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
385   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
386 
387   // Avoid stack access for these.
388   // TODO: Generalize to more vector types.
389   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
393 
394   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
395   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
399 
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
403 
404   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
405   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
406   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
407   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
408 
409   // Deal with vec3 vector operations when widened to vec4.
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
414 
415   // Deal with vec5 vector operations when widened to vec8.
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
420 
421   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
422   // and output demarshalling
423   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
424   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
425 
426   // We can't return success/failure, only the old value,
427   // let LLVM add the comparison
428   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
429   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
430 
431   if (Subtarget->hasFlatAddressSpace()) {
432     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
433     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
434   }
435 
436   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
437 
438   // FIXME: This should be narrowed to i32, but that only happens if i64 is
439   // illegal.
440   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
441   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
442   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
443 
444   // On SI this is s_memtime and s_memrealtime on VI.
445   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
446   setOperationAction(ISD::TRAP, MVT::Other, Custom);
447   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
448 
449   if (Subtarget->has16BitInsts()) {
450     setOperationAction(ISD::FPOW, MVT::f16, Promote);
451     setOperationAction(ISD::FLOG, MVT::f16, Custom);
452     setOperationAction(ISD::FEXP, MVT::f16, Custom);
453     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
454   }
455 
456   // v_mad_f32 does not support denormals. We report it as unconditionally
457   // legal, and the context where it is formed will disallow it when fp32
458   // denormals are enabled.
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   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
491   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
492   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
493   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
494 
495 
496   // These are really only legal for ieee_mode functions. We should be avoiding
497   // them for functions that don't have ieee_mode enabled, so just say they are
498   // legal.
499   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
500   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
501   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
502   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
503 
504 
505   if (Subtarget->haveRoundOpsF64()) {
506     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
507     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
508     setOperationAction(ISD::FRINT, MVT::f64, Legal);
509   } else {
510     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
511     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
512     setOperationAction(ISD::FRINT, MVT::f64, Custom);
513     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
514   }
515 
516   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
517 
518   setOperationAction(ISD::FSIN, MVT::f32, Custom);
519   setOperationAction(ISD::FCOS, MVT::f32, Custom);
520   setOperationAction(ISD::FDIV, MVT::f32, Custom);
521   setOperationAction(ISD::FDIV, MVT::f64, Custom);
522 
523   if (Subtarget->has16BitInsts()) {
524     setOperationAction(ISD::Constant, MVT::i16, Legal);
525 
526     setOperationAction(ISD::SMIN, MVT::i16, Legal);
527     setOperationAction(ISD::SMAX, MVT::i16, Legal);
528 
529     setOperationAction(ISD::UMIN, MVT::i16, Legal);
530     setOperationAction(ISD::UMAX, MVT::i16, Legal);
531 
532     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
533     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
534 
535     setOperationAction(ISD::ROTR, MVT::i16, Promote);
536     setOperationAction(ISD::ROTL, MVT::i16, Promote);
537 
538     setOperationAction(ISD::SDIV, MVT::i16, Promote);
539     setOperationAction(ISD::UDIV, MVT::i16, Promote);
540     setOperationAction(ISD::SREM, MVT::i16, Promote);
541     setOperationAction(ISD::UREM, MVT::i16, Promote);
542 
543     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
544 
545     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
546     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
547     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
548     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
549     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
550 
551     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
552 
553     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
554 
555     setOperationAction(ISD::LOAD, MVT::i16, Custom);
556 
557     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
558 
559     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
560     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
561     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
562     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
563 
564     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
565     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
566 
567     // F16 - Constant Actions.
568     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
569 
570     // F16 - Load/Store Actions.
571     setOperationAction(ISD::LOAD, MVT::f16, Promote);
572     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
573     setOperationAction(ISD::STORE, MVT::f16, Promote);
574     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
575 
576     // F16 - VOP1 Actions.
577     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
578     setOperationAction(ISD::FCOS, MVT::f16, Custom);
579     setOperationAction(ISD::FSIN, MVT::f16, Custom);
580 
581     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
582     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
583 
584     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
585     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
586     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
587     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
588     setOperationAction(ISD::FROUND, MVT::f16, Custom);
589 
590     // F16 - VOP2 Actions.
591     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
592     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
593 
594     setOperationAction(ISD::FDIV, MVT::f16, Custom);
595 
596     // F16 - VOP3 Actions.
597     setOperationAction(ISD::FMA, MVT::f16, Legal);
598     if (STI.hasMadF16())
599       setOperationAction(ISD::FMAD, MVT::f16, Legal);
600 
601     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
602       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
603         switch (Op) {
604         case ISD::LOAD:
605         case ISD::STORE:
606         case ISD::BUILD_VECTOR:
607         case ISD::BITCAST:
608         case ISD::EXTRACT_VECTOR_ELT:
609         case ISD::INSERT_VECTOR_ELT:
610         case ISD::INSERT_SUBVECTOR:
611         case ISD::EXTRACT_SUBVECTOR:
612         case ISD::SCALAR_TO_VECTOR:
613           break;
614         case ISD::CONCAT_VECTORS:
615           setOperationAction(Op, VT, Custom);
616           break;
617         default:
618           setOperationAction(Op, VT, Expand);
619           break;
620         }
621       }
622     }
623 
624     // v_perm_b32 can handle either of these.
625     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
626     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
627     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
628 
629     // XXX - Do these do anything? Vector constants turn into build_vector.
630     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
631     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
632 
633     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
634     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
635 
636     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
637     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
638     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
639     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
640 
641     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
642     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
643     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
644     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
645 
646     setOperationAction(ISD::AND, MVT::v2i16, Promote);
647     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
648     setOperationAction(ISD::OR, MVT::v2i16, Promote);
649     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
650     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
651     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
652 
653     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
654     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
655     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
656     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
657 
658     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
659     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
660     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
661     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
662 
663     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
664     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
665     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
666     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
667 
668     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
669     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
670     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
671 
672     if (!Subtarget->hasVOP3PInsts()) {
673       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
674       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
675     }
676 
677     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
678     // This isn't really legal, but this avoids the legalizer unrolling it (and
679     // allows matching fneg (fabs x) patterns)
680     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
681 
682     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
683     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
684     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
685     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
686 
687     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
688     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
689 
690     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
691     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
692   }
693 
694   if (Subtarget->hasVOP3PInsts()) {
695     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
696     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
697     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
698     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
699     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
700     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
701     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
702     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
703     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
704     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
705 
706     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
707     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
708     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
709 
710     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
711     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
712 
713     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
714 
715     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
716     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
717 
718     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
719     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
720 
721     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
722     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
723     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
724     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
725     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
726     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
727 
728     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
729     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
730     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
731     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
732 
733     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
734     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
735     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
736 
737     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
738     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
739 
740     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
741     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
742     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
743 
744     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
745     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
746     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
747   }
748 
749   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
750   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
751 
752   if (Subtarget->has16BitInsts()) {
753     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
754     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
755     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
756     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
757   } else {
758     // Legalization hack.
759     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
760     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
761 
762     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
763     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
764   }
765 
766   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
767     setOperationAction(ISD::SELECT, VT, Custom);
768   }
769 
770   setOperationAction(ISD::SMULO, MVT::i64, Custom);
771   setOperationAction(ISD::UMULO, MVT::i64, Custom);
772 
773   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
774   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
775   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
776   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
777   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
778   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
779   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
780 
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
783   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
784   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
785   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
786   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
787   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
788   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
789   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
790 
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
794   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
795   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
796   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
797   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
798   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
799 
800   setTargetDAGCombine(ISD::ADD);
801   setTargetDAGCombine(ISD::ADDCARRY);
802   setTargetDAGCombine(ISD::SUB);
803   setTargetDAGCombine(ISD::SUBCARRY);
804   setTargetDAGCombine(ISD::FADD);
805   setTargetDAGCombine(ISD::FSUB);
806   setTargetDAGCombine(ISD::FMINNUM);
807   setTargetDAGCombine(ISD::FMAXNUM);
808   setTargetDAGCombine(ISD::FMINNUM_IEEE);
809   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
810   setTargetDAGCombine(ISD::FMA);
811   setTargetDAGCombine(ISD::SMIN);
812   setTargetDAGCombine(ISD::SMAX);
813   setTargetDAGCombine(ISD::UMIN);
814   setTargetDAGCombine(ISD::UMAX);
815   setTargetDAGCombine(ISD::SETCC);
816   setTargetDAGCombine(ISD::AND);
817   setTargetDAGCombine(ISD::OR);
818   setTargetDAGCombine(ISD::XOR);
819   setTargetDAGCombine(ISD::SINT_TO_FP);
820   setTargetDAGCombine(ISD::UINT_TO_FP);
821   setTargetDAGCombine(ISD::FCANONICALIZE);
822   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
823   setTargetDAGCombine(ISD::ZERO_EXTEND);
824   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
825   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
826   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
827 
828   // All memory operations. Some folding on the pointer operand is done to help
829   // matching the constant offsets in the addressing modes.
830   setTargetDAGCombine(ISD::LOAD);
831   setTargetDAGCombine(ISD::STORE);
832   setTargetDAGCombine(ISD::ATOMIC_LOAD);
833   setTargetDAGCombine(ISD::ATOMIC_STORE);
834   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
835   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
836   setTargetDAGCombine(ISD::ATOMIC_SWAP);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
843   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
844   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
845   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
846   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
847   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
848 
849   // FIXME: In other contexts we pretend this is a per-function property.
850   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
851 
852   setSchedulingPreference(Sched::RegPressure);
853 }
854 
855 const GCNSubtarget *SITargetLowering::getSubtarget() const {
856   return Subtarget;
857 }
858 
859 //===----------------------------------------------------------------------===//
860 // TargetLowering queries
861 //===----------------------------------------------------------------------===//
862 
863 // v_mad_mix* support a conversion from f16 to f32.
864 //
865 // There is only one special case when denormals are enabled we don't currently,
866 // where this is OK to use.
867 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
868                                        EVT DestVT, EVT SrcVT) const {
869   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
870           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
871     DestVT.getScalarType() == MVT::f32 &&
872     SrcVT.getScalarType() == MVT::f16 &&
873     // TODO: This probably only requires no input flushing?
874     !hasFP32Denormals(DAG.getMachineFunction());
875 }
876 
877 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
878   // SI has some legal vector types, but no legal vector operations. Say no
879   // shuffles are legal in order to prefer scalarizing some vector operations.
880   return false;
881 }
882 
883 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
884                                                     CallingConv::ID CC,
885                                                     EVT VT) const {
886   if (CC == CallingConv::AMDGPU_KERNEL)
887     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
888 
889   if (VT.isVector()) {
890     EVT ScalarVT = VT.getScalarType();
891     unsigned Size = ScalarVT.getSizeInBits();
892     if (Size == 32)
893       return ScalarVT.getSimpleVT();
894 
895     if (Size > 32)
896       return MVT::i32;
897 
898     if (Size == 16 && Subtarget->has16BitInsts())
899       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
900   } else if (VT.getSizeInBits() > 32)
901     return MVT::i32;
902 
903   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
904 }
905 
906 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
907                                                          CallingConv::ID CC,
908                                                          EVT VT) const {
909   if (CC == CallingConv::AMDGPU_KERNEL)
910     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
911 
912   if (VT.isVector()) {
913     unsigned NumElts = VT.getVectorNumElements();
914     EVT ScalarVT = VT.getScalarType();
915     unsigned Size = ScalarVT.getSizeInBits();
916 
917     if (Size == 32)
918       return NumElts;
919 
920     if (Size > 32)
921       return NumElts * ((Size + 31) / 32);
922 
923     if (Size == 16 && Subtarget->has16BitInsts())
924       return (NumElts + 1) / 2;
925   } else if (VT.getSizeInBits() > 32)
926     return (VT.getSizeInBits() + 31) / 32;
927 
928   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
929 }
930 
931 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
932   LLVMContext &Context, CallingConv::ID CC,
933   EVT VT, EVT &IntermediateVT,
934   unsigned &NumIntermediates, MVT &RegisterVT) const {
935   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
936     unsigned NumElts = VT.getVectorNumElements();
937     EVT ScalarVT = VT.getScalarType();
938     unsigned Size = ScalarVT.getSizeInBits();
939     if (Size == 32) {
940       RegisterVT = ScalarVT.getSimpleVT();
941       IntermediateVT = RegisterVT;
942       NumIntermediates = NumElts;
943       return NumIntermediates;
944     }
945 
946     if (Size > 32) {
947       RegisterVT = MVT::i32;
948       IntermediateVT = RegisterVT;
949       NumIntermediates = NumElts * ((Size + 31) / 32);
950       return NumIntermediates;
951     }
952 
953     // FIXME: We should fix the ABI to be the same on targets without 16-bit
954     // support, but unless we can properly handle 3-vectors, it will be still be
955     // inconsistent.
956     if (Size == 16 && Subtarget->has16BitInsts()) {
957       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
958       IntermediateVT = RegisterVT;
959       NumIntermediates = (NumElts + 1) / 2;
960       return NumIntermediates;
961     }
962   }
963 
964   return TargetLowering::getVectorTypeBreakdownForCallingConv(
965     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
966 }
967 
968 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
969   assert(DMaskLanes != 0);
970 
971   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
972     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
973     return EVT::getVectorVT(Ty->getContext(),
974                             EVT::getEVT(VT->getElementType()),
975                             NumElts);
976   }
977 
978   return EVT::getEVT(Ty);
979 }
980 
981 // Peek through TFE struct returns to only use the data size.
982 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
983   auto *ST = dyn_cast<StructType>(Ty);
984   if (!ST)
985     return memVTFromImageData(Ty, DMaskLanes);
986 
987   // Some intrinsics return an aggregate type - special case to work out the
988   // correct memVT.
989   //
990   // Only limited forms of aggregate type currently expected.
991   if (ST->getNumContainedTypes() != 2 ||
992       !ST->getContainedType(1)->isIntegerTy(32))
993     return EVT();
994   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
995 }
996 
997 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
998                                           const CallInst &CI,
999                                           MachineFunction &MF,
1000                                           unsigned IntrID) const {
1001   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1002           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1003     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1004                                                   (Intrinsic::ID)IntrID);
1005     if (Attr.hasFnAttribute(Attribute::ReadNone))
1006       return false;
1007 
1008     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1009 
1010     if (RsrcIntr->IsImage) {
1011       Info.ptrVal = MFI->getImagePSV(
1012         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1013         CI.getArgOperand(RsrcIntr->RsrcArg));
1014       Info.align.reset();
1015     } else {
1016       Info.ptrVal = MFI->getBufferPSV(
1017         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1018         CI.getArgOperand(RsrcIntr->RsrcArg));
1019     }
1020 
1021     Info.flags = MachineMemOperand::MODereferenceable;
1022     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1023       unsigned DMaskLanes = 4;
1024 
1025       if (RsrcIntr->IsImage) {
1026         const AMDGPU::ImageDimIntrinsicInfo *Intr
1027           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1028         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1029           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1030 
1031         if (!BaseOpcode->Gather4) {
1032           // If this isn't a gather, we may have excess loaded elements in the
1033           // IR type. Check the dmask for the real number of elements loaded.
1034           unsigned DMask
1035             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1036           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1037         }
1038 
1039         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1040       } else
1041         Info.memVT = EVT::getEVT(CI.getType());
1042 
1043       // FIXME: What does alignment mean for an image?
1044       Info.opc = ISD::INTRINSIC_W_CHAIN;
1045       Info.flags |= MachineMemOperand::MOLoad;
1046     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1047       Info.opc = ISD::INTRINSIC_VOID;
1048 
1049       Type *DataTy = CI.getArgOperand(0)->getType();
1050       if (RsrcIntr->IsImage) {
1051         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1052         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1053         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1054       } else
1055         Info.memVT = EVT::getEVT(DataTy);
1056 
1057       Info.flags |= MachineMemOperand::MOStore;
1058     } else {
1059       // Atomic
1060       Info.opc = ISD::INTRINSIC_W_CHAIN;
1061       Info.memVT = MVT::getVT(CI.getType());
1062       Info.flags = MachineMemOperand::MOLoad |
1063                    MachineMemOperand::MOStore |
1064                    MachineMemOperand::MODereferenceable;
1065 
1066       // XXX - Should this be volatile without known ordering?
1067       Info.flags |= MachineMemOperand::MOVolatile;
1068     }
1069     return true;
1070   }
1071 
1072   switch (IntrID) {
1073   case Intrinsic::amdgcn_atomic_inc:
1074   case Intrinsic::amdgcn_atomic_dec:
1075   case Intrinsic::amdgcn_ds_ordered_add:
1076   case Intrinsic::amdgcn_ds_ordered_swap:
1077   case Intrinsic::amdgcn_ds_fadd:
1078   case Intrinsic::amdgcn_ds_fmin:
1079   case Intrinsic::amdgcn_ds_fmax: {
1080     Info.opc = ISD::INTRINSIC_W_CHAIN;
1081     Info.memVT = MVT::getVT(CI.getType());
1082     Info.ptrVal = CI.getOperand(0);
1083     Info.align.reset();
1084     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1085 
1086     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1087     if (!Vol->isZero())
1088       Info.flags |= MachineMemOperand::MOVolatile;
1089 
1090     return true;
1091   }
1092   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1093     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1094 
1095     Info.opc = ISD::INTRINSIC_VOID;
1096     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1097     Info.ptrVal = MFI->getBufferPSV(
1098       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1099       CI.getArgOperand(1));
1100     Info.align.reset();
1101     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1102 
1103     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1104     if (!Vol || !Vol->isZero())
1105       Info.flags |= MachineMemOperand::MOVolatile;
1106 
1107     return true;
1108   }
1109   case Intrinsic::amdgcn_global_atomic_fadd: {
1110     Info.opc = ISD::INTRINSIC_VOID;
1111     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1112                             ->getPointerElementType());
1113     Info.ptrVal = CI.getOperand(0);
1114     Info.align.reset();
1115     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1116 
1117     return true;
1118   }
1119   case Intrinsic::amdgcn_ds_append:
1120   case Intrinsic::amdgcn_ds_consume: {
1121     Info.opc = ISD::INTRINSIC_W_CHAIN;
1122     Info.memVT = MVT::getVT(CI.getType());
1123     Info.ptrVal = CI.getOperand(0);
1124     Info.align.reset();
1125     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1126 
1127     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1128     if (!Vol->isZero())
1129       Info.flags |= MachineMemOperand::MOVolatile;
1130 
1131     return true;
1132   }
1133   case Intrinsic::amdgcn_ds_gws_init:
1134   case Intrinsic::amdgcn_ds_gws_barrier:
1135   case Intrinsic::amdgcn_ds_gws_sema_v:
1136   case Intrinsic::amdgcn_ds_gws_sema_br:
1137   case Intrinsic::amdgcn_ds_gws_sema_p:
1138   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1139     Info.opc = ISD::INTRINSIC_VOID;
1140 
1141     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1142     Info.ptrVal =
1143         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1144 
1145     // This is an abstract access, but we need to specify a type and size.
1146     Info.memVT = MVT::i32;
1147     Info.size = 4;
1148     Info.align = Align(4);
1149 
1150     Info.flags = MachineMemOperand::MOStore;
1151     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1152       Info.flags = MachineMemOperand::MOLoad;
1153     return true;
1154   }
1155   default:
1156     return false;
1157   }
1158 }
1159 
1160 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1161                                             SmallVectorImpl<Value*> &Ops,
1162                                             Type *&AccessTy) const {
1163   switch (II->getIntrinsicID()) {
1164   case Intrinsic::amdgcn_atomic_inc:
1165   case Intrinsic::amdgcn_atomic_dec:
1166   case Intrinsic::amdgcn_ds_ordered_add:
1167   case Intrinsic::amdgcn_ds_ordered_swap:
1168   case Intrinsic::amdgcn_ds_fadd:
1169   case Intrinsic::amdgcn_ds_fmin:
1170   case Intrinsic::amdgcn_ds_fmax: {
1171     Value *Ptr = II->getArgOperand(0);
1172     AccessTy = II->getType();
1173     Ops.push_back(Ptr);
1174     return true;
1175   }
1176   default:
1177     return false;
1178   }
1179 }
1180 
1181 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1182   if (!Subtarget->hasFlatInstOffsets()) {
1183     // Flat instructions do not have offsets, and only have the register
1184     // address.
1185     return AM.BaseOffs == 0 && AM.Scale == 0;
1186   }
1187 
1188   return AM.Scale == 0 &&
1189          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1190                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1191                                   /*Signed=*/false));
1192 }
1193 
1194 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1195   if (Subtarget->hasFlatGlobalInsts())
1196     return AM.Scale == 0 &&
1197            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1198                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1199                                     /*Signed=*/true));
1200 
1201   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1202       // Assume the we will use FLAT for all global memory accesses
1203       // on VI.
1204       // FIXME: This assumption is currently wrong.  On VI we still use
1205       // MUBUF instructions for the r + i addressing mode.  As currently
1206       // implemented, the MUBUF instructions only work on buffer < 4GB.
1207       // It may be possible to support > 4GB buffers with MUBUF instructions,
1208       // by setting the stride value in the resource descriptor which would
1209       // increase the size limit to (stride * 4GB).  However, this is risky,
1210       // because it has never been validated.
1211     return isLegalFlatAddressingMode(AM);
1212   }
1213 
1214   return isLegalMUBUFAddressingMode(AM);
1215 }
1216 
1217 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1218   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1219   // additionally can do r + r + i with addr64. 32-bit has more addressing
1220   // mode options. Depending on the resource constant, it can also do
1221   // (i64 r0) + (i32 r1) * (i14 i).
1222   //
1223   // Private arrays end up using a scratch buffer most of the time, so also
1224   // assume those use MUBUF instructions. Scratch loads / stores are currently
1225   // implemented as mubuf instructions with offen bit set, so slightly
1226   // different than the normal addr64.
1227   if (!isUInt<12>(AM.BaseOffs))
1228     return false;
1229 
1230   // FIXME: Since we can split immediate into soffset and immediate offset,
1231   // would it make sense to allow any immediate?
1232 
1233   switch (AM.Scale) {
1234   case 0: // r + i or just i, depending on HasBaseReg.
1235     return true;
1236   case 1:
1237     return true; // We have r + r or r + i.
1238   case 2:
1239     if (AM.HasBaseReg) {
1240       // Reject 2 * r + r.
1241       return false;
1242     }
1243 
1244     // Allow 2 * r as r + r
1245     // Or  2 * r + i is allowed as r + r + i.
1246     return true;
1247   default: // Don't allow n * r
1248     return false;
1249   }
1250 }
1251 
1252 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1253                                              const AddrMode &AM, Type *Ty,
1254                                              unsigned AS, Instruction *I) const {
1255   // No global is ever allowed as a base.
1256   if (AM.BaseGV)
1257     return false;
1258 
1259   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1260     return isLegalGlobalAddressingMode(AM);
1261 
1262   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1263       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1264       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1265     // If the offset isn't a multiple of 4, it probably isn't going to be
1266     // correctly aligned.
1267     // FIXME: Can we get the real alignment here?
1268     if (AM.BaseOffs % 4 != 0)
1269       return isLegalMUBUFAddressingMode(AM);
1270 
1271     // There are no SMRD extloads, so if we have to do a small type access we
1272     // will use a MUBUF load.
1273     // FIXME?: We also need to do this if unaligned, but we don't know the
1274     // alignment here.
1275     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1276       return isLegalGlobalAddressingMode(AM);
1277 
1278     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1279       // SMRD instructions have an 8-bit, dword offset on SI.
1280       if (!isUInt<8>(AM.BaseOffs / 4))
1281         return false;
1282     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1283       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1284       // in 8-bits, it can use a smaller encoding.
1285       if (!isUInt<32>(AM.BaseOffs / 4))
1286         return false;
1287     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1288       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1289       if (!isUInt<20>(AM.BaseOffs))
1290         return false;
1291     } else
1292       llvm_unreachable("unhandled generation");
1293 
1294     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1295       return true;
1296 
1297     if (AM.Scale == 1 && AM.HasBaseReg)
1298       return true;
1299 
1300     return false;
1301 
1302   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1303     return isLegalMUBUFAddressingMode(AM);
1304   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1305              AS == AMDGPUAS::REGION_ADDRESS) {
1306     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1307     // field.
1308     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1309     // an 8-bit dword offset but we don't know the alignment here.
1310     if (!isUInt<16>(AM.BaseOffs))
1311       return false;
1312 
1313     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1314       return true;
1315 
1316     if (AM.Scale == 1 && AM.HasBaseReg)
1317       return true;
1318 
1319     return false;
1320   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1321              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1322     // For an unknown address space, this usually means that this is for some
1323     // reason being used for pure arithmetic, and not based on some addressing
1324     // computation. We don't have instructions that compute pointers with any
1325     // addressing modes, so treat them as having no offset like flat
1326     // instructions.
1327     return isLegalFlatAddressingMode(AM);
1328   }
1329 
1330   // Assume a user alias of global for unknown address spaces.
1331   return isLegalGlobalAddressingMode(AM);
1332 }
1333 
1334 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1335                                         const SelectionDAG &DAG) const {
1336   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1337     return (MemVT.getSizeInBits() <= 4 * 32);
1338   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1339     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1340     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1341   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1342     return (MemVT.getSizeInBits() <= 2 * 32);
1343   }
1344   return true;
1345 }
1346 
1347 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1348     unsigned Size, unsigned AddrSpace, unsigned Align,
1349     MachineMemOperand::Flags Flags, bool *IsFast) const {
1350   if (IsFast)
1351     *IsFast = false;
1352 
1353   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1354       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1355     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1356     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1357     // with adjacent offsets.
1358     bool AlignedBy4 = (Align % 4 == 0);
1359     if (IsFast)
1360       *IsFast = AlignedBy4;
1361 
1362     return AlignedBy4;
1363   }
1364 
1365   // FIXME: We have to be conservative here and assume that flat operations
1366   // will access scratch.  If we had access to the IR function, then we
1367   // could determine if any private memory was used in the function.
1368   if (!Subtarget->hasUnalignedScratchAccess() &&
1369       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1370        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1371     bool AlignedBy4 = Align >= 4;
1372     if (IsFast)
1373       *IsFast = AlignedBy4;
1374 
1375     return AlignedBy4;
1376   }
1377 
1378   if (Subtarget->hasUnalignedBufferAccess()) {
1379     // If we have an uniform constant load, it still requires using a slow
1380     // buffer instruction if unaligned.
1381     if (IsFast) {
1382       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1383       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1384       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1385                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1386         Align >= 4 : Align != 2;
1387     }
1388 
1389     return true;
1390   }
1391 
1392   // Smaller than dword value must be aligned.
1393   if (Size < 32)
1394     return false;
1395 
1396   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1397   // byte-address are ignored, thus forcing Dword alignment.
1398   // This applies to private, global, and constant memory.
1399   if (IsFast)
1400     *IsFast = true;
1401 
1402   return Size >= 32 && Align >= 4;
1403 }
1404 
1405 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1406     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1407     bool *IsFast) const {
1408   if (IsFast)
1409     *IsFast = false;
1410 
1411   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1412   // which isn't a simple VT.
1413   // Until MVT is extended to handle this, simply check for the size and
1414   // rely on the condition below: allow accesses if the size is a multiple of 4.
1415   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1416                            VT.getStoreSize() > 16)) {
1417     return false;
1418   }
1419 
1420   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1421                                             Align, Flags, IsFast);
1422 }
1423 
1424 EVT SITargetLowering::getOptimalMemOpType(
1425     const MemOp &Op, const AttributeList &FuncAttributes) const {
1426   // FIXME: Should account for address space here.
1427 
1428   // The default fallback uses the private pointer size as a guess for a type to
1429   // use. Make sure we switch these to 64-bit accesses.
1430 
1431   if (Op.size() >= 16 &&
1432       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1433     return MVT::v4i32;
1434 
1435   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1436     return MVT::v2i32;
1437 
1438   // Use the default.
1439   return MVT::Other;
1440 }
1441 
1442 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1443                                            unsigned DestAS) const {
1444   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1445 }
1446 
1447 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1448   const MemSDNode *MemNode = cast<MemSDNode>(N);
1449   const Value *Ptr = MemNode->getMemOperand()->getValue();
1450   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1451   return I && I->getMetadata("amdgpu.noclobber");
1452 }
1453 
1454 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1455                                            unsigned DestAS) const {
1456   // Flat -> private/local is a simple truncate.
1457   // Flat -> global is no-op
1458   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1459     return true;
1460 
1461   return isNoopAddrSpaceCast(SrcAS, DestAS);
1462 }
1463 
1464 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1465   const MemSDNode *MemNode = cast<MemSDNode>(N);
1466 
1467   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1468 }
1469 
1470 TargetLoweringBase::LegalizeTypeAction
1471 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1472   int NumElts = VT.getVectorNumElements();
1473   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1474     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1475   return TargetLoweringBase::getPreferredVectorAction(VT);
1476 }
1477 
1478 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1479                                                          Type *Ty) const {
1480   // FIXME: Could be smarter if called for vector constants.
1481   return true;
1482 }
1483 
1484 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1485   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1486     switch (Op) {
1487     case ISD::LOAD:
1488     case ISD::STORE:
1489 
1490     // These operations are done with 32-bit instructions anyway.
1491     case ISD::AND:
1492     case ISD::OR:
1493     case ISD::XOR:
1494     case ISD::SELECT:
1495       // TODO: Extensions?
1496       return true;
1497     default:
1498       return false;
1499     }
1500   }
1501 
1502   // SimplifySetCC uses this function to determine whether or not it should
1503   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1504   if (VT == MVT::i1 && Op == ISD::SETCC)
1505     return false;
1506 
1507   return TargetLowering::isTypeDesirableForOp(Op, VT);
1508 }
1509 
1510 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1511                                                    const SDLoc &SL,
1512                                                    SDValue Chain,
1513                                                    uint64_t Offset) const {
1514   const DataLayout &DL = DAG.getDataLayout();
1515   MachineFunction &MF = DAG.getMachineFunction();
1516   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1517 
1518   const ArgDescriptor *InputPtrReg;
1519   const TargetRegisterClass *RC;
1520 
1521   std::tie(InputPtrReg, RC)
1522     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1523 
1524   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1525   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1526   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1527     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1528 
1529   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1530 }
1531 
1532 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1533                                             const SDLoc &SL) const {
1534   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1535                                                FIRST_IMPLICIT);
1536   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1537 }
1538 
1539 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1540                                          const SDLoc &SL, SDValue Val,
1541                                          bool Signed,
1542                                          const ISD::InputArg *Arg) const {
1543   // First, if it is a widened vector, narrow it.
1544   if (VT.isVector() &&
1545       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1546     EVT NarrowedVT =
1547         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1548                          VT.getVectorNumElements());
1549     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1550                       DAG.getConstant(0, SL, MVT::i32));
1551   }
1552 
1553   // Then convert the vector elements or scalar value.
1554   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1555       VT.bitsLT(MemVT)) {
1556     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1557     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1558   }
1559 
1560   if (MemVT.isFloatingPoint())
1561     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1562   else if (Signed)
1563     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1564   else
1565     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1566 
1567   return Val;
1568 }
1569 
1570 SDValue SITargetLowering::lowerKernargMemParameter(
1571   SelectionDAG &DAG, EVT VT, EVT MemVT,
1572   const SDLoc &SL, SDValue Chain,
1573   uint64_t Offset, unsigned Align, bool Signed,
1574   const ISD::InputArg *Arg) const {
1575   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1576 
1577   // Try to avoid using an extload by loading earlier than the argument address,
1578   // and extracting the relevant bits. The load should hopefully be merged with
1579   // the previous argument.
1580   if (MemVT.getStoreSize() < 4 && Align < 4) {
1581     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1582     int64_t AlignDownOffset = alignDown(Offset, 4);
1583     int64_t OffsetDiff = Offset - AlignDownOffset;
1584 
1585     EVT IntVT = MemVT.changeTypeToInteger();
1586 
1587     // TODO: If we passed in the base kernel offset we could have a better
1588     // alignment than 4, but we don't really need it.
1589     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1590     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1591                                MachineMemOperand::MODereferenceable |
1592                                MachineMemOperand::MOInvariant);
1593 
1594     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1595     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1596 
1597     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1598     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1599     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1600 
1601 
1602     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1603   }
1604 
1605   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1606   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1607                              MachineMemOperand::MODereferenceable |
1608                              MachineMemOperand::MOInvariant);
1609 
1610   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1611   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1612 }
1613 
1614 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1615                                               const SDLoc &SL, SDValue Chain,
1616                                               const ISD::InputArg &Arg) const {
1617   MachineFunction &MF = DAG.getMachineFunction();
1618   MachineFrameInfo &MFI = MF.getFrameInfo();
1619 
1620   if (Arg.Flags.isByVal()) {
1621     unsigned Size = Arg.Flags.getByValSize();
1622     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1623     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1624   }
1625 
1626   unsigned ArgOffset = VA.getLocMemOffset();
1627   unsigned ArgSize = VA.getValVT().getStoreSize();
1628 
1629   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1630 
1631   // Create load nodes to retrieve arguments from the stack.
1632   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1633   SDValue ArgValue;
1634 
1635   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1636   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1637   MVT MemVT = VA.getValVT();
1638 
1639   switch (VA.getLocInfo()) {
1640   default:
1641     break;
1642   case CCValAssign::BCvt:
1643     MemVT = VA.getLocVT();
1644     break;
1645   case CCValAssign::SExt:
1646     ExtType = ISD::SEXTLOAD;
1647     break;
1648   case CCValAssign::ZExt:
1649     ExtType = ISD::ZEXTLOAD;
1650     break;
1651   case CCValAssign::AExt:
1652     ExtType = ISD::EXTLOAD;
1653     break;
1654   }
1655 
1656   ArgValue = DAG.getExtLoad(
1657     ExtType, SL, VA.getLocVT(), Chain, FIN,
1658     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1659     MemVT);
1660   return ArgValue;
1661 }
1662 
1663 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1664   const SIMachineFunctionInfo &MFI,
1665   EVT VT,
1666   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1667   const ArgDescriptor *Reg;
1668   const TargetRegisterClass *RC;
1669 
1670   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1671   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1672 }
1673 
1674 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1675                                    CallingConv::ID CallConv,
1676                                    ArrayRef<ISD::InputArg> Ins,
1677                                    BitVector &Skipped,
1678                                    FunctionType *FType,
1679                                    SIMachineFunctionInfo *Info) {
1680   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1681     const ISD::InputArg *Arg = &Ins[I];
1682 
1683     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1684            "vector type argument should have been split");
1685 
1686     // First check if it's a PS input addr.
1687     if (CallConv == CallingConv::AMDGPU_PS &&
1688         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1689       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1690 
1691       // Inconveniently only the first part of the split is marked as isSplit,
1692       // so skip to the end. We only want to increment PSInputNum once for the
1693       // entire split argument.
1694       if (Arg->Flags.isSplit()) {
1695         while (!Arg->Flags.isSplitEnd()) {
1696           assert((!Arg->VT.isVector() ||
1697                   Arg->VT.getScalarSizeInBits() == 16) &&
1698                  "unexpected vector split in ps argument type");
1699           if (!SkipArg)
1700             Splits.push_back(*Arg);
1701           Arg = &Ins[++I];
1702         }
1703       }
1704 
1705       if (SkipArg) {
1706         // We can safely skip PS inputs.
1707         Skipped.set(Arg->getOrigArgIndex());
1708         ++PSInputNum;
1709         continue;
1710       }
1711 
1712       Info->markPSInputAllocated(PSInputNum);
1713       if (Arg->Used)
1714         Info->markPSInputEnabled(PSInputNum);
1715 
1716       ++PSInputNum;
1717     }
1718 
1719     Splits.push_back(*Arg);
1720   }
1721 }
1722 
1723 // Allocate special inputs passed in VGPRs.
1724 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1725                                                       MachineFunction &MF,
1726                                                       const SIRegisterInfo &TRI,
1727                                                       SIMachineFunctionInfo &Info) const {
1728   const LLT S32 = LLT::scalar(32);
1729   MachineRegisterInfo &MRI = MF.getRegInfo();
1730 
1731   if (Info.hasWorkItemIDX()) {
1732     Register Reg = AMDGPU::VGPR0;
1733     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1734 
1735     CCInfo.AllocateReg(Reg);
1736     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1737   }
1738 
1739   if (Info.hasWorkItemIDY()) {
1740     Register Reg = AMDGPU::VGPR1;
1741     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1742 
1743     CCInfo.AllocateReg(Reg);
1744     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1745   }
1746 
1747   if (Info.hasWorkItemIDZ()) {
1748     Register Reg = AMDGPU::VGPR2;
1749     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1750 
1751     CCInfo.AllocateReg(Reg);
1752     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1753   }
1754 }
1755 
1756 // Try to allocate a VGPR at the end of the argument list, or if no argument
1757 // VGPRs are left allocating a stack slot.
1758 // If \p Mask is is given it indicates bitfield position in the register.
1759 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1760 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1761                                          ArgDescriptor Arg = ArgDescriptor()) {
1762   if (Arg.isSet())
1763     return ArgDescriptor::createArg(Arg, Mask);
1764 
1765   ArrayRef<MCPhysReg> ArgVGPRs
1766     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1767   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1768   if (RegIdx == ArgVGPRs.size()) {
1769     // Spill to stack required.
1770     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1771 
1772     return ArgDescriptor::createStack(Offset, Mask);
1773   }
1774 
1775   unsigned Reg = ArgVGPRs[RegIdx];
1776   Reg = CCInfo.AllocateReg(Reg);
1777   assert(Reg != AMDGPU::NoRegister);
1778 
1779   MachineFunction &MF = CCInfo.getMachineFunction();
1780   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1781   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1782   return ArgDescriptor::createRegister(Reg, Mask);
1783 }
1784 
1785 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1786                                              const TargetRegisterClass *RC,
1787                                              unsigned NumArgRegs) {
1788   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1789   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1790   if (RegIdx == ArgSGPRs.size())
1791     report_fatal_error("ran out of SGPRs for arguments");
1792 
1793   unsigned Reg = ArgSGPRs[RegIdx];
1794   Reg = CCInfo.AllocateReg(Reg);
1795   assert(Reg != AMDGPU::NoRegister);
1796 
1797   MachineFunction &MF = CCInfo.getMachineFunction();
1798   MF.addLiveIn(Reg, RC);
1799   return ArgDescriptor::createRegister(Reg);
1800 }
1801 
1802 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1803   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1804 }
1805 
1806 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1807   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1808 }
1809 
1810 /// Allocate implicit function VGPR arguments at the end of allocated user
1811 /// arguments.
1812 void SITargetLowering::allocateSpecialInputVGPRs(
1813   CCState &CCInfo, MachineFunction &MF,
1814   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1815   const unsigned Mask = 0x3ff;
1816   ArgDescriptor Arg;
1817 
1818   if (Info.hasWorkItemIDX()) {
1819     Arg = allocateVGPR32Input(CCInfo, Mask);
1820     Info.setWorkItemIDX(Arg);
1821   }
1822 
1823   if (Info.hasWorkItemIDY()) {
1824     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1825     Info.setWorkItemIDY(Arg);
1826   }
1827 
1828   if (Info.hasWorkItemIDZ())
1829     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1830 }
1831 
1832 /// Allocate implicit function VGPR arguments in fixed registers.
1833 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1834   CCState &CCInfo, MachineFunction &MF,
1835   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1836   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1837   if (!Reg)
1838     report_fatal_error("failed to allocated VGPR for implicit arguments");
1839 
1840   const unsigned Mask = 0x3ff;
1841   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1842   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1843   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1844 }
1845 
1846 void SITargetLowering::allocateSpecialInputSGPRs(
1847   CCState &CCInfo,
1848   MachineFunction &MF,
1849   const SIRegisterInfo &TRI,
1850   SIMachineFunctionInfo &Info) const {
1851   auto &ArgInfo = Info.getArgInfo();
1852 
1853   // TODO: Unify handling with private memory pointers.
1854 
1855   if (Info.hasDispatchPtr())
1856     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1857 
1858   if (Info.hasQueuePtr())
1859     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1860 
1861   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1862   // constant offset from the kernarg segment.
1863   if (Info.hasImplicitArgPtr())
1864     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1865 
1866   if (Info.hasDispatchID())
1867     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1868 
1869   // flat_scratch_init is not applicable for non-kernel functions.
1870 
1871   if (Info.hasWorkGroupIDX())
1872     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1873 
1874   if (Info.hasWorkGroupIDY())
1875     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1876 
1877   if (Info.hasWorkGroupIDZ())
1878     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1879 }
1880 
1881 // Allocate special inputs passed in user SGPRs.
1882 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1883                                             MachineFunction &MF,
1884                                             const SIRegisterInfo &TRI,
1885                                             SIMachineFunctionInfo &Info) const {
1886   if (Info.hasImplicitBufferPtr()) {
1887     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1888     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1889     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1890   }
1891 
1892   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1893   if (Info.hasPrivateSegmentBuffer()) {
1894     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1895     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1896     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1897   }
1898 
1899   if (Info.hasDispatchPtr()) {
1900     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1901     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1902     CCInfo.AllocateReg(DispatchPtrReg);
1903   }
1904 
1905   if (Info.hasQueuePtr()) {
1906     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1907     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1908     CCInfo.AllocateReg(QueuePtrReg);
1909   }
1910 
1911   if (Info.hasKernargSegmentPtr()) {
1912     MachineRegisterInfo &MRI = MF.getRegInfo();
1913     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1914     CCInfo.AllocateReg(InputPtrReg);
1915 
1916     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1917     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1918   }
1919 
1920   if (Info.hasDispatchID()) {
1921     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1922     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1923     CCInfo.AllocateReg(DispatchIDReg);
1924   }
1925 
1926   if (Info.hasFlatScratchInit()) {
1927     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1928     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1929     CCInfo.AllocateReg(FlatScratchInitReg);
1930   }
1931 
1932   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1933   // these from the dispatch pointer.
1934 }
1935 
1936 // Allocate special input registers that are initialized per-wave.
1937 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1938                                            MachineFunction &MF,
1939                                            SIMachineFunctionInfo &Info,
1940                                            CallingConv::ID CallConv,
1941                                            bool IsShader) const {
1942   if (Info.hasWorkGroupIDX()) {
1943     unsigned Reg = Info.addWorkGroupIDX();
1944     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1945     CCInfo.AllocateReg(Reg);
1946   }
1947 
1948   if (Info.hasWorkGroupIDY()) {
1949     unsigned Reg = Info.addWorkGroupIDY();
1950     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1951     CCInfo.AllocateReg(Reg);
1952   }
1953 
1954   if (Info.hasWorkGroupIDZ()) {
1955     unsigned Reg = Info.addWorkGroupIDZ();
1956     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1957     CCInfo.AllocateReg(Reg);
1958   }
1959 
1960   if (Info.hasWorkGroupInfo()) {
1961     unsigned Reg = Info.addWorkGroupInfo();
1962     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1963     CCInfo.AllocateReg(Reg);
1964   }
1965 
1966   if (Info.hasPrivateSegmentWaveByteOffset()) {
1967     // Scratch wave offset passed in system SGPR.
1968     unsigned PrivateSegmentWaveByteOffsetReg;
1969 
1970     if (IsShader) {
1971       PrivateSegmentWaveByteOffsetReg =
1972         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1973 
1974       // This is true if the scratch wave byte offset doesn't have a fixed
1975       // location.
1976       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1977         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1978         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1979       }
1980     } else
1981       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1982 
1983     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1984     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1985   }
1986 }
1987 
1988 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1989                                      MachineFunction &MF,
1990                                      const SIRegisterInfo &TRI,
1991                                      SIMachineFunctionInfo &Info) {
1992   // Now that we've figured out where the scratch register inputs are, see if
1993   // should reserve the arguments and use them directly.
1994   MachineFrameInfo &MFI = MF.getFrameInfo();
1995   bool HasStackObjects = MFI.hasStackObjects();
1996   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1997 
1998   // Record that we know we have non-spill stack objects so we don't need to
1999   // check all stack objects later.
2000   if (HasStackObjects)
2001     Info.setHasNonSpillStackObjects(true);
2002 
2003   // Everything live out of a block is spilled with fast regalloc, so it's
2004   // almost certain that spilling will be required.
2005   if (TM.getOptLevel() == CodeGenOpt::None)
2006     HasStackObjects = true;
2007 
2008   // For now assume stack access is needed in any callee functions, so we need
2009   // the scratch registers to pass in.
2010   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2011 
2012   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2013     // If we have stack objects, we unquestionably need the private buffer
2014     // resource. For the Code Object V2 ABI, this will be the first 4 user
2015     // SGPR inputs. We can reserve those and use them directly.
2016 
2017     Register PrivateSegmentBufferReg =
2018         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2019     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2020   } else {
2021     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2022     // We tentatively reserve the last registers (skipping the last registers
2023     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2024     // we'll replace these with the ones immediately after those which were
2025     // really allocated. In the prologue copies will be inserted from the
2026     // argument to these reserved registers.
2027 
2028     // Without HSA, relocations are used for the scratch pointer and the
2029     // buffer resource setup is always inserted in the prologue. Scratch wave
2030     // offset is still in an input SGPR.
2031     Info.setScratchRSrcReg(ReservedBufferReg);
2032   }
2033 
2034   MachineRegisterInfo &MRI = MF.getRegInfo();
2035 
2036   // For entry functions we have to set up the stack pointer if we use it,
2037   // whereas non-entry functions get this "for free". This means there is no
2038   // intrinsic advantage to using S32 over S34 in cases where we do not have
2039   // calls but do need a frame pointer (i.e. if we are requested to have one
2040   // because frame pointer elimination is disabled). To keep things simple we
2041   // only ever use S32 as the call ABI stack pointer, and so using it does not
2042   // imply we need a separate frame pointer.
2043   //
2044   // Try to use s32 as the SP, but move it if it would interfere with input
2045   // arguments. This won't work with calls though.
2046   //
2047   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2048   // registers.
2049   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2050     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2051   } else {
2052     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2053 
2054     if (MFI.hasCalls())
2055       report_fatal_error("call in graphics shader with too many input SGPRs");
2056 
2057     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2058       if (!MRI.isLiveIn(Reg)) {
2059         Info.setStackPtrOffsetReg(Reg);
2060         break;
2061       }
2062     }
2063 
2064     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2065       report_fatal_error("failed to find register for SP");
2066   }
2067 
2068   // hasFP should be accurate for entry functions even before the frame is
2069   // finalized, because it does not rely on the known stack size, only
2070   // properties like whether variable sized objects are present.
2071   if (ST.getFrameLowering()->hasFP(MF)) {
2072     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2073   }
2074 }
2075 
2076 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2077   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2078   return !Info->isEntryFunction();
2079 }
2080 
2081 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2082 
2083 }
2084 
2085 void SITargetLowering::insertCopiesSplitCSR(
2086   MachineBasicBlock *Entry,
2087   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2088   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2089 
2090   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2091   if (!IStart)
2092     return;
2093 
2094   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2095   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2096   MachineBasicBlock::iterator MBBI = Entry->begin();
2097   for (const MCPhysReg *I = IStart; *I; ++I) {
2098     const TargetRegisterClass *RC = nullptr;
2099     if (AMDGPU::SReg_64RegClass.contains(*I))
2100       RC = &AMDGPU::SGPR_64RegClass;
2101     else if (AMDGPU::SReg_32RegClass.contains(*I))
2102       RC = &AMDGPU::SGPR_32RegClass;
2103     else
2104       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2105 
2106     Register NewVR = MRI->createVirtualRegister(RC);
2107     // Create copy from CSR to a virtual register.
2108     Entry->addLiveIn(*I);
2109     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2110       .addReg(*I);
2111 
2112     // Insert the copy-back instructions right before the terminator.
2113     for (auto *Exit : Exits)
2114       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2115               TII->get(TargetOpcode::COPY), *I)
2116         .addReg(NewVR);
2117   }
2118 }
2119 
2120 SDValue SITargetLowering::LowerFormalArguments(
2121     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2122     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2123     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2124   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2125 
2126   MachineFunction &MF = DAG.getMachineFunction();
2127   const Function &Fn = MF.getFunction();
2128   FunctionType *FType = MF.getFunction().getFunctionType();
2129   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2130 
2131   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2132     DiagnosticInfoUnsupported NoGraphicsHSA(
2133         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2134     DAG.getContext()->diagnose(NoGraphicsHSA);
2135     return DAG.getEntryNode();
2136   }
2137 
2138   SmallVector<ISD::InputArg, 16> Splits;
2139   SmallVector<CCValAssign, 16> ArgLocs;
2140   BitVector Skipped(Ins.size());
2141   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2142                  *DAG.getContext());
2143 
2144   bool IsShader = AMDGPU::isShader(CallConv);
2145   bool IsKernel = AMDGPU::isKernel(CallConv);
2146   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2147 
2148   if (IsShader) {
2149     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2150 
2151     // At least one interpolation mode must be enabled or else the GPU will
2152     // hang.
2153     //
2154     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2155     // set PSInputAddr, the user wants to enable some bits after the compilation
2156     // based on run-time states. Since we can't know what the final PSInputEna
2157     // will look like, so we shouldn't do anything here and the user should take
2158     // responsibility for the correct programming.
2159     //
2160     // Otherwise, the following restrictions apply:
2161     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2162     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2163     //   enabled too.
2164     if (CallConv == CallingConv::AMDGPU_PS) {
2165       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2166            ((Info->getPSInputAddr() & 0xF) == 0 &&
2167             Info->isPSInputAllocated(11))) {
2168         CCInfo.AllocateReg(AMDGPU::VGPR0);
2169         CCInfo.AllocateReg(AMDGPU::VGPR1);
2170         Info->markPSInputAllocated(0);
2171         Info->markPSInputEnabled(0);
2172       }
2173       if (Subtarget->isAmdPalOS()) {
2174         // For isAmdPalOS, the user does not enable some bits after compilation
2175         // based on run-time states; the register values being generated here are
2176         // the final ones set in hardware. Therefore we need to apply the
2177         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2178         // a bit is set in PSInputAddr but not PSInputEnable is where the
2179         // frontend set up an input arg for a particular interpolation mode, but
2180         // nothing uses that input arg. Really we should have an earlier pass
2181         // that removes such an arg.)
2182         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2183         if ((PsInputBits & 0x7F) == 0 ||
2184             ((PsInputBits & 0xF) == 0 &&
2185              (PsInputBits >> 11 & 1)))
2186           Info->markPSInputEnabled(
2187               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2188       }
2189     }
2190 
2191     assert(!Info->hasDispatchPtr() &&
2192            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2193            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2194            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2195            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2196            !Info->hasWorkItemIDZ());
2197   } else if (IsKernel) {
2198     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2199   } else {
2200     Splits.append(Ins.begin(), Ins.end());
2201   }
2202 
2203   if (IsEntryFunc) {
2204     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2205     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2206   } else {
2207     // For the fixed ABI, pass workitem IDs in the last argument register.
2208     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2209       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2210   }
2211 
2212   if (IsKernel) {
2213     analyzeFormalArgumentsCompute(CCInfo, Ins);
2214   } else {
2215     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2216     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2217   }
2218 
2219   SmallVector<SDValue, 16> Chains;
2220 
2221   // FIXME: This is the minimum kernel argument alignment. We should improve
2222   // this to the maximum alignment of the arguments.
2223   //
2224   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2225   // kern arg offset.
2226   const unsigned KernelArgBaseAlign = 16;
2227 
2228    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2229     const ISD::InputArg &Arg = Ins[i];
2230     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2231       InVals.push_back(DAG.getUNDEF(Arg.VT));
2232       continue;
2233     }
2234 
2235     CCValAssign &VA = ArgLocs[ArgIdx++];
2236     MVT VT = VA.getLocVT();
2237 
2238     if (IsEntryFunc && VA.isMemLoc()) {
2239       VT = Ins[i].VT;
2240       EVT MemVT = VA.getLocVT();
2241 
2242       const uint64_t Offset = VA.getLocMemOffset();
2243       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2244 
2245       SDValue Arg = lowerKernargMemParameter(
2246         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2247       Chains.push_back(Arg.getValue(1));
2248 
2249       auto *ParamTy =
2250         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2251       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2252           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2253                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2254         // On SI local pointers are just offsets into LDS, so they are always
2255         // less than 16-bits.  On CI and newer they could potentially be
2256         // real pointers, so we can't guarantee their size.
2257         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2258                           DAG.getValueType(MVT::i16));
2259       }
2260 
2261       InVals.push_back(Arg);
2262       continue;
2263     } else if (!IsEntryFunc && VA.isMemLoc()) {
2264       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2265       InVals.push_back(Val);
2266       if (!Arg.Flags.isByVal())
2267         Chains.push_back(Val.getValue(1));
2268       continue;
2269     }
2270 
2271     assert(VA.isRegLoc() && "Parameter must be in a register!");
2272 
2273     Register Reg = VA.getLocReg();
2274     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2275     EVT ValVT = VA.getValVT();
2276 
2277     Reg = MF.addLiveIn(Reg, RC);
2278     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2279 
2280     if (Arg.Flags.isSRet()) {
2281       // The return object should be reasonably addressable.
2282 
2283       // FIXME: This helps when the return is a real sret. If it is a
2284       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2285       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2286       unsigned NumBits
2287         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2288       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2289         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2290     }
2291 
2292     // If this is an 8 or 16-bit value, it is really passed promoted
2293     // to 32 bits. Insert an assert[sz]ext to capture this, then
2294     // truncate to the right size.
2295     switch (VA.getLocInfo()) {
2296     case CCValAssign::Full:
2297       break;
2298     case CCValAssign::BCvt:
2299       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2300       break;
2301     case CCValAssign::SExt:
2302       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2303                         DAG.getValueType(ValVT));
2304       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2305       break;
2306     case CCValAssign::ZExt:
2307       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2308                         DAG.getValueType(ValVT));
2309       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2310       break;
2311     case CCValAssign::AExt:
2312       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2313       break;
2314     default:
2315       llvm_unreachable("Unknown loc info!");
2316     }
2317 
2318     InVals.push_back(Val);
2319   }
2320 
2321   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2322     // Special inputs come after user arguments.
2323     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2324   }
2325 
2326   // Start adding system SGPRs.
2327   if (IsEntryFunc) {
2328     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2329   } else {
2330     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2331     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2332   }
2333 
2334   auto &ArgUsageInfo =
2335     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2336   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2337 
2338   unsigned StackArgSize = CCInfo.getNextStackOffset();
2339   Info->setBytesInStackArgArea(StackArgSize);
2340 
2341   return Chains.empty() ? Chain :
2342     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2343 }
2344 
2345 // TODO: If return values can't fit in registers, we should return as many as
2346 // possible in registers before passing on stack.
2347 bool SITargetLowering::CanLowerReturn(
2348   CallingConv::ID CallConv,
2349   MachineFunction &MF, bool IsVarArg,
2350   const SmallVectorImpl<ISD::OutputArg> &Outs,
2351   LLVMContext &Context) const {
2352   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2353   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2354   // for shaders. Vector types should be explicitly handled by CC.
2355   if (AMDGPU::isEntryFunctionCC(CallConv))
2356     return true;
2357 
2358   SmallVector<CCValAssign, 16> RVLocs;
2359   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2360   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2361 }
2362 
2363 SDValue
2364 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2365                               bool isVarArg,
2366                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2367                               const SmallVectorImpl<SDValue> &OutVals,
2368                               const SDLoc &DL, SelectionDAG &DAG) const {
2369   MachineFunction &MF = DAG.getMachineFunction();
2370   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2371 
2372   if (AMDGPU::isKernel(CallConv)) {
2373     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2374                                              OutVals, DL, DAG);
2375   }
2376 
2377   bool IsShader = AMDGPU::isShader(CallConv);
2378 
2379   Info->setIfReturnsVoid(Outs.empty());
2380   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2381 
2382   // CCValAssign - represent the assignment of the return value to a location.
2383   SmallVector<CCValAssign, 48> RVLocs;
2384   SmallVector<ISD::OutputArg, 48> Splits;
2385 
2386   // CCState - Info about the registers and stack slots.
2387   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2388                  *DAG.getContext());
2389 
2390   // Analyze outgoing return values.
2391   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2392 
2393   SDValue Flag;
2394   SmallVector<SDValue, 48> RetOps;
2395   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2396 
2397   // Add return address for callable functions.
2398   if (!Info->isEntryFunction()) {
2399     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2400     SDValue ReturnAddrReg = CreateLiveInRegister(
2401       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2402 
2403     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2404         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2405         MVT::i64);
2406     Chain =
2407         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2408     Flag = Chain.getValue(1);
2409     RetOps.push_back(ReturnAddrVirtualReg);
2410   }
2411 
2412   // Copy the result values into the output registers.
2413   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2414        ++I, ++RealRVLocIdx) {
2415     CCValAssign &VA = RVLocs[I];
2416     assert(VA.isRegLoc() && "Can only return in registers!");
2417     // TODO: Partially return in registers if return values don't fit.
2418     SDValue Arg = OutVals[RealRVLocIdx];
2419 
2420     // Copied from other backends.
2421     switch (VA.getLocInfo()) {
2422     case CCValAssign::Full:
2423       break;
2424     case CCValAssign::BCvt:
2425       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2426       break;
2427     case CCValAssign::SExt:
2428       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2429       break;
2430     case CCValAssign::ZExt:
2431       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2432       break;
2433     case CCValAssign::AExt:
2434       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2435       break;
2436     default:
2437       llvm_unreachable("Unknown loc info!");
2438     }
2439 
2440     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2441     Flag = Chain.getValue(1);
2442     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2443   }
2444 
2445   // FIXME: Does sret work properly?
2446   if (!Info->isEntryFunction()) {
2447     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2448     const MCPhysReg *I =
2449       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2450     if (I) {
2451       for (; *I; ++I) {
2452         if (AMDGPU::SReg_64RegClass.contains(*I))
2453           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2454         else if (AMDGPU::SReg_32RegClass.contains(*I))
2455           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2456         else
2457           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2458       }
2459     }
2460   }
2461 
2462   // Update chain and glue.
2463   RetOps[0] = Chain;
2464   if (Flag.getNode())
2465     RetOps.push_back(Flag);
2466 
2467   unsigned Opc = AMDGPUISD::ENDPGM;
2468   if (!IsWaveEnd)
2469     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2470   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2471 }
2472 
2473 SDValue SITargetLowering::LowerCallResult(
2474     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2475     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2476     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2477     SDValue ThisVal) const {
2478   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2479 
2480   // Assign locations to each value returned by this call.
2481   SmallVector<CCValAssign, 16> RVLocs;
2482   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2483                  *DAG.getContext());
2484   CCInfo.AnalyzeCallResult(Ins, RetCC);
2485 
2486   // Copy all of the result registers out of their specified physreg.
2487   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2488     CCValAssign VA = RVLocs[i];
2489     SDValue Val;
2490 
2491     if (VA.isRegLoc()) {
2492       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2493       Chain = Val.getValue(1);
2494       InFlag = Val.getValue(2);
2495     } else if (VA.isMemLoc()) {
2496       report_fatal_error("TODO: return values in memory");
2497     } else
2498       llvm_unreachable("unknown argument location type");
2499 
2500     switch (VA.getLocInfo()) {
2501     case CCValAssign::Full:
2502       break;
2503     case CCValAssign::BCvt:
2504       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2505       break;
2506     case CCValAssign::ZExt:
2507       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2508                         DAG.getValueType(VA.getValVT()));
2509       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2510       break;
2511     case CCValAssign::SExt:
2512       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2513                         DAG.getValueType(VA.getValVT()));
2514       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2515       break;
2516     case CCValAssign::AExt:
2517       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2518       break;
2519     default:
2520       llvm_unreachable("Unknown loc info!");
2521     }
2522 
2523     InVals.push_back(Val);
2524   }
2525 
2526   return Chain;
2527 }
2528 
2529 // Add code to pass special inputs required depending on used features separate
2530 // from the explicit user arguments present in the IR.
2531 void SITargetLowering::passSpecialInputs(
2532     CallLoweringInfo &CLI,
2533     CCState &CCInfo,
2534     const SIMachineFunctionInfo &Info,
2535     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2536     SmallVectorImpl<SDValue> &MemOpChains,
2537     SDValue Chain) const {
2538   // If we don't have a call site, this was a call inserted by
2539   // legalization. These can never use special inputs.
2540   if (!CLI.CB)
2541     return;
2542 
2543   SelectionDAG &DAG = CLI.DAG;
2544   const SDLoc &DL = CLI.DL;
2545 
2546   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2547   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2548 
2549   const AMDGPUFunctionArgInfo *CalleeArgInfo
2550     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2551   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2552     auto &ArgUsageInfo =
2553       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2554     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2555   }
2556 
2557   // TODO: Unify with private memory register handling. This is complicated by
2558   // the fact that at least in kernels, the input argument is not necessarily
2559   // in the same location as the input.
2560   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2561     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2562     AMDGPUFunctionArgInfo::QUEUE_PTR,
2563     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2564     AMDGPUFunctionArgInfo::DISPATCH_ID,
2565     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2566     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2567     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2568   };
2569 
2570   for (auto InputID : InputRegs) {
2571     const ArgDescriptor *OutgoingArg;
2572     const TargetRegisterClass *ArgRC;
2573 
2574     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2575     if (!OutgoingArg)
2576       continue;
2577 
2578     const ArgDescriptor *IncomingArg;
2579     const TargetRegisterClass *IncomingArgRC;
2580     std::tie(IncomingArg, IncomingArgRC)
2581       = CallerArgInfo.getPreloadedValue(InputID);
2582     assert(IncomingArgRC == ArgRC);
2583 
2584     // All special arguments are ints for now.
2585     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2586     SDValue InputReg;
2587 
2588     if (IncomingArg) {
2589       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2590     } else {
2591       // The implicit arg ptr is special because it doesn't have a corresponding
2592       // input for kernels, and is computed from the kernarg segment pointer.
2593       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2594       InputReg = getImplicitArgPtr(DAG, DL);
2595     }
2596 
2597     if (OutgoingArg->isRegister()) {
2598       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2599       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2600         report_fatal_error("failed to allocate implicit input argument");
2601     } else {
2602       unsigned SpecialArgOffset =
2603           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2604       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2605                                               SpecialArgOffset);
2606       MemOpChains.push_back(ArgStore);
2607     }
2608   }
2609 
2610   // Pack workitem IDs into a single register or pass it as is if already
2611   // packed.
2612   const ArgDescriptor *OutgoingArg;
2613   const TargetRegisterClass *ArgRC;
2614 
2615   std::tie(OutgoingArg, ArgRC) =
2616     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2617   if (!OutgoingArg)
2618     std::tie(OutgoingArg, ArgRC) =
2619       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2620   if (!OutgoingArg)
2621     std::tie(OutgoingArg, ArgRC) =
2622       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2623   if (!OutgoingArg)
2624     return;
2625 
2626   const ArgDescriptor *IncomingArgX
2627     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2628   const ArgDescriptor *IncomingArgY
2629     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2630   const ArgDescriptor *IncomingArgZ
2631     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2632 
2633   SDValue InputReg;
2634   SDLoc SL;
2635 
2636   // If incoming ids are not packed we need to pack them.
2637   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2638     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2639 
2640   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2641     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2642     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2643                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2644     InputReg = InputReg.getNode() ?
2645                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2646   }
2647 
2648   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2649     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2650     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2651                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2652     InputReg = InputReg.getNode() ?
2653                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2654   }
2655 
2656   if (!InputReg.getNode()) {
2657     // Workitem ids are already packed, any of present incoming arguments
2658     // will carry all required fields.
2659     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2660       IncomingArgX ? *IncomingArgX :
2661       IncomingArgY ? *IncomingArgY :
2662                      *IncomingArgZ, ~0u);
2663     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2664   }
2665 
2666   if (OutgoingArg->isRegister()) {
2667     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2668     CCInfo.AllocateReg(OutgoingArg->getRegister());
2669   } else {
2670     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2671     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2672                                             SpecialArgOffset);
2673     MemOpChains.push_back(ArgStore);
2674   }
2675 }
2676 
2677 static bool canGuaranteeTCO(CallingConv::ID CC) {
2678   return CC == CallingConv::Fast;
2679 }
2680 
2681 /// Return true if we might ever do TCO for calls with this calling convention.
2682 static bool mayTailCallThisCC(CallingConv::ID CC) {
2683   switch (CC) {
2684   case CallingConv::C:
2685     return true;
2686   default:
2687     return canGuaranteeTCO(CC);
2688   }
2689 }
2690 
2691 bool SITargetLowering::isEligibleForTailCallOptimization(
2692     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2693     const SmallVectorImpl<ISD::OutputArg> &Outs,
2694     const SmallVectorImpl<SDValue> &OutVals,
2695     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2696   if (!mayTailCallThisCC(CalleeCC))
2697     return false;
2698 
2699   MachineFunction &MF = DAG.getMachineFunction();
2700   const Function &CallerF = MF.getFunction();
2701   CallingConv::ID CallerCC = CallerF.getCallingConv();
2702   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2703   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2704 
2705   // Kernels aren't callable, and don't have a live in return address so it
2706   // doesn't make sense to do a tail call with entry functions.
2707   if (!CallerPreserved)
2708     return false;
2709 
2710   bool CCMatch = CallerCC == CalleeCC;
2711 
2712   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2713     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2714       return true;
2715     return false;
2716   }
2717 
2718   // TODO: Can we handle var args?
2719   if (IsVarArg)
2720     return false;
2721 
2722   for (const Argument &Arg : CallerF.args()) {
2723     if (Arg.hasByValAttr())
2724       return false;
2725   }
2726 
2727   LLVMContext &Ctx = *DAG.getContext();
2728 
2729   // Check that the call results are passed in the same way.
2730   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2731                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2732                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2733     return false;
2734 
2735   // The callee has to preserve all registers the caller needs to preserve.
2736   if (!CCMatch) {
2737     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2738     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2739       return false;
2740   }
2741 
2742   // Nothing more to check if the callee is taking no arguments.
2743   if (Outs.empty())
2744     return true;
2745 
2746   SmallVector<CCValAssign, 16> ArgLocs;
2747   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2748 
2749   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2750 
2751   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2752   // If the stack arguments for this call do not fit into our own save area then
2753   // the call cannot be made tail.
2754   // TODO: Is this really necessary?
2755   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2756     return false;
2757 
2758   const MachineRegisterInfo &MRI = MF.getRegInfo();
2759   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2760 }
2761 
2762 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2763   if (!CI->isTailCall())
2764     return false;
2765 
2766   const Function *ParentFn = CI->getParent()->getParent();
2767   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2768     return false;
2769   return true;
2770 }
2771 
2772 // The wave scratch offset register is used as the global base pointer.
2773 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2774                                     SmallVectorImpl<SDValue> &InVals) const {
2775   SelectionDAG &DAG = CLI.DAG;
2776   const SDLoc &DL = CLI.DL;
2777   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2778   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2779   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2780   SDValue Chain = CLI.Chain;
2781   SDValue Callee = CLI.Callee;
2782   bool &IsTailCall = CLI.IsTailCall;
2783   CallingConv::ID CallConv = CLI.CallConv;
2784   bool IsVarArg = CLI.IsVarArg;
2785   bool IsSibCall = false;
2786   bool IsThisReturn = false;
2787   MachineFunction &MF = DAG.getMachineFunction();
2788 
2789   if (Callee.isUndef() || isNullConstant(Callee)) {
2790     if (!CLI.IsTailCall) {
2791       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2792         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2793     }
2794 
2795     return Chain;
2796   }
2797 
2798   if (IsVarArg) {
2799     return lowerUnhandledCall(CLI, InVals,
2800                               "unsupported call to variadic function ");
2801   }
2802 
2803   if (!CLI.CB)
2804     report_fatal_error("unsupported libcall legalization");
2805 
2806   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2807       !CLI.CB->getCalledFunction()) {
2808     return lowerUnhandledCall(CLI, InVals,
2809                               "unsupported indirect call to function ");
2810   }
2811 
2812   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2813     return lowerUnhandledCall(CLI, InVals,
2814                               "unsupported required tail call to function ");
2815   }
2816 
2817   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2818     // Note the issue is with the CC of the calling function, not of the call
2819     // itself.
2820     return lowerUnhandledCall(CLI, InVals,
2821                           "unsupported call from graphics shader of function ");
2822   }
2823 
2824   if (IsTailCall) {
2825     IsTailCall = isEligibleForTailCallOptimization(
2826       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2827     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2828       report_fatal_error("failed to perform tail call elimination on a call "
2829                          "site marked musttail");
2830     }
2831 
2832     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2833 
2834     // A sibling call is one where we're under the usual C ABI and not planning
2835     // to change that but can still do a tail call:
2836     if (!TailCallOpt && IsTailCall)
2837       IsSibCall = true;
2838 
2839     if (IsTailCall)
2840       ++NumTailCalls;
2841   }
2842 
2843   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2844   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2845   SmallVector<SDValue, 8> MemOpChains;
2846 
2847   // Analyze operands of the call, assigning locations to each operand.
2848   SmallVector<CCValAssign, 16> ArgLocs;
2849   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2850   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2851 
2852   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2853     // With a fixed ABI, allocate fixed registers before user arguments.
2854     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2855   }
2856 
2857   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2858 
2859   // Get a count of how many bytes are to be pushed on the stack.
2860   unsigned NumBytes = CCInfo.getNextStackOffset();
2861 
2862   if (IsSibCall) {
2863     // Since we're not changing the ABI to make this a tail call, the memory
2864     // operands are already available in the caller's incoming argument space.
2865     NumBytes = 0;
2866   }
2867 
2868   // FPDiff is the byte offset of the call's argument area from the callee's.
2869   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2870   // by this amount for a tail call. In a sibling call it must be 0 because the
2871   // caller will deallocate the entire stack and the callee still expects its
2872   // arguments to begin at SP+0. Completely unused for non-tail calls.
2873   int32_t FPDiff = 0;
2874   MachineFrameInfo &MFI = MF.getFrameInfo();
2875 
2876   // Adjust the stack pointer for the new arguments...
2877   // These operations are automatically eliminated by the prolog/epilog pass
2878   if (!IsSibCall) {
2879     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2880 
2881     SmallVector<SDValue, 4> CopyFromChains;
2882 
2883     // In the HSA case, this should be an identity copy.
2884     SDValue ScratchRSrcReg
2885       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2886     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2887     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2888     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2889   }
2890 
2891   MVT PtrVT = MVT::i32;
2892 
2893   // Walk the register/memloc assignments, inserting copies/loads.
2894   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2895     CCValAssign &VA = ArgLocs[i];
2896     SDValue Arg = OutVals[i];
2897 
2898     // Promote the value if needed.
2899     switch (VA.getLocInfo()) {
2900     case CCValAssign::Full:
2901       break;
2902     case CCValAssign::BCvt:
2903       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2904       break;
2905     case CCValAssign::ZExt:
2906       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2907       break;
2908     case CCValAssign::SExt:
2909       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2910       break;
2911     case CCValAssign::AExt:
2912       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2913       break;
2914     case CCValAssign::FPExt:
2915       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2916       break;
2917     default:
2918       llvm_unreachable("Unknown loc info!");
2919     }
2920 
2921     if (VA.isRegLoc()) {
2922       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2923     } else {
2924       assert(VA.isMemLoc());
2925 
2926       SDValue DstAddr;
2927       MachinePointerInfo DstInfo;
2928 
2929       unsigned LocMemOffset = VA.getLocMemOffset();
2930       int32_t Offset = LocMemOffset;
2931 
2932       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2933       MaybeAlign Alignment;
2934 
2935       if (IsTailCall) {
2936         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2937         unsigned OpSize = Flags.isByVal() ?
2938           Flags.getByValSize() : VA.getValVT().getStoreSize();
2939 
2940         // FIXME: We can have better than the minimum byval required alignment.
2941         Alignment =
2942             Flags.isByVal()
2943                 ? Flags.getNonZeroByValAlign()
2944                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2945 
2946         Offset = Offset + FPDiff;
2947         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2948 
2949         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2950         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2951 
2952         // Make sure any stack arguments overlapping with where we're storing
2953         // are loaded before this eventual operation. Otherwise they'll be
2954         // clobbered.
2955 
2956         // FIXME: Why is this really necessary? This seems to just result in a
2957         // lot of code to copy the stack and write them back to the same
2958         // locations, which are supposed to be immutable?
2959         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2960       } else {
2961         DstAddr = PtrOff;
2962         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2963         Alignment =
2964             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2965       }
2966 
2967       if (Outs[i].Flags.isByVal()) {
2968         SDValue SizeNode =
2969             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2970         SDValue Cpy =
2971             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2972                           Outs[i].Flags.getNonZeroByValAlign(),
2973                           /*isVol = */ false, /*AlwaysInline = */ true,
2974                           /*isTailCall = */ false, DstInfo,
2975                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2976 
2977         MemOpChains.push_back(Cpy);
2978       } else {
2979         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2980                                      Alignment ? Alignment->value() : 0);
2981         MemOpChains.push_back(Store);
2982       }
2983     }
2984   }
2985 
2986   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2987     // Copy special input registers after user input arguments.
2988     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2989   }
2990 
2991   if (!MemOpChains.empty())
2992     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2993 
2994   // Build a sequence of copy-to-reg nodes chained together with token chain
2995   // and flag operands which copy the outgoing args into the appropriate regs.
2996   SDValue InFlag;
2997   for (auto &RegToPass : RegsToPass) {
2998     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2999                              RegToPass.second, InFlag);
3000     InFlag = Chain.getValue(1);
3001   }
3002 
3003 
3004   SDValue PhysReturnAddrReg;
3005   if (IsTailCall) {
3006     // Since the return is being combined with the call, we need to pass on the
3007     // return address.
3008 
3009     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3010     SDValue ReturnAddrReg = CreateLiveInRegister(
3011       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3012 
3013     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3014                                         MVT::i64);
3015     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3016     InFlag = Chain.getValue(1);
3017   }
3018 
3019   // We don't usually want to end the call-sequence here because we would tidy
3020   // the frame up *after* the call, however in the ABI-changing tail-call case
3021   // we've carefully laid out the parameters so that when sp is reset they'll be
3022   // in the correct location.
3023   if (IsTailCall && !IsSibCall) {
3024     Chain = DAG.getCALLSEQ_END(Chain,
3025                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3026                                DAG.getTargetConstant(0, DL, MVT::i32),
3027                                InFlag, DL);
3028     InFlag = Chain.getValue(1);
3029   }
3030 
3031   std::vector<SDValue> Ops;
3032   Ops.push_back(Chain);
3033   Ops.push_back(Callee);
3034   // Add a redundant copy of the callee global which will not be legalized, as
3035   // we need direct access to the callee later.
3036   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3037     const GlobalValue *GV = GSD->getGlobal();
3038     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3039   } else {
3040     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3041   }
3042 
3043   if (IsTailCall) {
3044     // Each tail call may have to adjust the stack by a different amount, so
3045     // this information must travel along with the operation for eventual
3046     // consumption by emitEpilogue.
3047     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3048 
3049     Ops.push_back(PhysReturnAddrReg);
3050   }
3051 
3052   // Add argument registers to the end of the list so that they are known live
3053   // into the call.
3054   for (auto &RegToPass : RegsToPass) {
3055     Ops.push_back(DAG.getRegister(RegToPass.first,
3056                                   RegToPass.second.getValueType()));
3057   }
3058 
3059   // Add a register mask operand representing the call-preserved registers.
3060 
3061   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3062   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3063   assert(Mask && "Missing call preserved mask for calling convention");
3064   Ops.push_back(DAG.getRegisterMask(Mask));
3065 
3066   if (InFlag.getNode())
3067     Ops.push_back(InFlag);
3068 
3069   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3070 
3071   // If we're doing a tall call, use a TC_RETURN here rather than an
3072   // actual call instruction.
3073   if (IsTailCall) {
3074     MFI.setHasTailCall();
3075     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3076   }
3077 
3078   // Returns a chain and a flag for retval copy to use.
3079   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3080   Chain = Call.getValue(0);
3081   InFlag = Call.getValue(1);
3082 
3083   uint64_t CalleePopBytes = NumBytes;
3084   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3085                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3086                              InFlag, DL);
3087   if (!Ins.empty())
3088     InFlag = Chain.getValue(1);
3089 
3090   // Handle result values, copying them out of physregs into vregs that we
3091   // return.
3092   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3093                          InVals, IsThisReturn,
3094                          IsThisReturn ? OutVals[0] : SDValue());
3095 }
3096 
3097 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3098 // except for applying the wave size scale to the increment amount.
3099 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3100     SDValue Op, SelectionDAG &DAG) const {
3101   const MachineFunction &MF = DAG.getMachineFunction();
3102   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3103 
3104   SDLoc dl(Op);
3105   EVT VT = Op.getValueType();
3106   SDValue Tmp1 = Op;
3107   SDValue Tmp2 = Op.getValue(1);
3108   SDValue Tmp3 = Op.getOperand(2);
3109   SDValue Chain = Tmp1.getOperand(0);
3110 
3111   Register SPReg = Info->getStackPtrOffsetReg();
3112 
3113   // Chain the dynamic stack allocation so that it doesn't modify the stack
3114   // pointer when other instructions are using the stack.
3115   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3116 
3117   SDValue Size  = Tmp2.getOperand(1);
3118   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3119   Chain = SP.getValue(1);
3120   unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
3121   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3122   const TargetFrameLowering *TFL = ST.getFrameLowering();
3123   unsigned Opc =
3124     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3125     ISD::ADD : ISD::SUB;
3126 
3127   SDValue ScaledSize = DAG.getNode(
3128       ISD::SHL, dl, VT, Size,
3129       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3130 
3131   unsigned StackAlign = TFL->getStackAlignment();
3132   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3133   if (Align > StackAlign) {
3134     Tmp1 = DAG.getNode(
3135       ISD::AND, dl, VT, Tmp1,
3136       DAG.getConstant(-(uint64_t)Align << ST.getWavefrontSizeLog2(), dl, VT));
3137   }
3138 
3139   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3140   Tmp2 = DAG.getCALLSEQ_END(
3141       Chain, DAG.getIntPtrConstant(0, dl, true),
3142       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3143 
3144   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3145 }
3146 
3147 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3148                                                   SelectionDAG &DAG) const {
3149   // We only handle constant sizes here to allow non-entry block, static sized
3150   // allocas. A truly dynamic value is more difficult to support because we
3151   // don't know if the size value is uniform or not. If the size isn't uniform,
3152   // we would need to do a wave reduction to get the maximum size to know how
3153   // much to increment the uniform stack pointer.
3154   SDValue Size = Op.getOperand(1);
3155   if (isa<ConstantSDNode>(Size))
3156       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3157 
3158   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3159 }
3160 
3161 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3162                                              const MachineFunction &MF) const {
3163   Register Reg = StringSwitch<Register>(RegName)
3164     .Case("m0", AMDGPU::M0)
3165     .Case("exec", AMDGPU::EXEC)
3166     .Case("exec_lo", AMDGPU::EXEC_LO)
3167     .Case("exec_hi", AMDGPU::EXEC_HI)
3168     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3169     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3170     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3171     .Default(Register());
3172 
3173   if (Reg == AMDGPU::NoRegister) {
3174     report_fatal_error(Twine("invalid register name \""
3175                              + StringRef(RegName)  + "\"."));
3176 
3177   }
3178 
3179   if (!Subtarget->hasFlatScrRegister() &&
3180        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3181     report_fatal_error(Twine("invalid register \""
3182                              + StringRef(RegName)  + "\" for subtarget."));
3183   }
3184 
3185   switch (Reg) {
3186   case AMDGPU::M0:
3187   case AMDGPU::EXEC_LO:
3188   case AMDGPU::EXEC_HI:
3189   case AMDGPU::FLAT_SCR_LO:
3190   case AMDGPU::FLAT_SCR_HI:
3191     if (VT.getSizeInBits() == 32)
3192       return Reg;
3193     break;
3194   case AMDGPU::EXEC:
3195   case AMDGPU::FLAT_SCR:
3196     if (VT.getSizeInBits() == 64)
3197       return Reg;
3198     break;
3199   default:
3200     llvm_unreachable("missing register type checking");
3201   }
3202 
3203   report_fatal_error(Twine("invalid type for register \""
3204                            + StringRef(RegName) + "\"."));
3205 }
3206 
3207 // If kill is not the last instruction, split the block so kill is always a
3208 // proper terminator.
3209 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3210                                                     MachineBasicBlock *BB) const {
3211   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3212 
3213   MachineBasicBlock::iterator SplitPoint(&MI);
3214   ++SplitPoint;
3215 
3216   if (SplitPoint == BB->end()) {
3217     // Don't bother with a new block.
3218     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3219     return BB;
3220   }
3221 
3222   MachineFunction *MF = BB->getParent();
3223   MachineBasicBlock *SplitBB
3224     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3225 
3226   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3227   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3228 
3229   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3230   BB->addSuccessor(SplitBB);
3231 
3232   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3233   return SplitBB;
3234 }
3235 
3236 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3237 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3238 // be the first instruction in the remainder block.
3239 //
3240 /// \returns { LoopBody, Remainder }
3241 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3242 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3243   MachineFunction *MF = MBB.getParent();
3244   MachineBasicBlock::iterator I(&MI);
3245 
3246   // To insert the loop we need to split the block. Move everything after this
3247   // point to a new block, and insert a new empty block between the two.
3248   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3249   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3250   MachineFunction::iterator MBBI(MBB);
3251   ++MBBI;
3252 
3253   MF->insert(MBBI, LoopBB);
3254   MF->insert(MBBI, RemainderBB);
3255 
3256   LoopBB->addSuccessor(LoopBB);
3257   LoopBB->addSuccessor(RemainderBB);
3258 
3259   // Move the rest of the block into a new block.
3260   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3261 
3262   if (InstInLoop) {
3263     auto Next = std::next(I);
3264 
3265     // Move instruction to loop body.
3266     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3267 
3268     // Move the rest of the block.
3269     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3270   } else {
3271     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3272   }
3273 
3274   MBB.addSuccessor(LoopBB);
3275 
3276   return std::make_pair(LoopBB, RemainderBB);
3277 }
3278 
3279 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3280 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3281   MachineBasicBlock *MBB = MI.getParent();
3282   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3283   auto I = MI.getIterator();
3284   auto E = std::next(I);
3285 
3286   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3287     .addImm(0);
3288 
3289   MIBundleBuilder Bundler(*MBB, I, E);
3290   finalizeBundle(*MBB, Bundler.begin());
3291 }
3292 
3293 MachineBasicBlock *
3294 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3295                                          MachineBasicBlock *BB) const {
3296   const DebugLoc &DL = MI.getDebugLoc();
3297 
3298   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3299 
3300   MachineBasicBlock *LoopBB;
3301   MachineBasicBlock *RemainderBB;
3302   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3303 
3304   // Apparently kill flags are only valid if the def is in the same block?
3305   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3306     Src->setIsKill(false);
3307 
3308   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3309 
3310   MachineBasicBlock::iterator I = LoopBB->end();
3311 
3312   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3313     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3314 
3315   // Clear TRAP_STS.MEM_VIOL
3316   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3317     .addImm(0)
3318     .addImm(EncodedReg);
3319 
3320   bundleInstWithWaitcnt(MI);
3321 
3322   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3323 
3324   // Load and check TRAP_STS.MEM_VIOL
3325   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3326     .addImm(EncodedReg);
3327 
3328   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3329   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3330     .addReg(Reg, RegState::Kill)
3331     .addImm(0);
3332   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3333     .addMBB(LoopBB);
3334 
3335   return RemainderBB;
3336 }
3337 
3338 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3339 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3340 // will only do one iteration. In the worst case, this will loop 64 times.
3341 //
3342 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3343 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3344   const SIInstrInfo *TII,
3345   MachineRegisterInfo &MRI,
3346   MachineBasicBlock &OrigBB,
3347   MachineBasicBlock &LoopBB,
3348   const DebugLoc &DL,
3349   const MachineOperand &IdxReg,
3350   unsigned InitReg,
3351   unsigned ResultReg,
3352   unsigned PhiReg,
3353   unsigned InitSaveExecReg,
3354   int Offset,
3355   bool UseGPRIdxMode,
3356   bool IsIndirectSrc) {
3357   MachineFunction *MF = OrigBB.getParent();
3358   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3359   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3360   MachineBasicBlock::iterator I = LoopBB.begin();
3361 
3362   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3363   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3364   Register NewExec = MRI.createVirtualRegister(BoolRC);
3365   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3366   Register CondReg = MRI.createVirtualRegister(BoolRC);
3367 
3368   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3369     .addReg(InitReg)
3370     .addMBB(&OrigBB)
3371     .addReg(ResultReg)
3372     .addMBB(&LoopBB);
3373 
3374   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3375     .addReg(InitSaveExecReg)
3376     .addMBB(&OrigBB)
3377     .addReg(NewExec)
3378     .addMBB(&LoopBB);
3379 
3380   // Read the next variant <- also loop target.
3381   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3382     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3383 
3384   // Compare the just read M0 value to all possible Idx values.
3385   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3386     .addReg(CurrentIdxReg)
3387     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3388 
3389   // Update EXEC, save the original EXEC value to VCC.
3390   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3391                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3392           NewExec)
3393     .addReg(CondReg, RegState::Kill);
3394 
3395   MRI.setSimpleHint(NewExec, CondReg);
3396 
3397   if (UseGPRIdxMode) {
3398     unsigned IdxReg;
3399     if (Offset == 0) {
3400       IdxReg = CurrentIdxReg;
3401     } else {
3402       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3403       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3404         .addReg(CurrentIdxReg, RegState::Kill)
3405         .addImm(Offset);
3406     }
3407     unsigned IdxMode = IsIndirectSrc ?
3408       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3409     MachineInstr *SetOn =
3410       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3411       .addReg(IdxReg, RegState::Kill)
3412       .addImm(IdxMode);
3413     SetOn->getOperand(3).setIsUndef();
3414   } else {
3415     // Move index from VCC into M0
3416     if (Offset == 0) {
3417       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3418         .addReg(CurrentIdxReg, RegState::Kill);
3419     } else {
3420       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3421         .addReg(CurrentIdxReg, RegState::Kill)
3422         .addImm(Offset);
3423     }
3424   }
3425 
3426   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3427   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3428   MachineInstr *InsertPt =
3429     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3430                                                   : AMDGPU::S_XOR_B64_term), Exec)
3431       .addReg(Exec)
3432       .addReg(NewExec);
3433 
3434   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3435   // s_cbranch_scc0?
3436 
3437   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3438   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3439     .addMBB(&LoopBB);
3440 
3441   return InsertPt->getIterator();
3442 }
3443 
3444 // This has slightly sub-optimal regalloc when the source vector is killed by
3445 // the read. The register allocator does not understand that the kill is
3446 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3447 // subregister from it, using 1 more VGPR than necessary. This was saved when
3448 // this was expanded after register allocation.
3449 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3450                                                   MachineBasicBlock &MBB,
3451                                                   MachineInstr &MI,
3452                                                   unsigned InitResultReg,
3453                                                   unsigned PhiReg,
3454                                                   int Offset,
3455                                                   bool UseGPRIdxMode,
3456                                                   bool IsIndirectSrc) {
3457   MachineFunction *MF = MBB.getParent();
3458   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3459   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3460   MachineRegisterInfo &MRI = MF->getRegInfo();
3461   const DebugLoc &DL = MI.getDebugLoc();
3462   MachineBasicBlock::iterator I(&MI);
3463 
3464   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3465   Register DstReg = MI.getOperand(0).getReg();
3466   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3467   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3468   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3469   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3470 
3471   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3472 
3473   // Save the EXEC mask
3474   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3475     .addReg(Exec);
3476 
3477   MachineBasicBlock *LoopBB;
3478   MachineBasicBlock *RemainderBB;
3479   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3480 
3481   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3482 
3483   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3484                                       InitResultReg, DstReg, PhiReg, TmpExec,
3485                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3486   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3487   MachineFunction::iterator MBBI(LoopBB);
3488   ++MBBI;
3489   MF->insert(MBBI, LandingPad);
3490   LoopBB->removeSuccessor(RemainderBB);
3491   LandingPad->addSuccessor(RemainderBB);
3492   LoopBB->addSuccessor(LandingPad);
3493   MachineBasicBlock::iterator First = LandingPad->begin();
3494   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3495     .addReg(SaveExec);
3496 
3497   return InsPt;
3498 }
3499 
3500 // Returns subreg index, offset
3501 static std::pair<unsigned, int>
3502 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3503                             const TargetRegisterClass *SuperRC,
3504                             unsigned VecReg,
3505                             int Offset) {
3506   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3507 
3508   // Skip out of bounds offsets, or else we would end up using an undefined
3509   // register.
3510   if (Offset >= NumElts || Offset < 0)
3511     return std::make_pair(AMDGPU::sub0, Offset);
3512 
3513   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3514 }
3515 
3516 // Return true if the index is an SGPR and was set.
3517 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3518                                  MachineRegisterInfo &MRI,
3519                                  MachineInstr &MI,
3520                                  int Offset,
3521                                  bool UseGPRIdxMode,
3522                                  bool IsIndirectSrc) {
3523   MachineBasicBlock *MBB = MI.getParent();
3524   const DebugLoc &DL = MI.getDebugLoc();
3525   MachineBasicBlock::iterator I(&MI);
3526 
3527   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3528   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3529 
3530   assert(Idx->getReg() != AMDGPU::NoRegister);
3531 
3532   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3533     return false;
3534 
3535   if (UseGPRIdxMode) {
3536     unsigned IdxMode = IsIndirectSrc ?
3537       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3538     if (Offset == 0) {
3539       MachineInstr *SetOn =
3540           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3541               .add(*Idx)
3542               .addImm(IdxMode);
3543 
3544       SetOn->getOperand(3).setIsUndef();
3545     } else {
3546       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3547       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3548           .add(*Idx)
3549           .addImm(Offset);
3550       MachineInstr *SetOn =
3551         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3552         .addReg(Tmp, RegState::Kill)
3553         .addImm(IdxMode);
3554 
3555       SetOn->getOperand(3).setIsUndef();
3556     }
3557 
3558     return true;
3559   }
3560 
3561   if (Offset == 0) {
3562     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3563       .add(*Idx);
3564   } else {
3565     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3566       .add(*Idx)
3567       .addImm(Offset);
3568   }
3569 
3570   return true;
3571 }
3572 
3573 // Control flow needs to be inserted if indexing with a VGPR.
3574 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3575                                           MachineBasicBlock &MBB,
3576                                           const GCNSubtarget &ST) {
3577   const SIInstrInfo *TII = ST.getInstrInfo();
3578   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3579   MachineFunction *MF = MBB.getParent();
3580   MachineRegisterInfo &MRI = MF->getRegInfo();
3581 
3582   Register Dst = MI.getOperand(0).getReg();
3583   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3584   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3585 
3586   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3587 
3588   unsigned SubReg;
3589   std::tie(SubReg, Offset)
3590     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3591 
3592   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3593 
3594   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3595     MachineBasicBlock::iterator I(&MI);
3596     const DebugLoc &DL = MI.getDebugLoc();
3597 
3598     if (UseGPRIdxMode) {
3599       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3600       // to avoid interfering with other uses, so probably requires a new
3601       // optimization pass.
3602       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3603         .addReg(SrcReg, RegState::Undef, SubReg)
3604         .addReg(SrcReg, RegState::Implicit)
3605         .addReg(AMDGPU::M0, RegState::Implicit);
3606       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3607     } else {
3608       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3609         .addReg(SrcReg, RegState::Undef, SubReg)
3610         .addReg(SrcReg, RegState::Implicit);
3611     }
3612 
3613     MI.eraseFromParent();
3614 
3615     return &MBB;
3616   }
3617 
3618   const DebugLoc &DL = MI.getDebugLoc();
3619   MachineBasicBlock::iterator I(&MI);
3620 
3621   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3622   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3623 
3624   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3625 
3626   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3627                               Offset, UseGPRIdxMode, true);
3628   MachineBasicBlock *LoopBB = InsPt->getParent();
3629 
3630   if (UseGPRIdxMode) {
3631     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3632       .addReg(SrcReg, RegState::Undef, SubReg)
3633       .addReg(SrcReg, RegState::Implicit)
3634       .addReg(AMDGPU::M0, RegState::Implicit);
3635     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3636   } else {
3637     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3638       .addReg(SrcReg, RegState::Undef, SubReg)
3639       .addReg(SrcReg, RegState::Implicit);
3640   }
3641 
3642   MI.eraseFromParent();
3643 
3644   return LoopBB;
3645 }
3646 
3647 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3648                                           MachineBasicBlock &MBB,
3649                                           const GCNSubtarget &ST) {
3650   const SIInstrInfo *TII = ST.getInstrInfo();
3651   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3652   MachineFunction *MF = MBB.getParent();
3653   MachineRegisterInfo &MRI = MF->getRegInfo();
3654 
3655   Register Dst = MI.getOperand(0).getReg();
3656   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3657   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3658   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3659   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3660   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3661 
3662   // This can be an immediate, but will be folded later.
3663   assert(Val->getReg());
3664 
3665   unsigned SubReg;
3666   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3667                                                          SrcVec->getReg(),
3668                                                          Offset);
3669   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3670 
3671   if (Idx->getReg() == AMDGPU::NoRegister) {
3672     MachineBasicBlock::iterator I(&MI);
3673     const DebugLoc &DL = MI.getDebugLoc();
3674 
3675     assert(Offset == 0);
3676 
3677     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3678         .add(*SrcVec)
3679         .add(*Val)
3680         .addImm(SubReg);
3681 
3682     MI.eraseFromParent();
3683     return &MBB;
3684   }
3685 
3686   const MCInstrDesc &MovRelDesc
3687     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3688 
3689   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3690     MachineBasicBlock::iterator I(&MI);
3691     const DebugLoc &DL = MI.getDebugLoc();
3692     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3693       .addReg(SrcVec->getReg())
3694       .add(*Val)
3695       .addImm(SubReg);
3696     if (UseGPRIdxMode)
3697       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3698 
3699     MI.eraseFromParent();
3700     return &MBB;
3701   }
3702 
3703   if (Val->isReg())
3704     MRI.clearKillFlags(Val->getReg());
3705 
3706   const DebugLoc &DL = MI.getDebugLoc();
3707 
3708   Register PhiReg = MRI.createVirtualRegister(VecRC);
3709 
3710   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3711                               Offset, UseGPRIdxMode, false);
3712   MachineBasicBlock *LoopBB = InsPt->getParent();
3713 
3714   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3715     .addReg(PhiReg)
3716     .add(*Val)
3717     .addImm(AMDGPU::sub0);
3718   if (UseGPRIdxMode)
3719     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3720 
3721   MI.eraseFromParent();
3722   return LoopBB;
3723 }
3724 
3725 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3726   MachineInstr &MI, MachineBasicBlock *BB) const {
3727 
3728   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3729   MachineFunction *MF = BB->getParent();
3730   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3731 
3732   switch (MI.getOpcode()) {
3733   case AMDGPU::S_UADDO_PSEUDO:
3734   case AMDGPU::S_USUBO_PSEUDO: {
3735     const DebugLoc &DL = MI.getDebugLoc();
3736     MachineOperand &Dest0 = MI.getOperand(0);
3737     MachineOperand &Dest1 = MI.getOperand(1);
3738     MachineOperand &Src0 = MI.getOperand(2);
3739     MachineOperand &Src1 = MI.getOperand(3);
3740 
3741     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3742                        ? AMDGPU::S_ADD_I32
3743                        : AMDGPU::S_SUB_I32;
3744     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3745 
3746     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3747         .addImm(1)
3748         .addImm(0);
3749 
3750     MI.eraseFromParent();
3751     return BB;
3752   }
3753   case AMDGPU::S_ADD_U64_PSEUDO:
3754   case AMDGPU::S_SUB_U64_PSEUDO: {
3755     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3756     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3757     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3758     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3759     const DebugLoc &DL = MI.getDebugLoc();
3760 
3761     MachineOperand &Dest = MI.getOperand(0);
3762     MachineOperand &Src0 = MI.getOperand(1);
3763     MachineOperand &Src1 = MI.getOperand(2);
3764 
3765     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3766     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3767 
3768     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3769         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3770     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3771         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3772 
3773     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3774         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3775     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3776         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3777 
3778     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3779 
3780     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3781     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3782     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3783     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3784     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3785         .addReg(DestSub0)
3786         .addImm(AMDGPU::sub0)
3787         .addReg(DestSub1)
3788         .addImm(AMDGPU::sub1);
3789     MI.eraseFromParent();
3790     return BB;
3791   }
3792   case AMDGPU::V_ADD_U64_PSEUDO:
3793   case AMDGPU::V_SUB_U64_PSEUDO: {
3794     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3795     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3796     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3797     const DebugLoc &DL = MI.getDebugLoc();
3798 
3799     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3800 
3801     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3802 
3803     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3804     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3805 
3806     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3807     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3808 
3809     MachineOperand &Dest = MI.getOperand(0);
3810     MachineOperand &Src0 = MI.getOperand(1);
3811     MachineOperand &Src1 = MI.getOperand(2);
3812 
3813     const TargetRegisterClass *Src0RC = Src0.isReg()
3814                                             ? MRI.getRegClass(Src0.getReg())
3815                                             : &AMDGPU::VReg_64RegClass;
3816     const TargetRegisterClass *Src1RC = Src1.isReg()
3817                                             ? MRI.getRegClass(Src1.getReg())
3818                                             : &AMDGPU::VReg_64RegClass;
3819 
3820     const TargetRegisterClass *Src0SubRC =
3821         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3822     const TargetRegisterClass *Src1SubRC =
3823         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3824 
3825     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3826         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3827     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3828         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3829 
3830     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3831         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3832     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3833         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3834 
3835     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
3836     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3837                                .addReg(CarryReg, RegState::Define)
3838                                .add(SrcReg0Sub0)
3839                                .add(SrcReg1Sub0)
3840                                .addImm(0); // clamp bit
3841 
3842     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3843     MachineInstr *HiHalf =
3844         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3845             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3846             .add(SrcReg0Sub1)
3847             .add(SrcReg1Sub1)
3848             .addReg(CarryReg, RegState::Kill)
3849             .addImm(0); // clamp bit
3850 
3851     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3852         .addReg(DestSub0)
3853         .addImm(AMDGPU::sub0)
3854         .addReg(DestSub1)
3855         .addImm(AMDGPU::sub1);
3856     TII->legalizeOperands(*LoHalf);
3857     TII->legalizeOperands(*HiHalf);
3858     MI.eraseFromParent();
3859     return BB;
3860   }
3861   case AMDGPU::S_ADD_CO_PSEUDO:
3862   case AMDGPU::S_SUB_CO_PSEUDO: {
3863     // This pseudo has a chance to be selected
3864     // only from uniform add/subcarry node. All the VGPR operands
3865     // therefore assumed to be splat vectors.
3866     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3867     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3868     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3869     MachineBasicBlock::iterator MII = MI;
3870     const DebugLoc &DL = MI.getDebugLoc();
3871     MachineOperand &Dest = MI.getOperand(0);
3872     MachineOperand &Src0 = MI.getOperand(2);
3873     MachineOperand &Src1 = MI.getOperand(3);
3874     MachineOperand &Src2 = MI.getOperand(4);
3875     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3876                        ? AMDGPU::S_ADDC_U32
3877                        : AMDGPU::S_SUBB_U32;
3878     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3879       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3880       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3881           .addReg(Src0.getReg());
3882       Src0.setReg(RegOp0);
3883     }
3884     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3885       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3886       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3887           .addReg(Src1.getReg());
3888       Src1.setReg(RegOp1);
3889     }
3890     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3891     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3892       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3893           .addReg(Src2.getReg());
3894       Src2.setReg(RegOp2);
3895     }
3896 
3897     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3898       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3899           .addReg(Src2.getReg())
3900           .addImm(0);
3901     } else {
3902       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3903           .addReg(Src2.getReg())
3904           .addImm(0);
3905     }
3906 
3907     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3908     MI.eraseFromParent();
3909     return BB;
3910   }
3911   case AMDGPU::SI_INIT_M0: {
3912     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3913             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3914         .add(MI.getOperand(0));
3915     MI.eraseFromParent();
3916     return BB;
3917   }
3918   case AMDGPU::SI_INIT_EXEC:
3919     // This should be before all vector instructions.
3920     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3921             AMDGPU::EXEC)
3922         .addImm(MI.getOperand(0).getImm());
3923     MI.eraseFromParent();
3924     return BB;
3925 
3926   case AMDGPU::SI_INIT_EXEC_LO:
3927     // This should be before all vector instructions.
3928     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3929             AMDGPU::EXEC_LO)
3930         .addImm(MI.getOperand(0).getImm());
3931     MI.eraseFromParent();
3932     return BB;
3933 
3934   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3935     // Extract the thread count from an SGPR input and set EXEC accordingly.
3936     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3937     //
3938     // S_BFE_U32 count, input, {shift, 7}
3939     // S_BFM_B64 exec, count, 0
3940     // S_CMP_EQ_U32 count, 64
3941     // S_CMOV_B64 exec, -1
3942     MachineInstr *FirstMI = &*BB->begin();
3943     MachineRegisterInfo &MRI = MF->getRegInfo();
3944     Register InputReg = MI.getOperand(0).getReg();
3945     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3946     bool Found = false;
3947 
3948     // Move the COPY of the input reg to the beginning, so that we can use it.
3949     for (auto I = BB->begin(); I != &MI; I++) {
3950       if (I->getOpcode() != TargetOpcode::COPY ||
3951           I->getOperand(0).getReg() != InputReg)
3952         continue;
3953 
3954       if (I == FirstMI) {
3955         FirstMI = &*++BB->begin();
3956       } else {
3957         I->removeFromParent();
3958         BB->insert(FirstMI, &*I);
3959       }
3960       Found = true;
3961       break;
3962     }
3963     assert(Found);
3964     (void)Found;
3965 
3966     // This should be before all vector instructions.
3967     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3968     bool isWave32 = getSubtarget()->isWave32();
3969     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3970     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3971         .addReg(InputReg)
3972         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3973     BuildMI(*BB, FirstMI, DebugLoc(),
3974             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3975             Exec)
3976         .addReg(CountReg)
3977         .addImm(0);
3978     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3979         .addReg(CountReg, RegState::Kill)
3980         .addImm(getSubtarget()->getWavefrontSize());
3981     BuildMI(*BB, FirstMI, DebugLoc(),
3982             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3983             Exec)
3984         .addImm(-1);
3985     MI.eraseFromParent();
3986     return BB;
3987   }
3988 
3989   case AMDGPU::GET_GROUPSTATICSIZE: {
3990     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3991            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3992     DebugLoc DL = MI.getDebugLoc();
3993     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3994         .add(MI.getOperand(0))
3995         .addImm(MFI->getLDSSize());
3996     MI.eraseFromParent();
3997     return BB;
3998   }
3999   case AMDGPU::SI_INDIRECT_SRC_V1:
4000   case AMDGPU::SI_INDIRECT_SRC_V2:
4001   case AMDGPU::SI_INDIRECT_SRC_V4:
4002   case AMDGPU::SI_INDIRECT_SRC_V8:
4003   case AMDGPU::SI_INDIRECT_SRC_V16:
4004   case AMDGPU::SI_INDIRECT_SRC_V32:
4005     return emitIndirectSrc(MI, *BB, *getSubtarget());
4006   case AMDGPU::SI_INDIRECT_DST_V1:
4007   case AMDGPU::SI_INDIRECT_DST_V2:
4008   case AMDGPU::SI_INDIRECT_DST_V4:
4009   case AMDGPU::SI_INDIRECT_DST_V8:
4010   case AMDGPU::SI_INDIRECT_DST_V16:
4011   case AMDGPU::SI_INDIRECT_DST_V32:
4012     return emitIndirectDst(MI, *BB, *getSubtarget());
4013   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4014   case AMDGPU::SI_KILL_I1_PSEUDO:
4015     return splitKillBlock(MI, BB);
4016   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4017     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4018     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4019     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4020 
4021     Register Dst = MI.getOperand(0).getReg();
4022     Register Src0 = MI.getOperand(1).getReg();
4023     Register Src1 = MI.getOperand(2).getReg();
4024     const DebugLoc &DL = MI.getDebugLoc();
4025     Register SrcCond = MI.getOperand(3).getReg();
4026 
4027     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4028     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4029     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4030     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4031 
4032     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4033       .addReg(SrcCond);
4034     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4035       .addImm(0)
4036       .addReg(Src0, 0, AMDGPU::sub0)
4037       .addImm(0)
4038       .addReg(Src1, 0, AMDGPU::sub0)
4039       .addReg(SrcCondCopy);
4040     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4041       .addImm(0)
4042       .addReg(Src0, 0, AMDGPU::sub1)
4043       .addImm(0)
4044       .addReg(Src1, 0, AMDGPU::sub1)
4045       .addReg(SrcCondCopy);
4046 
4047     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4048       .addReg(DstLo)
4049       .addImm(AMDGPU::sub0)
4050       .addReg(DstHi)
4051       .addImm(AMDGPU::sub1);
4052     MI.eraseFromParent();
4053     return BB;
4054   }
4055   case AMDGPU::SI_BR_UNDEF: {
4056     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4057     const DebugLoc &DL = MI.getDebugLoc();
4058     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4059                            .add(MI.getOperand(0));
4060     Br->getOperand(1).setIsUndef(true); // read undef SCC
4061     MI.eraseFromParent();
4062     return BB;
4063   }
4064   case AMDGPU::ADJCALLSTACKUP:
4065   case AMDGPU::ADJCALLSTACKDOWN: {
4066     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4067     MachineInstrBuilder MIB(*MF, &MI);
4068 
4069     // Add an implicit use of the frame offset reg to prevent the restore copy
4070     // inserted after the call from being reorderd after stack operations in the
4071     // the caller's frame.
4072     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4073         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4074         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4075     return BB;
4076   }
4077   case AMDGPU::SI_CALL_ISEL: {
4078     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4079     const DebugLoc &DL = MI.getDebugLoc();
4080 
4081     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4082 
4083     MachineInstrBuilder MIB;
4084     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4085 
4086     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4087       MIB.add(MI.getOperand(I));
4088 
4089     MIB.cloneMemRefs(MI);
4090     MI.eraseFromParent();
4091     return BB;
4092   }
4093   case AMDGPU::V_ADD_I32_e32:
4094   case AMDGPU::V_SUB_I32_e32:
4095   case AMDGPU::V_SUBREV_I32_e32: {
4096     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4097     const DebugLoc &DL = MI.getDebugLoc();
4098     unsigned Opc = MI.getOpcode();
4099 
4100     bool NeedClampOperand = false;
4101     if (TII->pseudoToMCOpcode(Opc) == -1) {
4102       Opc = AMDGPU::getVOPe64(Opc);
4103       NeedClampOperand = true;
4104     }
4105 
4106     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4107     if (TII->isVOP3(*I)) {
4108       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4109       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4110       I.addReg(TRI->getVCC(), RegState::Define);
4111     }
4112     I.add(MI.getOperand(1))
4113      .add(MI.getOperand(2));
4114     if (NeedClampOperand)
4115       I.addImm(0); // clamp bit for e64 encoding
4116 
4117     TII->legalizeOperands(*I);
4118 
4119     MI.eraseFromParent();
4120     return BB;
4121   }
4122   case AMDGPU::DS_GWS_INIT:
4123   case AMDGPU::DS_GWS_SEMA_V:
4124   case AMDGPU::DS_GWS_SEMA_BR:
4125   case AMDGPU::DS_GWS_SEMA_P:
4126   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4127   case AMDGPU::DS_GWS_BARRIER:
4128     // A s_waitcnt 0 is required to be the instruction immediately following.
4129     if (getSubtarget()->hasGWSAutoReplay()) {
4130       bundleInstWithWaitcnt(MI);
4131       return BB;
4132     }
4133 
4134     return emitGWSMemViolTestLoop(MI, BB);
4135   case AMDGPU::S_SETREG_B32: {
4136     if (!getSubtarget()->hasDenormModeInst())
4137       return BB;
4138 
4139     // Try to optimize cases that only set the denormal mode or rounding mode.
4140     //
4141     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4142     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4143     // instead.
4144     //
4145     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4146     // allow you to have a no side effect instruction in the output of a
4147     // sideeffecting pattern.
4148 
4149     // TODO: Should also emit a no side effects pseudo if only FP bits are
4150     // touched, even if not all of them or to a variable.
4151     unsigned ID, Offset, Width;
4152     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4153     if (ID != AMDGPU::Hwreg::ID_MODE)
4154       return BB;
4155 
4156     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4157     const unsigned SetMask = WidthMask << Offset;
4158     unsigned SetDenormOp = 0;
4159     unsigned SetRoundOp = 0;
4160 
4161     // The dedicated instructions can only set the whole denorm or round mode at
4162     // once, not a subset of bits in either.
4163     if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4164                                   AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) {
4165       // If this fully sets both the round and denorm mode, emit the two
4166       // dedicated instructions for these.
4167       assert(Offset == 0);
4168       SetRoundOp = AMDGPU::S_ROUND_MODE;
4169       SetDenormOp = AMDGPU::S_DENORM_MODE;
4170     } else if (Width == 4) {
4171       if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) {
4172         SetRoundOp = AMDGPU::S_ROUND_MODE;
4173         assert(Offset == 0);
4174       } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) {
4175         SetDenormOp = AMDGPU::S_DENORM_MODE;
4176         assert(Offset == 4);
4177       }
4178     }
4179 
4180     if (SetRoundOp || SetDenormOp) {
4181       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4182       MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4183       if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4184         unsigned ImmVal = Def->getOperand(1).getImm();
4185         if (SetRoundOp) {
4186           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4187             .addImm(ImmVal & 0xf);
4188 
4189           // If we also have the denorm mode, get just the denorm mode bits.
4190           ImmVal >>= 4;
4191         }
4192 
4193         if (SetDenormOp) {
4194           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4195             .addImm(ImmVal & 0xf);
4196         }
4197 
4198         MI.eraseFromParent();
4199       }
4200     }
4201 
4202     return BB;
4203   }
4204   default:
4205     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4206   }
4207 }
4208 
4209 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4210   return isTypeLegal(VT.getScalarType());
4211 }
4212 
4213 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4214   // This currently forces unfolding various combinations of fsub into fma with
4215   // free fneg'd operands. As long as we have fast FMA (controlled by
4216   // isFMAFasterThanFMulAndFAdd), we should perform these.
4217 
4218   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4219   // most of these combines appear to be cycle neutral but save on instruction
4220   // count / code size.
4221   return true;
4222 }
4223 
4224 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4225                                          EVT VT) const {
4226   if (!VT.isVector()) {
4227     return MVT::i1;
4228   }
4229   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4230 }
4231 
4232 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4233   // TODO: Should i16 be used always if legal? For now it would force VALU
4234   // shifts.
4235   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4236 }
4237 
4238 // Answering this is somewhat tricky and depends on the specific device which
4239 // have different rates for fma or all f64 operations.
4240 //
4241 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4242 // regardless of which device (although the number of cycles differs between
4243 // devices), so it is always profitable for f64.
4244 //
4245 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4246 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4247 // which we can always do even without fused FP ops since it returns the same
4248 // result as the separate operations and since it is always full
4249 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4250 // however does not support denormals, so we do report fma as faster if we have
4251 // a fast fma device and require denormals.
4252 //
4253 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4254                                                   EVT VT) const {
4255   VT = VT.getScalarType();
4256 
4257   switch (VT.getSimpleVT().SimpleTy) {
4258   case MVT::f32: {
4259     // This is as fast on some subtargets. However, we always have full rate f32
4260     // mad available which returns the same result as the separate operations
4261     // which we should prefer over fma. We can't use this if we want to support
4262     // denormals, so only report this in these cases.
4263     if (hasFP32Denormals(MF))
4264       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4265 
4266     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4267     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4268   }
4269   case MVT::f64:
4270     return true;
4271   case MVT::f16:
4272     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4273   default:
4274     break;
4275   }
4276 
4277   return false;
4278 }
4279 
4280 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4281                                    const SDNode *N) const {
4282   // TODO: Check future ftz flag
4283   // v_mad_f32/v_mac_f32 do not support denormals.
4284   EVT VT = N->getValueType(0);
4285   if (VT == MVT::f32)
4286     return !hasFP32Denormals(DAG.getMachineFunction());
4287   if (VT == MVT::f16) {
4288     return Subtarget->hasMadF16() &&
4289            !hasFP64FP16Denormals(DAG.getMachineFunction());
4290   }
4291 
4292   return false;
4293 }
4294 
4295 //===----------------------------------------------------------------------===//
4296 // Custom DAG Lowering Operations
4297 //===----------------------------------------------------------------------===//
4298 
4299 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4300 // wider vector type is legal.
4301 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4302                                              SelectionDAG &DAG) const {
4303   unsigned Opc = Op.getOpcode();
4304   EVT VT = Op.getValueType();
4305   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4306 
4307   SDValue Lo, Hi;
4308   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4309 
4310   SDLoc SL(Op);
4311   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4312                              Op->getFlags());
4313   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4314                              Op->getFlags());
4315 
4316   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4317 }
4318 
4319 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4320 // wider vector type is legal.
4321 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4322                                               SelectionDAG &DAG) const {
4323   unsigned Opc = Op.getOpcode();
4324   EVT VT = Op.getValueType();
4325   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4326 
4327   SDValue Lo0, Hi0;
4328   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4329   SDValue Lo1, Hi1;
4330   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4331 
4332   SDLoc SL(Op);
4333 
4334   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4335                              Op->getFlags());
4336   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4337                              Op->getFlags());
4338 
4339   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4340 }
4341 
4342 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4343                                               SelectionDAG &DAG) const {
4344   unsigned Opc = Op.getOpcode();
4345   EVT VT = Op.getValueType();
4346   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4347 
4348   SDValue Lo0, Hi0;
4349   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4350   SDValue Lo1, Hi1;
4351   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4352   SDValue Lo2, Hi2;
4353   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4354 
4355   SDLoc SL(Op);
4356 
4357   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4358                              Op->getFlags());
4359   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4360                              Op->getFlags());
4361 
4362   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4363 }
4364 
4365 
4366 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4367   switch (Op.getOpcode()) {
4368   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4369   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4370   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4371   case ISD::LOAD: {
4372     SDValue Result = LowerLOAD(Op, DAG);
4373     assert((!Result.getNode() ||
4374             Result.getNode()->getNumValues() == 2) &&
4375            "Load should return a value and a chain");
4376     return Result;
4377   }
4378 
4379   case ISD::FSIN:
4380   case ISD::FCOS:
4381     return LowerTrig(Op, DAG);
4382   case ISD::SELECT: return LowerSELECT(Op, DAG);
4383   case ISD::FDIV: return LowerFDIV(Op, DAG);
4384   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4385   case ISD::STORE: return LowerSTORE(Op, DAG);
4386   case ISD::GlobalAddress: {
4387     MachineFunction &MF = DAG.getMachineFunction();
4388     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4389     return LowerGlobalAddress(MFI, Op, DAG);
4390   }
4391   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4392   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4393   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4394   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4395   case ISD::INSERT_SUBVECTOR:
4396     return lowerINSERT_SUBVECTOR(Op, DAG);
4397   case ISD::INSERT_VECTOR_ELT:
4398     return lowerINSERT_VECTOR_ELT(Op, DAG);
4399   case ISD::EXTRACT_VECTOR_ELT:
4400     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4401   case ISD::VECTOR_SHUFFLE:
4402     return lowerVECTOR_SHUFFLE(Op, DAG);
4403   case ISD::BUILD_VECTOR:
4404     return lowerBUILD_VECTOR(Op, DAG);
4405   case ISD::FP_ROUND:
4406     return lowerFP_ROUND(Op, DAG);
4407   case ISD::TRAP:
4408     return lowerTRAP(Op, DAG);
4409   case ISD::DEBUGTRAP:
4410     return lowerDEBUGTRAP(Op, DAG);
4411   case ISD::FABS:
4412   case ISD::FNEG:
4413   case ISD::FCANONICALIZE:
4414   case ISD::BSWAP:
4415     return splitUnaryVectorOp(Op, DAG);
4416   case ISD::FMINNUM:
4417   case ISD::FMAXNUM:
4418     return lowerFMINNUM_FMAXNUM(Op, DAG);
4419   case ISD::FMA:
4420     return splitTernaryVectorOp(Op, DAG);
4421   case ISD::SHL:
4422   case ISD::SRA:
4423   case ISD::SRL:
4424   case ISD::ADD:
4425   case ISD::SUB:
4426   case ISD::MUL:
4427   case ISD::SMIN:
4428   case ISD::SMAX:
4429   case ISD::UMIN:
4430   case ISD::UMAX:
4431   case ISD::FADD:
4432   case ISD::FMUL:
4433   case ISD::FMINNUM_IEEE:
4434   case ISD::FMAXNUM_IEEE:
4435     return splitBinaryVectorOp(Op, DAG);
4436   case ISD::SMULO:
4437   case ISD::UMULO:
4438     return lowerXMULO(Op, DAG);
4439   case ISD::DYNAMIC_STACKALLOC:
4440     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4441   }
4442   return SDValue();
4443 }
4444 
4445 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4446                                        const SDLoc &DL,
4447                                        SelectionDAG &DAG, bool Unpacked) {
4448   if (!LoadVT.isVector())
4449     return Result;
4450 
4451   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4452     // Truncate to v2i16/v4i16.
4453     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4454 
4455     // Workaround legalizer not scalarizing truncate after vector op
4456     // legalization byt not creating intermediate vector trunc.
4457     SmallVector<SDValue, 4> Elts;
4458     DAG.ExtractVectorElements(Result, Elts);
4459     for (SDValue &Elt : Elts)
4460       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4461 
4462     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4463 
4464     // Bitcast to original type (v2f16/v4f16).
4465     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4466   }
4467 
4468   // Cast back to the original packed type.
4469   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4470 }
4471 
4472 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4473                                               MemSDNode *M,
4474                                               SelectionDAG &DAG,
4475                                               ArrayRef<SDValue> Ops,
4476                                               bool IsIntrinsic) const {
4477   SDLoc DL(M);
4478 
4479   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4480   EVT LoadVT = M->getValueType(0);
4481 
4482   EVT EquivLoadVT = LoadVT;
4483   if (Unpacked && LoadVT.isVector()) {
4484     EquivLoadVT = LoadVT.isVector() ?
4485       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4486                        LoadVT.getVectorNumElements()) : LoadVT;
4487   }
4488 
4489   // Change from v4f16/v2f16 to EquivLoadVT.
4490   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4491 
4492   SDValue Load
4493     = DAG.getMemIntrinsicNode(
4494       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4495       VTList, Ops, M->getMemoryVT(),
4496       M->getMemOperand());
4497   if (!Unpacked) // Just adjusted the opcode.
4498     return Load;
4499 
4500   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4501 
4502   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4503 }
4504 
4505 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4506                                              SelectionDAG &DAG,
4507                                              ArrayRef<SDValue> Ops) const {
4508   SDLoc DL(M);
4509   EVT LoadVT = M->getValueType(0);
4510   EVT EltType = LoadVT.getScalarType();
4511   EVT IntVT = LoadVT.changeTypeToInteger();
4512 
4513   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4514 
4515   unsigned Opc =
4516       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4517 
4518   if (IsD16) {
4519     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4520   }
4521 
4522   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4523   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4524     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4525 
4526   if (isTypeLegal(LoadVT)) {
4527     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4528                                M->getMemOperand(), DAG);
4529   }
4530 
4531   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4532   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4533   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4534                                         M->getMemOperand(), DAG);
4535   return DAG.getMergeValues(
4536       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4537       DL);
4538 }
4539 
4540 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4541                                   SDNode *N, SelectionDAG &DAG) {
4542   EVT VT = N->getValueType(0);
4543   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4544   int CondCode = CD->getSExtValue();
4545   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4546       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4547     return DAG.getUNDEF(VT);
4548 
4549   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4550 
4551   SDValue LHS = N->getOperand(1);
4552   SDValue RHS = N->getOperand(2);
4553 
4554   SDLoc DL(N);
4555 
4556   EVT CmpVT = LHS.getValueType();
4557   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4558     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4559       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4560     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4561     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4562   }
4563 
4564   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4565 
4566   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4567   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4568 
4569   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4570                               DAG.getCondCode(CCOpcode));
4571   if (VT.bitsEq(CCVT))
4572     return SetCC;
4573   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4574 }
4575 
4576 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4577                                   SDNode *N, SelectionDAG &DAG) {
4578   EVT VT = N->getValueType(0);
4579   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4580 
4581   int CondCode = CD->getSExtValue();
4582   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4583       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4584     return DAG.getUNDEF(VT);
4585   }
4586 
4587   SDValue Src0 = N->getOperand(1);
4588   SDValue Src1 = N->getOperand(2);
4589   EVT CmpVT = Src0.getValueType();
4590   SDLoc SL(N);
4591 
4592   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4593     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4594     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4595   }
4596 
4597   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4598   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4599   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4600   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4601   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4602                               Src1, DAG.getCondCode(CCOpcode));
4603   if (VT.bitsEq(CCVT))
4604     return SetCC;
4605   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4606 }
4607 
4608 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4609                                     SelectionDAG &DAG) {
4610   EVT VT = N->getValueType(0);
4611   SDValue Src = N->getOperand(1);
4612   SDLoc SL(N);
4613 
4614   if (Src.getOpcode() == ISD::SETCC) {
4615     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4616     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4617                        Src.getOperand(1), Src.getOperand(2));
4618   }
4619   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4620     // (ballot 0) -> 0
4621     if (Arg->isNullValue())
4622       return DAG.getConstant(0, SL, VT);
4623 
4624     // (ballot 1) -> EXEC/EXEC_LO
4625     if (Arg->isOne()) {
4626       Register Exec;
4627       if (VT.getScalarSizeInBits() == 32)
4628         Exec = AMDGPU::EXEC_LO;
4629       else if (VT.getScalarSizeInBits() == 64)
4630         Exec = AMDGPU::EXEC;
4631       else
4632         return SDValue();
4633 
4634       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4635     }
4636   }
4637 
4638   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4639   // ISD::SETNE)
4640   return DAG.getNode(
4641       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4642       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4643 }
4644 
4645 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4646                                           SmallVectorImpl<SDValue> &Results,
4647                                           SelectionDAG &DAG) const {
4648   switch (N->getOpcode()) {
4649   case ISD::INSERT_VECTOR_ELT: {
4650     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4651       Results.push_back(Res);
4652     return;
4653   }
4654   case ISD::EXTRACT_VECTOR_ELT: {
4655     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4656       Results.push_back(Res);
4657     return;
4658   }
4659   case ISD::INTRINSIC_WO_CHAIN: {
4660     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4661     switch (IID) {
4662     case Intrinsic::amdgcn_cvt_pkrtz: {
4663       SDValue Src0 = N->getOperand(1);
4664       SDValue Src1 = N->getOperand(2);
4665       SDLoc SL(N);
4666       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4667                                 Src0, Src1);
4668       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4669       return;
4670     }
4671     case Intrinsic::amdgcn_cvt_pknorm_i16:
4672     case Intrinsic::amdgcn_cvt_pknorm_u16:
4673     case Intrinsic::amdgcn_cvt_pk_i16:
4674     case Intrinsic::amdgcn_cvt_pk_u16: {
4675       SDValue Src0 = N->getOperand(1);
4676       SDValue Src1 = N->getOperand(2);
4677       SDLoc SL(N);
4678       unsigned Opcode;
4679 
4680       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4681         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4682       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4683         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4684       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4685         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4686       else
4687         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4688 
4689       EVT VT = N->getValueType(0);
4690       if (isTypeLegal(VT))
4691         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4692       else {
4693         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4694         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4695       }
4696       return;
4697     }
4698     }
4699     break;
4700   }
4701   case ISD::INTRINSIC_W_CHAIN: {
4702     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4703       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4704         // FIXME: Hacky
4705         Results.push_back(Res.getOperand(0));
4706         Results.push_back(Res.getOperand(1));
4707       } else {
4708         Results.push_back(Res);
4709         Results.push_back(Res.getValue(1));
4710       }
4711       return;
4712     }
4713 
4714     break;
4715   }
4716   case ISD::SELECT: {
4717     SDLoc SL(N);
4718     EVT VT = N->getValueType(0);
4719     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4720     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4721     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4722 
4723     EVT SelectVT = NewVT;
4724     if (NewVT.bitsLT(MVT::i32)) {
4725       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4726       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4727       SelectVT = MVT::i32;
4728     }
4729 
4730     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4731                                     N->getOperand(0), LHS, RHS);
4732 
4733     if (NewVT != SelectVT)
4734       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4735     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4736     return;
4737   }
4738   case ISD::FNEG: {
4739     if (N->getValueType(0) != MVT::v2f16)
4740       break;
4741 
4742     SDLoc SL(N);
4743     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4744 
4745     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4746                              BC,
4747                              DAG.getConstant(0x80008000, SL, MVT::i32));
4748     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4749     return;
4750   }
4751   case ISD::FABS: {
4752     if (N->getValueType(0) != MVT::v2f16)
4753       break;
4754 
4755     SDLoc SL(N);
4756     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4757 
4758     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4759                              BC,
4760                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4761     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4762     return;
4763   }
4764   default:
4765     break;
4766   }
4767 }
4768 
4769 /// Helper function for LowerBRCOND
4770 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4771 
4772   SDNode *Parent = Value.getNode();
4773   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4774        I != E; ++I) {
4775 
4776     if (I.getUse().get() != Value)
4777       continue;
4778 
4779     if (I->getOpcode() == Opcode)
4780       return *I;
4781   }
4782   return nullptr;
4783 }
4784 
4785 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4786   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4787     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4788     case Intrinsic::amdgcn_if:
4789       return AMDGPUISD::IF;
4790     case Intrinsic::amdgcn_else:
4791       return AMDGPUISD::ELSE;
4792     case Intrinsic::amdgcn_loop:
4793       return AMDGPUISD::LOOP;
4794     case Intrinsic::amdgcn_end_cf:
4795       llvm_unreachable("should not occur");
4796     default:
4797       return 0;
4798     }
4799   }
4800 
4801   // break, if_break, else_break are all only used as inputs to loop, not
4802   // directly as branch conditions.
4803   return 0;
4804 }
4805 
4806 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4807   const Triple &TT = getTargetMachine().getTargetTriple();
4808   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4809           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4810          AMDGPU::shouldEmitConstantsToTextSection(TT);
4811 }
4812 
4813 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4814   // FIXME: Either avoid relying on address space here or change the default
4815   // address space for functions to avoid the explicit check.
4816   return (GV->getValueType()->isFunctionTy() ||
4817           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4818          !shouldEmitFixup(GV) &&
4819          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4820 }
4821 
4822 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4823   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4824 }
4825 
4826 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4827   if (!GV->hasExternalLinkage())
4828     return true;
4829 
4830   const auto OS = getTargetMachine().getTargetTriple().getOS();
4831   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4832 }
4833 
4834 /// This transforms the control flow intrinsics to get the branch destination as
4835 /// last parameter, also switches branch target with BR if the need arise
4836 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4837                                       SelectionDAG &DAG) const {
4838   SDLoc DL(BRCOND);
4839 
4840   SDNode *Intr = BRCOND.getOperand(1).getNode();
4841   SDValue Target = BRCOND.getOperand(2);
4842   SDNode *BR = nullptr;
4843   SDNode *SetCC = nullptr;
4844 
4845   if (Intr->getOpcode() == ISD::SETCC) {
4846     // As long as we negate the condition everything is fine
4847     SetCC = Intr;
4848     Intr = SetCC->getOperand(0).getNode();
4849 
4850   } else {
4851     // Get the target from BR if we don't negate the condition
4852     BR = findUser(BRCOND, ISD::BR);
4853     assert(BR && "brcond missing unconditional branch user");
4854     Target = BR->getOperand(1);
4855   }
4856 
4857   unsigned CFNode = isCFIntrinsic(Intr);
4858   if (CFNode == 0) {
4859     // This is a uniform branch so we don't need to legalize.
4860     return BRCOND;
4861   }
4862 
4863   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4864                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4865 
4866   assert(!SetCC ||
4867         (SetCC->getConstantOperandVal(1) == 1 &&
4868          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4869                                                              ISD::SETNE));
4870 
4871   // operands of the new intrinsic call
4872   SmallVector<SDValue, 4> Ops;
4873   if (HaveChain)
4874     Ops.push_back(BRCOND.getOperand(0));
4875 
4876   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4877   Ops.push_back(Target);
4878 
4879   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4880 
4881   // build the new intrinsic call
4882   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4883 
4884   if (!HaveChain) {
4885     SDValue Ops[] =  {
4886       SDValue(Result, 0),
4887       BRCOND.getOperand(0)
4888     };
4889 
4890     Result = DAG.getMergeValues(Ops, DL).getNode();
4891   }
4892 
4893   if (BR) {
4894     // Give the branch instruction our target
4895     SDValue Ops[] = {
4896       BR->getOperand(0),
4897       BRCOND.getOperand(2)
4898     };
4899     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4900     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4901   }
4902 
4903   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4904 
4905   // Copy the intrinsic results to registers
4906   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4907     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4908     if (!CopyToReg)
4909       continue;
4910 
4911     Chain = DAG.getCopyToReg(
4912       Chain, DL,
4913       CopyToReg->getOperand(1),
4914       SDValue(Result, i - 1),
4915       SDValue());
4916 
4917     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4918   }
4919 
4920   // Remove the old intrinsic from the chain
4921   DAG.ReplaceAllUsesOfValueWith(
4922     SDValue(Intr, Intr->getNumValues() - 1),
4923     Intr->getOperand(0));
4924 
4925   return Chain;
4926 }
4927 
4928 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4929                                           SelectionDAG &DAG) const {
4930   MVT VT = Op.getSimpleValueType();
4931   SDLoc DL(Op);
4932   // Checking the depth
4933   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4934     return DAG.getConstant(0, DL, VT);
4935 
4936   MachineFunction &MF = DAG.getMachineFunction();
4937   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4938   // Check for kernel and shader functions
4939   if (Info->isEntryFunction())
4940     return DAG.getConstant(0, DL, VT);
4941 
4942   MachineFrameInfo &MFI = MF.getFrameInfo();
4943   // There is a call to @llvm.returnaddress in this function
4944   MFI.setReturnAddressIsTaken(true);
4945 
4946   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4947   // Get the return address reg and mark it as an implicit live-in
4948   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4949 
4950   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4951 }
4952 
4953 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4954                                             SDValue Op,
4955                                             const SDLoc &DL,
4956                                             EVT VT) const {
4957   return Op.getValueType().bitsLE(VT) ?
4958       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4959     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4960                 DAG.getTargetConstant(0, DL, MVT::i32));
4961 }
4962 
4963 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4964   assert(Op.getValueType() == MVT::f16 &&
4965          "Do not know how to custom lower FP_ROUND for non-f16 type");
4966 
4967   SDValue Src = Op.getOperand(0);
4968   EVT SrcVT = Src.getValueType();
4969   if (SrcVT != MVT::f64)
4970     return Op;
4971 
4972   SDLoc DL(Op);
4973 
4974   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4975   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4976   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4977 }
4978 
4979 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4980                                                SelectionDAG &DAG) const {
4981   EVT VT = Op.getValueType();
4982   const MachineFunction &MF = DAG.getMachineFunction();
4983   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4984   bool IsIEEEMode = Info->getMode().IEEE;
4985 
4986   // FIXME: Assert during selection that this is only selected for
4987   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4988   // mode functions, but this happens to be OK since it's only done in cases
4989   // where there is known no sNaN.
4990   if (IsIEEEMode)
4991     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4992 
4993   if (VT == MVT::v4f16)
4994     return splitBinaryVectorOp(Op, DAG);
4995   return Op;
4996 }
4997 
4998 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
4999   EVT VT = Op.getValueType();
5000   SDLoc SL(Op);
5001   SDValue LHS = Op.getOperand(0);
5002   SDValue RHS = Op.getOperand(1);
5003   bool isSigned = Op.getOpcode() == ISD::SMULO;
5004 
5005   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5006     const APInt &C = RHSC->getAPIntValue();
5007     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5008     if (C.isPowerOf2()) {
5009       // smulo(x, signed_min) is same as umulo(x, signed_min).
5010       bool UseArithShift = isSigned && !C.isMinSignedValue();
5011       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5012       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5013       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5014           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5015                       SL, VT, Result, ShiftAmt),
5016           LHS, ISD::SETNE);
5017       return DAG.getMergeValues({ Result, Overflow }, SL);
5018     }
5019   }
5020 
5021   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5022   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5023                             SL, VT, LHS, RHS);
5024 
5025   SDValue Sign = isSigned
5026     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5027                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5028     : DAG.getConstant(0, SL, VT);
5029   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5030 
5031   return DAG.getMergeValues({ Result, Overflow }, SL);
5032 }
5033 
5034 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5035   SDLoc SL(Op);
5036   SDValue Chain = Op.getOperand(0);
5037 
5038   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5039       !Subtarget->isTrapHandlerEnabled())
5040     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5041 
5042   MachineFunction &MF = DAG.getMachineFunction();
5043   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5044   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
5045   assert(UserSGPR != AMDGPU::NoRegister);
5046   SDValue QueuePtr = CreateLiveInRegister(
5047     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5048   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5049   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5050                                    QueuePtr, SDValue());
5051   SDValue Ops[] = {
5052     ToReg,
5053     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5054     SGPR01,
5055     ToReg.getValue(1)
5056   };
5057   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5058 }
5059 
5060 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5061   SDLoc SL(Op);
5062   SDValue Chain = Op.getOperand(0);
5063   MachineFunction &MF = DAG.getMachineFunction();
5064 
5065   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5066       !Subtarget->isTrapHandlerEnabled()) {
5067     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5068                                      "debugtrap handler not supported",
5069                                      Op.getDebugLoc(),
5070                                      DS_Warning);
5071     LLVMContext &Ctx = MF.getFunction().getContext();
5072     Ctx.diagnose(NoTrap);
5073     return Chain;
5074   }
5075 
5076   SDValue Ops[] = {
5077     Chain,
5078     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5079   };
5080   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5081 }
5082 
5083 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5084                                              SelectionDAG &DAG) const {
5085   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5086   if (Subtarget->hasApertureRegs()) {
5087     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5088         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5089         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5090     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5091         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5092         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5093     unsigned Encoding =
5094         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5095         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5096         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5097 
5098     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5099     SDValue ApertureReg = SDValue(
5100         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5101     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5102     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5103   }
5104 
5105   MachineFunction &MF = DAG.getMachineFunction();
5106   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5107   Register UserSGPR = Info->getQueuePtrUserSGPR();
5108   assert(UserSGPR != AMDGPU::NoRegister);
5109 
5110   SDValue QueuePtr = CreateLiveInRegister(
5111     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5112 
5113   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5114   // private_segment_aperture_base_hi.
5115   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5116 
5117   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
5118 
5119   // TODO: Use custom target PseudoSourceValue.
5120   // TODO: We should use the value from the IR intrinsic call, but it might not
5121   // be available and how do we get it?
5122   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5123   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5124                      MinAlign(64, StructOffset),
5125                      MachineMemOperand::MODereferenceable |
5126                          MachineMemOperand::MOInvariant);
5127 }
5128 
5129 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5130                                              SelectionDAG &DAG) const {
5131   SDLoc SL(Op);
5132   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5133 
5134   SDValue Src = ASC->getOperand(0);
5135   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5136 
5137   const AMDGPUTargetMachine &TM =
5138     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5139 
5140   // flat -> local/private
5141   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5142     unsigned DestAS = ASC->getDestAddressSpace();
5143 
5144     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5145         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5146       unsigned NullVal = TM.getNullPointerValue(DestAS);
5147       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5148       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5149       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5150 
5151       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5152                          NonNull, Ptr, SegmentNullPtr);
5153     }
5154   }
5155 
5156   // local/private -> flat
5157   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5158     unsigned SrcAS = ASC->getSrcAddressSpace();
5159 
5160     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5161         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5162       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5163       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5164 
5165       SDValue NonNull
5166         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5167 
5168       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5169       SDValue CvtPtr
5170         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5171 
5172       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5173                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5174                          FlatNullPtr);
5175     }
5176   }
5177 
5178   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5179       Src.getValueType() == MVT::i64)
5180     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5181 
5182   // global <-> flat are no-ops and never emitted.
5183 
5184   const MachineFunction &MF = DAG.getMachineFunction();
5185   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5186     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5187   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5188 
5189   return DAG.getUNDEF(ASC->getValueType(0));
5190 }
5191 
5192 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5193 // the small vector and inserting them into the big vector. That is better than
5194 // the default expansion of doing it via a stack slot. Even though the use of
5195 // the stack slot would be optimized away afterwards, the stack slot itself
5196 // remains.
5197 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5198                                                 SelectionDAG &DAG) const {
5199   SDValue Vec = Op.getOperand(0);
5200   SDValue Ins = Op.getOperand(1);
5201   SDValue Idx = Op.getOperand(2);
5202   EVT VecVT = Vec.getValueType();
5203   EVT InsVT = Ins.getValueType();
5204   EVT EltVT = VecVT.getVectorElementType();
5205   unsigned InsNumElts = InsVT.getVectorNumElements();
5206   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5207   SDLoc SL(Op);
5208 
5209   for (unsigned I = 0; I != InsNumElts; ++I) {
5210     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5211                               DAG.getConstant(I, SL, MVT::i32));
5212     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5213                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5214   }
5215   return Vec;
5216 }
5217 
5218 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5219                                                  SelectionDAG &DAG) const {
5220   SDValue Vec = Op.getOperand(0);
5221   SDValue InsVal = Op.getOperand(1);
5222   SDValue Idx = Op.getOperand(2);
5223   EVT VecVT = Vec.getValueType();
5224   EVT EltVT = VecVT.getVectorElementType();
5225   unsigned VecSize = VecVT.getSizeInBits();
5226   unsigned EltSize = EltVT.getSizeInBits();
5227 
5228 
5229   assert(VecSize <= 64);
5230 
5231   unsigned NumElts = VecVT.getVectorNumElements();
5232   SDLoc SL(Op);
5233   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5234 
5235   if (NumElts == 4 && EltSize == 16 && KIdx) {
5236     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5237 
5238     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5239                                  DAG.getConstant(0, SL, MVT::i32));
5240     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5241                                  DAG.getConstant(1, SL, MVT::i32));
5242 
5243     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5244     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5245 
5246     unsigned Idx = KIdx->getZExtValue();
5247     bool InsertLo = Idx < 2;
5248     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5249       InsertLo ? LoVec : HiVec,
5250       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5251       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5252 
5253     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5254 
5255     SDValue Concat = InsertLo ?
5256       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5257       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5258 
5259     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5260   }
5261 
5262   if (isa<ConstantSDNode>(Idx))
5263     return SDValue();
5264 
5265   MVT IntVT = MVT::getIntegerVT(VecSize);
5266 
5267   // Avoid stack access for dynamic indexing.
5268   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5269 
5270   // Create a congruent vector with the target value in each element so that
5271   // the required element can be masked and ORed into the target vector.
5272   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5273                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5274 
5275   assert(isPowerOf2_32(EltSize));
5276   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5277 
5278   // Convert vector index to bit-index.
5279   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5280 
5281   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5282   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5283                             DAG.getConstant(0xffff, SL, IntVT),
5284                             ScaledIdx);
5285 
5286   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5287   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5288                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5289 
5290   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5291   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5292 }
5293 
5294 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5295                                                   SelectionDAG &DAG) const {
5296   SDLoc SL(Op);
5297 
5298   EVT ResultVT = Op.getValueType();
5299   SDValue Vec = Op.getOperand(0);
5300   SDValue Idx = Op.getOperand(1);
5301   EVT VecVT = Vec.getValueType();
5302   unsigned VecSize = VecVT.getSizeInBits();
5303   EVT EltVT = VecVT.getVectorElementType();
5304   assert(VecSize <= 64);
5305 
5306   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5307 
5308   // Make sure we do any optimizations that will make it easier to fold
5309   // source modifiers before obscuring it with bit operations.
5310 
5311   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5312   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5313     return Combined;
5314 
5315   unsigned EltSize = EltVT.getSizeInBits();
5316   assert(isPowerOf2_32(EltSize));
5317 
5318   MVT IntVT = MVT::getIntegerVT(VecSize);
5319   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5320 
5321   // Convert vector index to bit-index (* EltSize)
5322   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5323 
5324   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5325   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5326 
5327   if (ResultVT == MVT::f16) {
5328     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5329     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5330   }
5331 
5332   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5333 }
5334 
5335 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5336   assert(Elt % 2 == 0);
5337   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5338 }
5339 
5340 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5341                                               SelectionDAG &DAG) const {
5342   SDLoc SL(Op);
5343   EVT ResultVT = Op.getValueType();
5344   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5345 
5346   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5347   EVT EltVT = PackVT.getVectorElementType();
5348   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5349 
5350   // vector_shuffle <0,1,6,7> lhs, rhs
5351   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5352   //
5353   // vector_shuffle <6,7,2,3> lhs, rhs
5354   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5355   //
5356   // vector_shuffle <6,7,0,1> lhs, rhs
5357   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5358 
5359   // Avoid scalarizing when both halves are reading from consecutive elements.
5360   SmallVector<SDValue, 4> Pieces;
5361   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5362     if (elementPairIsContiguous(SVN->getMask(), I)) {
5363       const int Idx = SVN->getMaskElt(I);
5364       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5365       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5366       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5367                                     PackVT, SVN->getOperand(VecIdx),
5368                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5369       Pieces.push_back(SubVec);
5370     } else {
5371       const int Idx0 = SVN->getMaskElt(I);
5372       const int Idx1 = SVN->getMaskElt(I + 1);
5373       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5374       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5375       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5376       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5377 
5378       SDValue Vec0 = SVN->getOperand(VecIdx0);
5379       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5380                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5381 
5382       SDValue Vec1 = SVN->getOperand(VecIdx1);
5383       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5384                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5385       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5386     }
5387   }
5388 
5389   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5390 }
5391 
5392 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5393                                             SelectionDAG &DAG) const {
5394   SDLoc SL(Op);
5395   EVT VT = Op.getValueType();
5396 
5397   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5398     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5399 
5400     // Turn into pair of packed build_vectors.
5401     // TODO: Special case for constants that can be materialized with s_mov_b64.
5402     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5403                                     { Op.getOperand(0), Op.getOperand(1) });
5404     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5405                                     { Op.getOperand(2), Op.getOperand(3) });
5406 
5407     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5408     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5409 
5410     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5411     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5412   }
5413 
5414   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5415   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5416 
5417   SDValue Lo = Op.getOperand(0);
5418   SDValue Hi = Op.getOperand(1);
5419 
5420   // Avoid adding defined bits with the zero_extend.
5421   if (Hi.isUndef()) {
5422     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5423     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5424     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5425   }
5426 
5427   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5428   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5429 
5430   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5431                               DAG.getConstant(16, SL, MVT::i32));
5432   if (Lo.isUndef())
5433     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5434 
5435   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5436   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5437 
5438   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5439   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5440 }
5441 
5442 bool
5443 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5444   // We can fold offsets for anything that doesn't require a GOT relocation.
5445   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5446           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5447           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5448          !shouldEmitGOTReloc(GA->getGlobal());
5449 }
5450 
5451 static SDValue
5452 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5453                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5454                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5455   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5456   // lowered to the following code sequence:
5457   //
5458   // For constant address space:
5459   //   s_getpc_b64 s[0:1]
5460   //   s_add_u32 s0, s0, $symbol
5461   //   s_addc_u32 s1, s1, 0
5462   //
5463   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5464   //   a fixup or relocation is emitted to replace $symbol with a literal
5465   //   constant, which is a pc-relative offset from the encoding of the $symbol
5466   //   operand to the global variable.
5467   //
5468   // For global address space:
5469   //   s_getpc_b64 s[0:1]
5470   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5471   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5472   //
5473   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5474   //   fixups or relocations are emitted to replace $symbol@*@lo and
5475   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5476   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5477   //   operand to the global variable.
5478   //
5479   // What we want here is an offset from the value returned by s_getpc
5480   // (which is the address of the s_add_u32 instruction) to the global
5481   // variable, but since the encoding of $symbol starts 4 bytes after the start
5482   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5483   // small. This requires us to add 4 to the global variable offset in order to
5484   // compute the correct address.
5485   SDValue PtrLo =
5486       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5487   SDValue PtrHi;
5488   if (GAFlags == SIInstrInfo::MO_NONE) {
5489     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5490   } else {
5491     PtrHi =
5492         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5493   }
5494   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5495 }
5496 
5497 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5498                                              SDValue Op,
5499                                              SelectionDAG &DAG) const {
5500   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5501   const GlobalValue *GV = GSD->getGlobal();
5502   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5503        shouldUseLDSConstAddress(GV)) ||
5504       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5505       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5506     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5507 
5508   SDLoc DL(GSD);
5509   EVT PtrVT = Op.getValueType();
5510 
5511   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5512     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5513                                             SIInstrInfo::MO_ABS32_LO);
5514     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5515   }
5516 
5517   if (shouldEmitFixup(GV))
5518     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5519   else if (shouldEmitPCReloc(GV))
5520     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5521                                    SIInstrInfo::MO_REL32);
5522 
5523   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5524                                             SIInstrInfo::MO_GOTPCREL32);
5525 
5526   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5527   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5528   const DataLayout &DataLayout = DAG.getDataLayout();
5529   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5530   MachinePointerInfo PtrInfo
5531     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5532 
5533   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5534                      MachineMemOperand::MODereferenceable |
5535                          MachineMemOperand::MOInvariant);
5536 }
5537 
5538 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5539                                    const SDLoc &DL, SDValue V) const {
5540   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5541   // the destination register.
5542   //
5543   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5544   // so we will end up with redundant moves to m0.
5545   //
5546   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5547 
5548   // A Null SDValue creates a glue result.
5549   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5550                                   V, Chain);
5551   return SDValue(M0, 0);
5552 }
5553 
5554 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5555                                                  SDValue Op,
5556                                                  MVT VT,
5557                                                  unsigned Offset) const {
5558   SDLoc SL(Op);
5559   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5560                                            DAG.getEntryNode(), Offset, 4, false);
5561   // The local size values will have the hi 16-bits as zero.
5562   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5563                      DAG.getValueType(VT));
5564 }
5565 
5566 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5567                                         EVT VT) {
5568   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5569                                       "non-hsa intrinsic with hsa target",
5570                                       DL.getDebugLoc());
5571   DAG.getContext()->diagnose(BadIntrin);
5572   return DAG.getUNDEF(VT);
5573 }
5574 
5575 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5576                                          EVT VT) {
5577   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5578                                       "intrinsic not supported on subtarget",
5579                                       DL.getDebugLoc());
5580   DAG.getContext()->diagnose(BadIntrin);
5581   return DAG.getUNDEF(VT);
5582 }
5583 
5584 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5585                                     ArrayRef<SDValue> Elts) {
5586   assert(!Elts.empty());
5587   MVT Type;
5588   unsigned NumElts;
5589 
5590   if (Elts.size() == 1) {
5591     Type = MVT::f32;
5592     NumElts = 1;
5593   } else if (Elts.size() == 2) {
5594     Type = MVT::v2f32;
5595     NumElts = 2;
5596   } else if (Elts.size() == 3) {
5597     Type = MVT::v3f32;
5598     NumElts = 3;
5599   } else if (Elts.size() <= 4) {
5600     Type = MVT::v4f32;
5601     NumElts = 4;
5602   } else if (Elts.size() <= 8) {
5603     Type = MVT::v8f32;
5604     NumElts = 8;
5605   } else {
5606     assert(Elts.size() <= 16);
5607     Type = MVT::v16f32;
5608     NumElts = 16;
5609   }
5610 
5611   SmallVector<SDValue, 16> VecElts(NumElts);
5612   for (unsigned i = 0; i < Elts.size(); ++i) {
5613     SDValue Elt = Elts[i];
5614     if (Elt.getValueType() != MVT::f32)
5615       Elt = DAG.getBitcast(MVT::f32, Elt);
5616     VecElts[i] = Elt;
5617   }
5618   for (unsigned i = Elts.size(); i < NumElts; ++i)
5619     VecElts[i] = DAG.getUNDEF(MVT::f32);
5620 
5621   if (NumElts == 1)
5622     return VecElts[0];
5623   return DAG.getBuildVector(Type, DL, VecElts);
5624 }
5625 
5626 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5627                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5628   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5629 
5630   uint64_t Value = CachePolicyConst->getZExtValue();
5631   SDLoc DL(CachePolicy);
5632   if (GLC) {
5633     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5634     Value &= ~(uint64_t)0x1;
5635   }
5636   if (SLC) {
5637     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5638     Value &= ~(uint64_t)0x2;
5639   }
5640   if (DLC) {
5641     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5642     Value &= ~(uint64_t)0x4;
5643   }
5644 
5645   return Value == 0;
5646 }
5647 
5648 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5649                               SDValue Src, int ExtraElts) {
5650   EVT SrcVT = Src.getValueType();
5651 
5652   SmallVector<SDValue, 8> Elts;
5653 
5654   if (SrcVT.isVector())
5655     DAG.ExtractVectorElements(Src, Elts);
5656   else
5657     Elts.push_back(Src);
5658 
5659   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5660   while (ExtraElts--)
5661     Elts.push_back(Undef);
5662 
5663   return DAG.getBuildVector(CastVT, DL, Elts);
5664 }
5665 
5666 // Re-construct the required return value for a image load intrinsic.
5667 // This is more complicated due to the optional use TexFailCtrl which means the required
5668 // return type is an aggregate
5669 static SDValue constructRetValue(SelectionDAG &DAG,
5670                                  MachineSDNode *Result,
5671                                  ArrayRef<EVT> ResultTypes,
5672                                  bool IsTexFail, bool Unpacked, bool IsD16,
5673                                  int DMaskPop, int NumVDataDwords,
5674                                  const SDLoc &DL, LLVMContext &Context) {
5675   // Determine the required return type. This is the same regardless of IsTexFail flag
5676   EVT ReqRetVT = ResultTypes[0];
5677   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5678   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5679     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5680 
5681   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5682     DMaskPop : (DMaskPop + 1) / 2;
5683 
5684   MVT DataDwordVT = NumDataDwords == 1 ?
5685     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5686 
5687   MVT MaskPopVT = MaskPopDwords == 1 ?
5688     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5689 
5690   SDValue Data(Result, 0);
5691   SDValue TexFail;
5692 
5693   if (IsTexFail) {
5694     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5695     if (MaskPopVT.isVector()) {
5696       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5697                          SDValue(Result, 0), ZeroIdx);
5698     } else {
5699       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5700                          SDValue(Result, 0), ZeroIdx);
5701     }
5702 
5703     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5704                           SDValue(Result, 0),
5705                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5706   }
5707 
5708   if (DataDwordVT.isVector())
5709     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5710                           NumDataDwords - MaskPopDwords);
5711 
5712   if (IsD16)
5713     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5714 
5715   if (!ReqRetVT.isVector())
5716     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5717 
5718   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5719 
5720   if (TexFail)
5721     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5722 
5723   if (Result->getNumValues() == 1)
5724     return Data;
5725 
5726   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5727 }
5728 
5729 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5730                          SDValue *LWE, bool &IsTexFail) {
5731   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5732 
5733   uint64_t Value = TexFailCtrlConst->getZExtValue();
5734   if (Value) {
5735     IsTexFail = true;
5736   }
5737 
5738   SDLoc DL(TexFailCtrlConst);
5739   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5740   Value &= ~(uint64_t)0x1;
5741   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5742   Value &= ~(uint64_t)0x2;
5743 
5744   return Value == 0;
5745 }
5746 
5747 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5748                                         MVT PackVectorVT,
5749                                         SmallVectorImpl<SDValue> &PackedAddrs,
5750                                         unsigned DimIdx, unsigned EndIdx,
5751                                         unsigned NumGradients) {
5752   SDLoc DL(Op);
5753   for (unsigned I = DimIdx; I < EndIdx; I++) {
5754     SDValue Addr = Op.getOperand(I);
5755 
5756     // Gradients are packed with undef for each coordinate.
5757     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5758     // 1D: undef,dx/dh; undef,dx/dv
5759     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5760     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5761     if (((I + 1) >= EndIdx) ||
5762         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5763                                          I == DimIdx + NumGradients - 1))) {
5764       if (Addr.getValueType() != MVT::i16)
5765         Addr = DAG.getBitcast(MVT::i16, Addr);
5766       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5767     } else {
5768       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5769       I++;
5770     }
5771     Addr = DAG.getBitcast(MVT::f32, Addr);
5772     PackedAddrs.push_back(Addr);
5773   }
5774 }
5775 
5776 SDValue SITargetLowering::lowerImage(SDValue Op,
5777                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5778                                      SelectionDAG &DAG) const {
5779   SDLoc DL(Op);
5780   MachineFunction &MF = DAG.getMachineFunction();
5781   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5782   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5783       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5784   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5785   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5786       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5787   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5788       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5789   unsigned IntrOpcode = Intr->BaseOpcode;
5790   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5791 
5792   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5793   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5794   bool IsD16 = false;
5795   bool IsG16 = false;
5796   bool IsA16 = false;
5797   SDValue VData;
5798   int NumVDataDwords;
5799   bool AdjustRetType = false;
5800 
5801   unsigned AddrIdx; // Index of first address argument
5802   unsigned DMask;
5803   unsigned DMaskLanes = 0;
5804 
5805   if (BaseOpcode->Atomic) {
5806     VData = Op.getOperand(2);
5807 
5808     bool Is64Bit = VData.getValueType() == MVT::i64;
5809     if (BaseOpcode->AtomicX2) {
5810       SDValue VData2 = Op.getOperand(3);
5811       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5812                                  {VData, VData2});
5813       if (Is64Bit)
5814         VData = DAG.getBitcast(MVT::v4i32, VData);
5815 
5816       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5817       DMask = Is64Bit ? 0xf : 0x3;
5818       NumVDataDwords = Is64Bit ? 4 : 2;
5819       AddrIdx = 4;
5820     } else {
5821       DMask = Is64Bit ? 0x3 : 0x1;
5822       NumVDataDwords = Is64Bit ? 2 : 1;
5823       AddrIdx = 3;
5824     }
5825   } else {
5826     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5827     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5828     DMask = DMaskConst->getZExtValue();
5829     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5830 
5831     if (BaseOpcode->Store) {
5832       VData = Op.getOperand(2);
5833 
5834       MVT StoreVT = VData.getSimpleValueType();
5835       if (StoreVT.getScalarType() == MVT::f16) {
5836         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5837           return Op; // D16 is unsupported for this instruction
5838 
5839         IsD16 = true;
5840         VData = handleD16VData(VData, DAG);
5841       }
5842 
5843       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5844     } else {
5845       // Work out the num dwords based on the dmask popcount and underlying type
5846       // and whether packing is supported.
5847       MVT LoadVT = ResultTypes[0].getSimpleVT();
5848       if (LoadVT.getScalarType() == MVT::f16) {
5849         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5850           return Op; // D16 is unsupported for this instruction
5851 
5852         IsD16 = true;
5853       }
5854 
5855       // Confirm that the return type is large enough for the dmask specified
5856       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5857           (!LoadVT.isVector() && DMaskLanes > 1))
5858           return Op;
5859 
5860       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5861         NumVDataDwords = (DMaskLanes + 1) / 2;
5862       else
5863         NumVDataDwords = DMaskLanes;
5864 
5865       AdjustRetType = true;
5866     }
5867 
5868     AddrIdx = DMaskIdx + 1;
5869   }
5870 
5871   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5872   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5873   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5874   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5875                        NumCoords + NumLCM;
5876   unsigned NumMIVAddrs = NumVAddrs;
5877 
5878   SmallVector<SDValue, 4> VAddrs;
5879 
5880   // Optimize _L to _LZ when _L is zero
5881   if (LZMappingInfo) {
5882     if (auto ConstantLod =
5883          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5884       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5885         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5886         NumMIVAddrs--;               // remove 'lod'
5887       }
5888     }
5889   }
5890 
5891   // Optimize _mip away, when 'lod' is zero
5892   if (MIPMappingInfo) {
5893     if (auto ConstantLod =
5894          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5895       if (ConstantLod->isNullValue()) {
5896         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5897         NumMIVAddrs--;               // remove 'lod'
5898       }
5899     }
5900   }
5901 
5902   // Push back extra arguments.
5903   for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++)
5904     VAddrs.push_back(Op.getOperand(AddrIdx + I));
5905 
5906   // Check for 16 bit addresses or derivatives and pack if true.
5907   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5908   unsigned CoordIdx = DimIdx + NumGradients;
5909   unsigned CoordsEnd = AddrIdx + NumMIVAddrs;
5910 
5911   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5912   MVT VAddrScalarVT = VAddrVT.getScalarType();
5913   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5914   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5915 
5916   VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType();
5917   VAddrScalarVT = VAddrVT.getScalarType();
5918   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5919   if (IsA16 || IsG16) {
5920     if (IsA16) {
5921       if (!ST->hasA16()) {
5922         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5923                              "support 16 bit addresses\n");
5924         return Op;
5925       }
5926       if (!IsG16) {
5927         LLVM_DEBUG(
5928             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
5929                       "need 16 bit derivatives but got 32 bit derivatives\n");
5930         return Op;
5931       }
5932     } else if (!ST->hasG16()) {
5933       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5934                            "support 16 bit derivatives\n");
5935       return Op;
5936     }
5937 
5938     if (BaseOpcode->Gradients && !IsA16) {
5939       if (!ST->hasG16()) {
5940         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5941                              "support 16 bit derivatives\n");
5942         return Op;
5943       }
5944       // Activate g16
5945       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
5946           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
5947       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
5948     }
5949 
5950     // Don't compress addresses for G16
5951     const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx;
5952     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx,
5953                                 PackEndIdx, NumGradients);
5954 
5955     if (!IsA16) {
5956       // Add uncompressed address
5957       for (unsigned I = CoordIdx; I < CoordsEnd; I++)
5958         VAddrs.push_back(Op.getOperand(I));
5959     }
5960   } else {
5961     for (unsigned I = DimIdx; I < CoordsEnd; I++)
5962       VAddrs.push_back(Op.getOperand(I));
5963   }
5964 
5965   // If the register allocator cannot place the address registers contiguously
5966   // without introducing moves, then using the non-sequential address encoding
5967   // is always preferable, since it saves VALU instructions and is usually a
5968   // wash in terms of code size or even better.
5969   //
5970   // However, we currently have no way of hinting to the register allocator that
5971   // MIMG addresses should be placed contiguously when it is possible to do so,
5972   // so force non-NSA for the common 2-address case as a heuristic.
5973   //
5974   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5975   // allocation when possible.
5976   bool UseNSA =
5977       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5978   SDValue VAddr;
5979   if (!UseNSA)
5980     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5981 
5982   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5983   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5984   unsigned CtrlIdx; // Index of texfailctrl argument
5985   SDValue Unorm;
5986   if (!BaseOpcode->Sampler) {
5987     Unorm = True;
5988     CtrlIdx = AddrIdx + NumVAddrs + 1;
5989   } else {
5990     auto UnormConst =
5991         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5992 
5993     Unorm = UnormConst->getZExtValue() ? True : False;
5994     CtrlIdx = AddrIdx + NumVAddrs + 3;
5995   }
5996 
5997   SDValue TFE;
5998   SDValue LWE;
5999   SDValue TexFail = Op.getOperand(CtrlIdx);
6000   bool IsTexFail = false;
6001   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6002     return Op;
6003 
6004   if (IsTexFail) {
6005     if (!DMaskLanes) {
6006       // Expecting to get an error flag since TFC is on - and dmask is 0
6007       // Force dmask to be at least 1 otherwise the instruction will fail
6008       DMask = 0x1;
6009       DMaskLanes = 1;
6010       NumVDataDwords = 1;
6011     }
6012     NumVDataDwords += 1;
6013     AdjustRetType = true;
6014   }
6015 
6016   // Has something earlier tagged that the return type needs adjusting
6017   // This happens if the instruction is a load or has set TexFailCtrl flags
6018   if (AdjustRetType) {
6019     // NumVDataDwords reflects the true number of dwords required in the return type
6020     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6021       // This is a no-op load. This can be eliminated
6022       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6023       if (isa<MemSDNode>(Op))
6024         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6025       return Undef;
6026     }
6027 
6028     EVT NewVT = NumVDataDwords > 1 ?
6029                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6030                 : MVT::i32;
6031 
6032     ResultTypes[0] = NewVT;
6033     if (ResultTypes.size() == 3) {
6034       // Original result was aggregate type used for TexFailCtrl results
6035       // The actual instruction returns as a vector type which has now been
6036       // created. Remove the aggregate result.
6037       ResultTypes.erase(&ResultTypes[1]);
6038     }
6039   }
6040 
6041   SDValue GLC;
6042   SDValue SLC;
6043   SDValue DLC;
6044   if (BaseOpcode->Atomic) {
6045     GLC = True; // TODO no-return optimization
6046     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
6047                           IsGFX10 ? &DLC : nullptr))
6048       return Op;
6049   } else {
6050     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
6051                           IsGFX10 ? &DLC : nullptr))
6052       return Op;
6053   }
6054 
6055   SmallVector<SDValue, 26> Ops;
6056   if (BaseOpcode->Store || BaseOpcode->Atomic)
6057     Ops.push_back(VData); // vdata
6058   if (UseNSA) {
6059     for (const SDValue &Addr : VAddrs)
6060       Ops.push_back(Addr);
6061   } else {
6062     Ops.push_back(VAddr);
6063   }
6064   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
6065   if (BaseOpcode->Sampler)
6066     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
6067   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6068   if (IsGFX10)
6069     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6070   Ops.push_back(Unorm);
6071   if (IsGFX10)
6072     Ops.push_back(DLC);
6073   Ops.push_back(GLC);
6074   Ops.push_back(SLC);
6075   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6076                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6077   if (IsGFX10)
6078     Ops.push_back(IsA16 ? True : False);
6079   Ops.push_back(TFE);
6080   Ops.push_back(LWE);
6081   if (!IsGFX10)
6082     Ops.push_back(DimInfo->DA ? True : False);
6083   if (BaseOpcode->HasD16)
6084     Ops.push_back(IsD16 ? True : False);
6085   if (isa<MemSDNode>(Op))
6086     Ops.push_back(Op.getOperand(0)); // chain
6087 
6088   int NumVAddrDwords =
6089       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6090   int Opcode = -1;
6091 
6092   if (IsGFX10) {
6093     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6094                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6095                                           : AMDGPU::MIMGEncGfx10Default,
6096                                    NumVDataDwords, NumVAddrDwords);
6097   } else {
6098     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6099       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6100                                      NumVDataDwords, NumVAddrDwords);
6101     if (Opcode == -1)
6102       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6103                                      NumVDataDwords, NumVAddrDwords);
6104   }
6105   assert(Opcode != -1);
6106 
6107   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6108   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6109     MachineMemOperand *MemRef = MemOp->getMemOperand();
6110     DAG.setNodeMemRefs(NewNode, {MemRef});
6111   }
6112 
6113   if (BaseOpcode->AtomicX2) {
6114     SmallVector<SDValue, 1> Elt;
6115     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6116     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6117   } else if (!BaseOpcode->Store) {
6118     return constructRetValue(DAG, NewNode,
6119                              OrigResultTypes, IsTexFail,
6120                              Subtarget->hasUnpackedD16VMem(), IsD16,
6121                              DMaskLanes, NumVDataDwords, DL,
6122                              *DAG.getContext());
6123   }
6124 
6125   return SDValue(NewNode, 0);
6126 }
6127 
6128 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6129                                        SDValue Offset, SDValue CachePolicy,
6130                                        SelectionDAG &DAG) const {
6131   MachineFunction &MF = DAG.getMachineFunction();
6132 
6133   const DataLayout &DataLayout = DAG.getDataLayout();
6134   Align Alignment =
6135       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6136 
6137   MachineMemOperand *MMO = MF.getMachineMemOperand(
6138       MachinePointerInfo(),
6139       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6140           MachineMemOperand::MOInvariant,
6141       VT.getStoreSize(), Alignment);
6142 
6143   if (!Offset->isDivergent()) {
6144     SDValue Ops[] = {
6145         Rsrc,
6146         Offset, // Offset
6147         CachePolicy
6148     };
6149 
6150     // Widen vec3 load to vec4.
6151     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6152       EVT WidenedVT =
6153           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6154       auto WidenedOp = DAG.getMemIntrinsicNode(
6155           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6156           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6157       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6158                                    DAG.getVectorIdxConstant(0, DL));
6159       return Subvector;
6160     }
6161 
6162     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6163                                    DAG.getVTList(VT), Ops, VT, MMO);
6164   }
6165 
6166   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6167   // assume that the buffer is unswizzled.
6168   SmallVector<SDValue, 4> Loads;
6169   unsigned NumLoads = 1;
6170   MVT LoadVT = VT.getSimpleVT();
6171   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6172   assert((LoadVT.getScalarType() == MVT::i32 ||
6173           LoadVT.getScalarType() == MVT::f32));
6174 
6175   if (NumElts == 8 || NumElts == 16) {
6176     NumLoads = NumElts / 4;
6177     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6178   }
6179 
6180   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6181   SDValue Ops[] = {
6182       DAG.getEntryNode(),                               // Chain
6183       Rsrc,                                             // rsrc
6184       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6185       {},                                               // voffset
6186       {},                                               // soffset
6187       {},                                               // offset
6188       CachePolicy,                                      // cachepolicy
6189       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6190   };
6191 
6192   // Use the alignment to ensure that the required offsets will fit into the
6193   // immediate offsets.
6194   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
6195 
6196   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6197   for (unsigned i = 0; i < NumLoads; ++i) {
6198     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6199     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6200                                         LoadVT, MMO, DAG));
6201   }
6202 
6203   if (NumElts == 8 || NumElts == 16)
6204     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6205 
6206   return Loads[0];
6207 }
6208 
6209 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6210                                                   SelectionDAG &DAG) const {
6211   MachineFunction &MF = DAG.getMachineFunction();
6212   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6213 
6214   EVT VT = Op.getValueType();
6215   SDLoc DL(Op);
6216   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6217 
6218   // TODO: Should this propagate fast-math-flags?
6219 
6220   switch (IntrinsicID) {
6221   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6222     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6223       return emitNonHSAIntrinsicError(DAG, DL, VT);
6224     return getPreloadedValue(DAG, *MFI, VT,
6225                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6226   }
6227   case Intrinsic::amdgcn_dispatch_ptr:
6228   case Intrinsic::amdgcn_queue_ptr: {
6229     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6230       DiagnosticInfoUnsupported BadIntrin(
6231           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6232           DL.getDebugLoc());
6233       DAG.getContext()->diagnose(BadIntrin);
6234       return DAG.getUNDEF(VT);
6235     }
6236 
6237     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6238       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6239     return getPreloadedValue(DAG, *MFI, VT, RegID);
6240   }
6241   case Intrinsic::amdgcn_implicitarg_ptr: {
6242     if (MFI->isEntryFunction())
6243       return getImplicitArgPtr(DAG, DL);
6244     return getPreloadedValue(DAG, *MFI, VT,
6245                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6246   }
6247   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6248     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6249       // This only makes sense to call in a kernel, so just lower to null.
6250       return DAG.getConstant(0, DL, VT);
6251     }
6252 
6253     return getPreloadedValue(DAG, *MFI, VT,
6254                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6255   }
6256   case Intrinsic::amdgcn_dispatch_id: {
6257     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6258   }
6259   case Intrinsic::amdgcn_rcp:
6260     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6261   case Intrinsic::amdgcn_rsq:
6262     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6263   case Intrinsic::amdgcn_rsq_legacy:
6264     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6265       return emitRemovedIntrinsicError(DAG, DL, VT);
6266     return SDValue();
6267   case Intrinsic::amdgcn_rcp_legacy:
6268     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6269       return emitRemovedIntrinsicError(DAG, DL, VT);
6270     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6271   case Intrinsic::amdgcn_rsq_clamp: {
6272     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6273       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6274 
6275     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6276     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6277     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6278 
6279     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6280     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6281                               DAG.getConstantFP(Max, DL, VT));
6282     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6283                        DAG.getConstantFP(Min, DL, VT));
6284   }
6285   case Intrinsic::r600_read_ngroups_x:
6286     if (Subtarget->isAmdHsaOS())
6287       return emitNonHSAIntrinsicError(DAG, DL, VT);
6288 
6289     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6290                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6291   case Intrinsic::r600_read_ngroups_y:
6292     if (Subtarget->isAmdHsaOS())
6293       return emitNonHSAIntrinsicError(DAG, DL, VT);
6294 
6295     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6296                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6297   case Intrinsic::r600_read_ngroups_z:
6298     if (Subtarget->isAmdHsaOS())
6299       return emitNonHSAIntrinsicError(DAG, DL, VT);
6300 
6301     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6302                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6303   case Intrinsic::r600_read_global_size_x:
6304     if (Subtarget->isAmdHsaOS())
6305       return emitNonHSAIntrinsicError(DAG, DL, VT);
6306 
6307     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6308                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6309   case Intrinsic::r600_read_global_size_y:
6310     if (Subtarget->isAmdHsaOS())
6311       return emitNonHSAIntrinsicError(DAG, DL, VT);
6312 
6313     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6314                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6315   case Intrinsic::r600_read_global_size_z:
6316     if (Subtarget->isAmdHsaOS())
6317       return emitNonHSAIntrinsicError(DAG, DL, VT);
6318 
6319     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6320                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6321   case Intrinsic::r600_read_local_size_x:
6322     if (Subtarget->isAmdHsaOS())
6323       return emitNonHSAIntrinsicError(DAG, DL, VT);
6324 
6325     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6326                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6327   case Intrinsic::r600_read_local_size_y:
6328     if (Subtarget->isAmdHsaOS())
6329       return emitNonHSAIntrinsicError(DAG, DL, VT);
6330 
6331     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6332                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6333   case Intrinsic::r600_read_local_size_z:
6334     if (Subtarget->isAmdHsaOS())
6335       return emitNonHSAIntrinsicError(DAG, DL, VT);
6336 
6337     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6338                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6339   case Intrinsic::amdgcn_workgroup_id_x:
6340     return getPreloadedValue(DAG, *MFI, VT,
6341                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6342   case Intrinsic::amdgcn_workgroup_id_y:
6343     return getPreloadedValue(DAG, *MFI, VT,
6344                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6345   case Intrinsic::amdgcn_workgroup_id_z:
6346     return getPreloadedValue(DAG, *MFI, VT,
6347                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6348   case Intrinsic::amdgcn_workitem_id_x:
6349     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6350                           SDLoc(DAG.getEntryNode()),
6351                           MFI->getArgInfo().WorkItemIDX);
6352   case Intrinsic::amdgcn_workitem_id_y:
6353     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6354                           SDLoc(DAG.getEntryNode()),
6355                           MFI->getArgInfo().WorkItemIDY);
6356   case Intrinsic::amdgcn_workitem_id_z:
6357     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6358                           SDLoc(DAG.getEntryNode()),
6359                           MFI->getArgInfo().WorkItemIDZ);
6360   case Intrinsic::amdgcn_wavefrontsize:
6361     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6362                            SDLoc(Op), MVT::i32);
6363   case Intrinsic::amdgcn_s_buffer_load: {
6364     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6365     SDValue GLC;
6366     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6367     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6368                           IsGFX10 ? &DLC : nullptr))
6369       return Op;
6370     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6371                         DAG);
6372   }
6373   case Intrinsic::amdgcn_fdiv_fast:
6374     return lowerFDIV_FAST(Op, DAG);
6375   case Intrinsic::amdgcn_sin:
6376     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6377 
6378   case Intrinsic::amdgcn_cos:
6379     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6380 
6381   case Intrinsic::amdgcn_mul_u24:
6382     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6383   case Intrinsic::amdgcn_mul_i24:
6384     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6385 
6386   case Intrinsic::amdgcn_log_clamp: {
6387     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6388       return SDValue();
6389 
6390     DiagnosticInfoUnsupported BadIntrin(
6391       MF.getFunction(), "intrinsic not supported on subtarget",
6392       DL.getDebugLoc());
6393       DAG.getContext()->diagnose(BadIntrin);
6394       return DAG.getUNDEF(VT);
6395   }
6396   case Intrinsic::amdgcn_ldexp:
6397     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6398                        Op.getOperand(1), Op.getOperand(2));
6399 
6400   case Intrinsic::amdgcn_fract:
6401     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6402 
6403   case Intrinsic::amdgcn_class:
6404     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6405                        Op.getOperand(1), Op.getOperand(2));
6406   case Intrinsic::amdgcn_div_fmas:
6407     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6408                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6409                        Op.getOperand(4));
6410 
6411   case Intrinsic::amdgcn_div_fixup:
6412     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6413                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6414 
6415   case Intrinsic::amdgcn_trig_preop:
6416     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
6417                        Op.getOperand(1), Op.getOperand(2));
6418   case Intrinsic::amdgcn_div_scale: {
6419     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6420 
6421     // Translate to the operands expected by the machine instruction. The
6422     // first parameter must be the same as the first instruction.
6423     SDValue Numerator = Op.getOperand(1);
6424     SDValue Denominator = Op.getOperand(2);
6425 
6426     // Note this order is opposite of the machine instruction's operations,
6427     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6428     // intrinsic has the numerator as the first operand to match a normal
6429     // division operation.
6430 
6431     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6432 
6433     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6434                        Denominator, Numerator);
6435   }
6436   case Intrinsic::amdgcn_icmp: {
6437     // There is a Pat that handles this variant, so return it as-is.
6438     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6439         Op.getConstantOperandVal(2) == 0 &&
6440         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6441       return Op;
6442     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6443   }
6444   case Intrinsic::amdgcn_fcmp: {
6445     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6446   }
6447   case Intrinsic::amdgcn_ballot:
6448     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6449   case Intrinsic::amdgcn_fmed3:
6450     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6451                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6452   case Intrinsic::amdgcn_fdot2:
6453     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6454                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6455                        Op.getOperand(4));
6456   case Intrinsic::amdgcn_fmul_legacy:
6457     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6458                        Op.getOperand(1), Op.getOperand(2));
6459   case Intrinsic::amdgcn_sffbh:
6460     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6461   case Intrinsic::amdgcn_sbfe:
6462     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6463                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6464   case Intrinsic::amdgcn_ubfe:
6465     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6466                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6467   case Intrinsic::amdgcn_cvt_pkrtz:
6468   case Intrinsic::amdgcn_cvt_pknorm_i16:
6469   case Intrinsic::amdgcn_cvt_pknorm_u16:
6470   case Intrinsic::amdgcn_cvt_pk_i16:
6471   case Intrinsic::amdgcn_cvt_pk_u16: {
6472     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6473     EVT VT = Op.getValueType();
6474     unsigned Opcode;
6475 
6476     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6477       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6478     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6479       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6480     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6481       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6482     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6483       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6484     else
6485       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6486 
6487     if (isTypeLegal(VT))
6488       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6489 
6490     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6491                                Op.getOperand(1), Op.getOperand(2));
6492     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6493   }
6494   case Intrinsic::amdgcn_fmad_ftz:
6495     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6496                        Op.getOperand(2), Op.getOperand(3));
6497 
6498   case Intrinsic::amdgcn_if_break:
6499     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6500                                       Op->getOperand(1), Op->getOperand(2)), 0);
6501 
6502   case Intrinsic::amdgcn_groupstaticsize: {
6503     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6504     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6505       return Op;
6506 
6507     const Module *M = MF.getFunction().getParent();
6508     const GlobalValue *GV =
6509         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6510     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6511                                             SIInstrInfo::MO_ABS32_LO);
6512     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6513   }
6514   case Intrinsic::amdgcn_is_shared:
6515   case Intrinsic::amdgcn_is_private: {
6516     SDLoc SL(Op);
6517     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6518       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6519     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6520     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6521                                  Op.getOperand(1));
6522 
6523     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6524                                 DAG.getConstant(1, SL, MVT::i32));
6525     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6526   }
6527   case Intrinsic::amdgcn_alignbit:
6528     return DAG.getNode(ISD::FSHR, DL, VT,
6529                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6530   case Intrinsic::amdgcn_reloc_constant: {
6531     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6532     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6533     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6534     auto RelocSymbol = cast<GlobalVariable>(
6535         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6536     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6537                                             SIInstrInfo::MO_ABS32_LO);
6538     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6539   }
6540   default:
6541     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6542             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6543       return lowerImage(Op, ImageDimIntr, DAG);
6544 
6545     return Op;
6546   }
6547 }
6548 
6549 // This function computes an appropriate offset to pass to
6550 // MachineMemOperand::setOffset() based on the offset inputs to
6551 // an intrinsic.  If any of the offsets are non-contstant or
6552 // if VIndex is non-zero then this function returns 0.  Otherwise,
6553 // it returns the sum of VOffset, SOffset, and Offset.
6554 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6555                                       SDValue SOffset,
6556                                       SDValue Offset,
6557                                       SDValue VIndex = SDValue()) {
6558 
6559   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6560       !isa<ConstantSDNode>(Offset))
6561     return 0;
6562 
6563   if (VIndex) {
6564     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6565       return 0;
6566   }
6567 
6568   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6569          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6570          cast<ConstantSDNode>(Offset)->getSExtValue();
6571 }
6572 
6573 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6574   switch (MF.getFunction().getCallingConv()) {
6575   case CallingConv::AMDGPU_PS:
6576     return 1;
6577   case CallingConv::AMDGPU_VS:
6578     return 2;
6579   case CallingConv::AMDGPU_GS:
6580     return 3;
6581   case CallingConv::AMDGPU_HS:
6582   case CallingConv::AMDGPU_LS:
6583   case CallingConv::AMDGPU_ES:
6584     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6585   case CallingConv::AMDGPU_CS:
6586   case CallingConv::AMDGPU_KERNEL:
6587   case CallingConv::C:
6588   case CallingConv::Fast:
6589   default:
6590     // Assume other calling conventions are various compute callable functions
6591     return 0;
6592   }
6593 }
6594 
6595 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6596                                                  SelectionDAG &DAG) const {
6597   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6598   SDLoc DL(Op);
6599 
6600   switch (IntrID) {
6601   case Intrinsic::amdgcn_ds_ordered_add:
6602   case Intrinsic::amdgcn_ds_ordered_swap: {
6603     MemSDNode *M = cast<MemSDNode>(Op);
6604     SDValue Chain = M->getOperand(0);
6605     SDValue M0 = M->getOperand(2);
6606     SDValue Value = M->getOperand(3);
6607     unsigned IndexOperand = M->getConstantOperandVal(7);
6608     unsigned WaveRelease = M->getConstantOperandVal(8);
6609     unsigned WaveDone = M->getConstantOperandVal(9);
6610 
6611     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6612     IndexOperand &= ~0x3f;
6613     unsigned CountDw = 0;
6614 
6615     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6616       CountDw = (IndexOperand >> 24) & 0xf;
6617       IndexOperand &= ~(0xf << 24);
6618 
6619       if (CountDw < 1 || CountDw > 4) {
6620         report_fatal_error(
6621             "ds_ordered_count: dword count must be between 1 and 4");
6622       }
6623     }
6624 
6625     if (IndexOperand)
6626       report_fatal_error("ds_ordered_count: bad index operand");
6627 
6628     if (WaveDone && !WaveRelease)
6629       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6630 
6631     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6632     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6633     unsigned Offset0 = OrderedCountIndex << 2;
6634     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6635                        (Instruction << 4);
6636 
6637     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6638       Offset1 |= (CountDw - 1) << 6;
6639 
6640     unsigned Offset = Offset0 | (Offset1 << 8);
6641 
6642     SDValue Ops[] = {
6643       Chain,
6644       Value,
6645       DAG.getTargetConstant(Offset, DL, MVT::i16),
6646       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6647     };
6648     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6649                                    M->getVTList(), Ops, M->getMemoryVT(),
6650                                    M->getMemOperand());
6651   }
6652   case Intrinsic::amdgcn_ds_fadd: {
6653     MemSDNode *M = cast<MemSDNode>(Op);
6654     unsigned Opc;
6655     switch (IntrID) {
6656     case Intrinsic::amdgcn_ds_fadd:
6657       Opc = ISD::ATOMIC_LOAD_FADD;
6658       break;
6659     }
6660 
6661     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6662                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6663                          M->getMemOperand());
6664   }
6665   case Intrinsic::amdgcn_atomic_inc:
6666   case Intrinsic::amdgcn_atomic_dec:
6667   case Intrinsic::amdgcn_ds_fmin:
6668   case Intrinsic::amdgcn_ds_fmax: {
6669     MemSDNode *M = cast<MemSDNode>(Op);
6670     unsigned Opc;
6671     switch (IntrID) {
6672     case Intrinsic::amdgcn_atomic_inc:
6673       Opc = AMDGPUISD::ATOMIC_INC;
6674       break;
6675     case Intrinsic::amdgcn_atomic_dec:
6676       Opc = AMDGPUISD::ATOMIC_DEC;
6677       break;
6678     case Intrinsic::amdgcn_ds_fmin:
6679       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6680       break;
6681     case Intrinsic::amdgcn_ds_fmax:
6682       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6683       break;
6684     default:
6685       llvm_unreachable("Unknown intrinsic!");
6686     }
6687     SDValue Ops[] = {
6688       M->getOperand(0), // Chain
6689       M->getOperand(2), // Ptr
6690       M->getOperand(3)  // Value
6691     };
6692 
6693     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6694                                    M->getMemoryVT(), M->getMemOperand());
6695   }
6696   case Intrinsic::amdgcn_buffer_load:
6697   case Intrinsic::amdgcn_buffer_load_format: {
6698     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6699     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6700     unsigned IdxEn = 1;
6701     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6702       IdxEn = Idx->getZExtValue() != 0;
6703     SDValue Ops[] = {
6704       Op.getOperand(0), // Chain
6705       Op.getOperand(2), // rsrc
6706       Op.getOperand(3), // vindex
6707       SDValue(),        // voffset -- will be set by setBufferOffsets
6708       SDValue(),        // soffset -- will be set by setBufferOffsets
6709       SDValue(),        // offset -- will be set by setBufferOffsets
6710       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6711       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6712     };
6713 
6714     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6715     // We don't know the offset if vindex is non-zero, so clear it.
6716     if (IdxEn)
6717       Offset = 0;
6718 
6719     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6720         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6721 
6722     EVT VT = Op.getValueType();
6723     EVT IntVT = VT.changeTypeToInteger();
6724     auto *M = cast<MemSDNode>(Op);
6725     M->getMemOperand()->setOffset(Offset);
6726     EVT LoadVT = Op.getValueType();
6727 
6728     if (LoadVT.getScalarType() == MVT::f16)
6729       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6730                                  M, DAG, Ops);
6731 
6732     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6733     if (LoadVT.getScalarType() == MVT::i8 ||
6734         LoadVT.getScalarType() == MVT::i16)
6735       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6736 
6737     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6738                                M->getMemOperand(), DAG);
6739   }
6740   case Intrinsic::amdgcn_raw_buffer_load:
6741   case Intrinsic::amdgcn_raw_buffer_load_format: {
6742     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6743 
6744     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6745     SDValue Ops[] = {
6746       Op.getOperand(0), // Chain
6747       Op.getOperand(2), // rsrc
6748       DAG.getConstant(0, DL, MVT::i32), // vindex
6749       Offsets.first,    // voffset
6750       Op.getOperand(4), // soffset
6751       Offsets.second,   // offset
6752       Op.getOperand(5), // cachepolicy, swizzled buffer
6753       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6754     };
6755 
6756     auto *M = cast<MemSDNode>(Op);
6757     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6758     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6759   }
6760   case Intrinsic::amdgcn_struct_buffer_load:
6761   case Intrinsic::amdgcn_struct_buffer_load_format: {
6762     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6763 
6764     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6765     SDValue Ops[] = {
6766       Op.getOperand(0), // Chain
6767       Op.getOperand(2), // rsrc
6768       Op.getOperand(3), // vindex
6769       Offsets.first,    // voffset
6770       Op.getOperand(5), // soffset
6771       Offsets.second,   // offset
6772       Op.getOperand(6), // cachepolicy, swizzled buffer
6773       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6774     };
6775 
6776     auto *M = cast<MemSDNode>(Op);
6777     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6778                                                         Ops[2]));
6779     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6780   }
6781   case Intrinsic::amdgcn_tbuffer_load: {
6782     MemSDNode *M = cast<MemSDNode>(Op);
6783     EVT LoadVT = Op.getValueType();
6784 
6785     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6786     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6787     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6788     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6789     unsigned IdxEn = 1;
6790     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6791       IdxEn = Idx->getZExtValue() != 0;
6792     SDValue Ops[] = {
6793       Op.getOperand(0),  // Chain
6794       Op.getOperand(2),  // rsrc
6795       Op.getOperand(3),  // vindex
6796       Op.getOperand(4),  // voffset
6797       Op.getOperand(5),  // soffset
6798       Op.getOperand(6),  // offset
6799       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6800       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6801       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6802     };
6803 
6804     if (LoadVT.getScalarType() == MVT::f16)
6805       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6806                                  M, DAG, Ops);
6807     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6808                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6809                                DAG);
6810   }
6811   case Intrinsic::amdgcn_raw_tbuffer_load: {
6812     MemSDNode *M = cast<MemSDNode>(Op);
6813     EVT LoadVT = Op.getValueType();
6814     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6815 
6816     SDValue Ops[] = {
6817       Op.getOperand(0),  // Chain
6818       Op.getOperand(2),  // rsrc
6819       DAG.getConstant(0, DL, MVT::i32), // vindex
6820       Offsets.first,     // voffset
6821       Op.getOperand(4),  // soffset
6822       Offsets.second,    // offset
6823       Op.getOperand(5),  // format
6824       Op.getOperand(6),  // cachepolicy, swizzled buffer
6825       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6826     };
6827 
6828     if (LoadVT.getScalarType() == MVT::f16)
6829       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6830                                  M, DAG, Ops);
6831     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6832                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6833                                DAG);
6834   }
6835   case Intrinsic::amdgcn_struct_tbuffer_load: {
6836     MemSDNode *M = cast<MemSDNode>(Op);
6837     EVT LoadVT = Op.getValueType();
6838     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6839 
6840     SDValue Ops[] = {
6841       Op.getOperand(0),  // Chain
6842       Op.getOperand(2),  // rsrc
6843       Op.getOperand(3),  // vindex
6844       Offsets.first,     // voffset
6845       Op.getOperand(5),  // soffset
6846       Offsets.second,    // offset
6847       Op.getOperand(6),  // format
6848       Op.getOperand(7),  // cachepolicy, swizzled buffer
6849       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6850     };
6851 
6852     if (LoadVT.getScalarType() == MVT::f16)
6853       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6854                                  M, DAG, Ops);
6855     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6856                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6857                                DAG);
6858   }
6859   case Intrinsic::amdgcn_buffer_atomic_swap:
6860   case Intrinsic::amdgcn_buffer_atomic_add:
6861   case Intrinsic::amdgcn_buffer_atomic_sub:
6862   case Intrinsic::amdgcn_buffer_atomic_smin:
6863   case Intrinsic::amdgcn_buffer_atomic_umin:
6864   case Intrinsic::amdgcn_buffer_atomic_smax:
6865   case Intrinsic::amdgcn_buffer_atomic_umax:
6866   case Intrinsic::amdgcn_buffer_atomic_and:
6867   case Intrinsic::amdgcn_buffer_atomic_or:
6868   case Intrinsic::amdgcn_buffer_atomic_xor: {
6869     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6870     unsigned IdxEn = 1;
6871     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6872       IdxEn = Idx->getZExtValue() != 0;
6873     SDValue Ops[] = {
6874       Op.getOperand(0), // Chain
6875       Op.getOperand(2), // vdata
6876       Op.getOperand(3), // rsrc
6877       Op.getOperand(4), // vindex
6878       SDValue(),        // voffset -- will be set by setBufferOffsets
6879       SDValue(),        // soffset -- will be set by setBufferOffsets
6880       SDValue(),        // offset -- will be set by setBufferOffsets
6881       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6882       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6883     };
6884     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6885     // We don't know the offset if vindex is non-zero, so clear it.
6886     if (IdxEn)
6887       Offset = 0;
6888     EVT VT = Op.getValueType();
6889 
6890     auto *M = cast<MemSDNode>(Op);
6891     M->getMemOperand()->setOffset(Offset);
6892     unsigned Opcode = 0;
6893 
6894     switch (IntrID) {
6895     case Intrinsic::amdgcn_buffer_atomic_swap:
6896       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6897       break;
6898     case Intrinsic::amdgcn_buffer_atomic_add:
6899       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6900       break;
6901     case Intrinsic::amdgcn_buffer_atomic_sub:
6902       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6903       break;
6904     case Intrinsic::amdgcn_buffer_atomic_smin:
6905       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6906       break;
6907     case Intrinsic::amdgcn_buffer_atomic_umin:
6908       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6909       break;
6910     case Intrinsic::amdgcn_buffer_atomic_smax:
6911       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6912       break;
6913     case Intrinsic::amdgcn_buffer_atomic_umax:
6914       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6915       break;
6916     case Intrinsic::amdgcn_buffer_atomic_and:
6917       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6918       break;
6919     case Intrinsic::amdgcn_buffer_atomic_or:
6920       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6921       break;
6922     case Intrinsic::amdgcn_buffer_atomic_xor:
6923       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6924       break;
6925     default:
6926       llvm_unreachable("unhandled atomic opcode");
6927     }
6928 
6929     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6930                                    M->getMemOperand());
6931   }
6932   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6933   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6934   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6935   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6936   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6937   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6938   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6939   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6940   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6941   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6942   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6943   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6944     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6945     SDValue Ops[] = {
6946       Op.getOperand(0), // Chain
6947       Op.getOperand(2), // vdata
6948       Op.getOperand(3), // rsrc
6949       DAG.getConstant(0, DL, MVT::i32), // vindex
6950       Offsets.first,    // voffset
6951       Op.getOperand(5), // soffset
6952       Offsets.second,   // offset
6953       Op.getOperand(6), // cachepolicy
6954       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6955     };
6956     EVT VT = Op.getValueType();
6957 
6958     auto *M = cast<MemSDNode>(Op);
6959     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6960     unsigned Opcode = 0;
6961 
6962     switch (IntrID) {
6963     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6964       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6965       break;
6966     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6967       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6968       break;
6969     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6970       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6971       break;
6972     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6973       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6974       break;
6975     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6976       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6977       break;
6978     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6979       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6980       break;
6981     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6982       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6983       break;
6984     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6985       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6986       break;
6987     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6988       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6989       break;
6990     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6991       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6992       break;
6993     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6994       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6995       break;
6996     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6997       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6998       break;
6999     default:
7000       llvm_unreachable("unhandled atomic opcode");
7001     }
7002 
7003     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7004                                    M->getMemOperand());
7005   }
7006   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7007   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7008   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7009   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7010   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7011   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7012   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7013   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7014   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7015   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7016   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7017   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
7018     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7019     SDValue Ops[] = {
7020       Op.getOperand(0), // Chain
7021       Op.getOperand(2), // vdata
7022       Op.getOperand(3), // rsrc
7023       Op.getOperand(4), // vindex
7024       Offsets.first,    // voffset
7025       Op.getOperand(6), // soffset
7026       Offsets.second,   // offset
7027       Op.getOperand(7), // cachepolicy
7028       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7029     };
7030     EVT VT = Op.getValueType();
7031 
7032     auto *M = cast<MemSDNode>(Op);
7033     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7034                                                         Ops[3]));
7035     unsigned Opcode = 0;
7036 
7037     switch (IntrID) {
7038     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7039       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7040       break;
7041     case Intrinsic::amdgcn_struct_buffer_atomic_add:
7042       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7043       break;
7044     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7045       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7046       break;
7047     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7048       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7049       break;
7050     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7051       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7052       break;
7053     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7054       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7055       break;
7056     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7057       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7058       break;
7059     case Intrinsic::amdgcn_struct_buffer_atomic_and:
7060       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7061       break;
7062     case Intrinsic::amdgcn_struct_buffer_atomic_or:
7063       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7064       break;
7065     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7066       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7067       break;
7068     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7069       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
7070       break;
7071     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7072       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
7073       break;
7074     default:
7075       llvm_unreachable("unhandled atomic opcode");
7076     }
7077 
7078     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7079                                    M->getMemOperand());
7080   }
7081   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7082     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7083     unsigned IdxEn = 1;
7084     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7085       IdxEn = Idx->getZExtValue() != 0;
7086     SDValue Ops[] = {
7087       Op.getOperand(0), // Chain
7088       Op.getOperand(2), // src
7089       Op.getOperand(3), // cmp
7090       Op.getOperand(4), // rsrc
7091       Op.getOperand(5), // vindex
7092       SDValue(),        // voffset -- will be set by setBufferOffsets
7093       SDValue(),        // soffset -- will be set by setBufferOffsets
7094       SDValue(),        // offset -- will be set by setBufferOffsets
7095       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7096       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7097     };
7098     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7099     // We don't know the offset if vindex is non-zero, so clear it.
7100     if (IdxEn)
7101       Offset = 0;
7102     EVT VT = Op.getValueType();
7103     auto *M = cast<MemSDNode>(Op);
7104     M->getMemOperand()->setOffset(Offset);
7105 
7106     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7107                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7108   }
7109   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7110     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7111     SDValue Ops[] = {
7112       Op.getOperand(0), // Chain
7113       Op.getOperand(2), // src
7114       Op.getOperand(3), // cmp
7115       Op.getOperand(4), // rsrc
7116       DAG.getConstant(0, DL, MVT::i32), // vindex
7117       Offsets.first,    // voffset
7118       Op.getOperand(6), // soffset
7119       Offsets.second,   // offset
7120       Op.getOperand(7), // cachepolicy
7121       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7122     };
7123     EVT VT = Op.getValueType();
7124     auto *M = cast<MemSDNode>(Op);
7125     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7126 
7127     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7128                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7129   }
7130   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7131     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7132     SDValue Ops[] = {
7133       Op.getOperand(0), // Chain
7134       Op.getOperand(2), // src
7135       Op.getOperand(3), // cmp
7136       Op.getOperand(4), // rsrc
7137       Op.getOperand(5), // vindex
7138       Offsets.first,    // voffset
7139       Op.getOperand(7), // soffset
7140       Offsets.second,   // offset
7141       Op.getOperand(8), // cachepolicy
7142       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7143     };
7144     EVT VT = Op.getValueType();
7145     auto *M = cast<MemSDNode>(Op);
7146     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7147                                                         Ops[4]));
7148 
7149     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7150                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7151   }
7152 
7153   default:
7154     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7155             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7156       return lowerImage(Op, ImageDimIntr, DAG);
7157 
7158     return SDValue();
7159   }
7160 }
7161 
7162 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7163 // dwordx4 if on SI.
7164 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7165                                               SDVTList VTList,
7166                                               ArrayRef<SDValue> Ops, EVT MemVT,
7167                                               MachineMemOperand *MMO,
7168                                               SelectionDAG &DAG) const {
7169   EVT VT = VTList.VTs[0];
7170   EVT WidenedVT = VT;
7171   EVT WidenedMemVT = MemVT;
7172   if (!Subtarget->hasDwordx3LoadStores() &&
7173       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7174     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7175                                  WidenedVT.getVectorElementType(), 4);
7176     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7177                                     WidenedMemVT.getVectorElementType(), 4);
7178     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7179   }
7180 
7181   assert(VTList.NumVTs == 2);
7182   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7183 
7184   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7185                                        WidenedMemVT, MMO);
7186   if (WidenedVT != VT) {
7187     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7188                                DAG.getVectorIdxConstant(0, DL));
7189     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7190   }
7191   return NewOp;
7192 }
7193 
7194 SDValue SITargetLowering::handleD16VData(SDValue VData,
7195                                          SelectionDAG &DAG) const {
7196   EVT StoreVT = VData.getValueType();
7197 
7198   // No change for f16 and legal vector D16 types.
7199   if (!StoreVT.isVector())
7200     return VData;
7201 
7202   SDLoc DL(VData);
7203   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
7204 
7205   if (Subtarget->hasUnpackedD16VMem()) {
7206     // We need to unpack the packed data to store.
7207     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7208     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7209 
7210     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
7211                                         StoreVT.getVectorNumElements());
7212     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7213     return DAG.UnrollVectorOp(ZExt.getNode());
7214   }
7215 
7216   assert(isTypeLegal(StoreVT));
7217   return VData;
7218 }
7219 
7220 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7221                                               SelectionDAG &DAG) const {
7222   SDLoc DL(Op);
7223   SDValue Chain = Op.getOperand(0);
7224   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7225   MachineFunction &MF = DAG.getMachineFunction();
7226 
7227   switch (IntrinsicID) {
7228   case Intrinsic::amdgcn_exp_compr: {
7229     SDValue Src0 = Op.getOperand(4);
7230     SDValue Src1 = Op.getOperand(5);
7231     // Hack around illegal type on SI by directly selecting it.
7232     if (isTypeLegal(Src0.getValueType()))
7233       return SDValue();
7234 
7235     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7236     SDValue Undef = DAG.getUNDEF(MVT::f32);
7237     const SDValue Ops[] = {
7238       Op.getOperand(2), // tgt
7239       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7240       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7241       Undef, // src2
7242       Undef, // src3
7243       Op.getOperand(7), // vm
7244       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7245       Op.getOperand(3), // en
7246       Op.getOperand(0) // Chain
7247     };
7248 
7249     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7250     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7251   }
7252   case Intrinsic::amdgcn_s_barrier: {
7253     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7254       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7255       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7256       if (WGSize <= ST.getWavefrontSize())
7257         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7258                                           Op.getOperand(0)), 0);
7259     }
7260     return SDValue();
7261   };
7262   case Intrinsic::amdgcn_tbuffer_store: {
7263     SDValue VData = Op.getOperand(2);
7264     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7265     if (IsD16)
7266       VData = handleD16VData(VData, DAG);
7267     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7268     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7269     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7270     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7271     unsigned IdxEn = 1;
7272     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7273       IdxEn = Idx->getZExtValue() != 0;
7274     SDValue Ops[] = {
7275       Chain,
7276       VData,             // vdata
7277       Op.getOperand(3),  // rsrc
7278       Op.getOperand(4),  // vindex
7279       Op.getOperand(5),  // voffset
7280       Op.getOperand(6),  // soffset
7281       Op.getOperand(7),  // offset
7282       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7283       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7284       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7285     };
7286     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7287                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7288     MemSDNode *M = cast<MemSDNode>(Op);
7289     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7290                                    M->getMemoryVT(), M->getMemOperand());
7291   }
7292 
7293   case Intrinsic::amdgcn_struct_tbuffer_store: {
7294     SDValue VData = Op.getOperand(2);
7295     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7296     if (IsD16)
7297       VData = handleD16VData(VData, DAG);
7298     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7299     SDValue Ops[] = {
7300       Chain,
7301       VData,             // vdata
7302       Op.getOperand(3),  // rsrc
7303       Op.getOperand(4),  // vindex
7304       Offsets.first,     // voffset
7305       Op.getOperand(6),  // soffset
7306       Offsets.second,    // offset
7307       Op.getOperand(7),  // format
7308       Op.getOperand(8),  // cachepolicy, swizzled buffer
7309       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7310     };
7311     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7312                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7313     MemSDNode *M = cast<MemSDNode>(Op);
7314     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7315                                    M->getMemoryVT(), M->getMemOperand());
7316   }
7317 
7318   case Intrinsic::amdgcn_raw_tbuffer_store: {
7319     SDValue VData = Op.getOperand(2);
7320     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7321     if (IsD16)
7322       VData = handleD16VData(VData, DAG);
7323     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7324     SDValue Ops[] = {
7325       Chain,
7326       VData,             // vdata
7327       Op.getOperand(3),  // rsrc
7328       DAG.getConstant(0, DL, MVT::i32), // vindex
7329       Offsets.first,     // voffset
7330       Op.getOperand(5),  // soffset
7331       Offsets.second,    // offset
7332       Op.getOperand(6),  // format
7333       Op.getOperand(7),  // cachepolicy, swizzled buffer
7334       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7335     };
7336     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7337                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7338     MemSDNode *M = cast<MemSDNode>(Op);
7339     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7340                                    M->getMemoryVT(), M->getMemOperand());
7341   }
7342 
7343   case Intrinsic::amdgcn_buffer_store:
7344   case Intrinsic::amdgcn_buffer_store_format: {
7345     SDValue VData = Op.getOperand(2);
7346     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7347     if (IsD16)
7348       VData = handleD16VData(VData, DAG);
7349     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7350     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7351     unsigned IdxEn = 1;
7352     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7353       IdxEn = Idx->getZExtValue() != 0;
7354     SDValue Ops[] = {
7355       Chain,
7356       VData,
7357       Op.getOperand(3), // rsrc
7358       Op.getOperand(4), // vindex
7359       SDValue(), // voffset -- will be set by setBufferOffsets
7360       SDValue(), // soffset -- will be set by setBufferOffsets
7361       SDValue(), // offset -- will be set by setBufferOffsets
7362       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7363       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7364     };
7365     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7366     // We don't know the offset if vindex is non-zero, so clear it.
7367     if (IdxEn)
7368       Offset = 0;
7369     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7370                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7371     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7372     MemSDNode *M = cast<MemSDNode>(Op);
7373     M->getMemOperand()->setOffset(Offset);
7374 
7375     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7376     EVT VDataType = VData.getValueType().getScalarType();
7377     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7378       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7379 
7380     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7381                                    M->getMemoryVT(), M->getMemOperand());
7382   }
7383 
7384   case Intrinsic::amdgcn_raw_buffer_store:
7385   case Intrinsic::amdgcn_raw_buffer_store_format: {
7386     const bool IsFormat =
7387         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7388 
7389     SDValue VData = Op.getOperand(2);
7390     EVT VDataVT = VData.getValueType();
7391     EVT EltType = VDataVT.getScalarType();
7392     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7393     if (IsD16)
7394       VData = handleD16VData(VData, DAG);
7395 
7396     if (!isTypeLegal(VDataVT)) {
7397       VData =
7398           DAG.getNode(ISD::BITCAST, DL,
7399                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7400     }
7401 
7402     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7403     SDValue Ops[] = {
7404       Chain,
7405       VData,
7406       Op.getOperand(3), // rsrc
7407       DAG.getConstant(0, DL, MVT::i32), // vindex
7408       Offsets.first,    // voffset
7409       Op.getOperand(5), // soffset
7410       Offsets.second,   // offset
7411       Op.getOperand(6), // cachepolicy, swizzled buffer
7412       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7413     };
7414     unsigned Opc =
7415         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7416     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7417     MemSDNode *M = cast<MemSDNode>(Op);
7418     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7419 
7420     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7421     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7422       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7423 
7424     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7425                                    M->getMemoryVT(), M->getMemOperand());
7426   }
7427 
7428   case Intrinsic::amdgcn_struct_buffer_store:
7429   case Intrinsic::amdgcn_struct_buffer_store_format: {
7430     const bool IsFormat =
7431         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7432 
7433     SDValue VData = Op.getOperand(2);
7434     EVT VDataVT = VData.getValueType();
7435     EVT EltType = VDataVT.getScalarType();
7436     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7437 
7438     if (IsD16)
7439       VData = handleD16VData(VData, DAG);
7440 
7441     if (!isTypeLegal(VDataVT)) {
7442       VData =
7443           DAG.getNode(ISD::BITCAST, DL,
7444                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7445     }
7446 
7447     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7448     SDValue Ops[] = {
7449       Chain,
7450       VData,
7451       Op.getOperand(3), // rsrc
7452       Op.getOperand(4), // vindex
7453       Offsets.first,    // voffset
7454       Op.getOperand(6), // soffset
7455       Offsets.second,   // offset
7456       Op.getOperand(7), // cachepolicy, swizzled buffer
7457       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7458     };
7459     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7460                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7461     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7462     MemSDNode *M = cast<MemSDNode>(Op);
7463     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7464                                                         Ops[3]));
7465 
7466     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7467     EVT VDataType = VData.getValueType().getScalarType();
7468     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7469       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7470 
7471     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7472                                    M->getMemoryVT(), M->getMemOperand());
7473   }
7474 
7475   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7476     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7477     unsigned IdxEn = 1;
7478     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7479       IdxEn = Idx->getZExtValue() != 0;
7480     SDValue Ops[] = {
7481       Chain,
7482       Op.getOperand(2), // vdata
7483       Op.getOperand(3), // rsrc
7484       Op.getOperand(4), // vindex
7485       SDValue(),        // voffset -- will be set by setBufferOffsets
7486       SDValue(),        // soffset -- will be set by setBufferOffsets
7487       SDValue(),        // offset -- will be set by setBufferOffsets
7488       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7489       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7490     };
7491     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7492     // We don't know the offset if vindex is non-zero, so clear it.
7493     if (IdxEn)
7494       Offset = 0;
7495     EVT VT = Op.getOperand(2).getValueType();
7496 
7497     auto *M = cast<MemSDNode>(Op);
7498     M->getMemOperand()->setOffset(Offset);
7499     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7500                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7501 
7502     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7503                                    M->getMemOperand());
7504   }
7505 
7506   case Intrinsic::amdgcn_global_atomic_fadd: {
7507     SDValue Ops[] = {
7508       Chain,
7509       Op.getOperand(2), // ptr
7510       Op.getOperand(3)  // vdata
7511     };
7512     EVT VT = Op.getOperand(3).getValueType();
7513 
7514     auto *M = cast<MemSDNode>(Op);
7515     if (VT.isVector()) {
7516       return DAG.getMemIntrinsicNode(
7517         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7518         M->getMemOperand());
7519     }
7520 
7521     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7522                          DAG.getVTList(VT, MVT::Other), Ops,
7523                          M->getMemOperand()).getValue(1);
7524   }
7525   case Intrinsic::amdgcn_end_cf:
7526     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7527                                       Op->getOperand(2), Chain), 0);
7528 
7529   default: {
7530     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7531             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7532       return lowerImage(Op, ImageDimIntr, DAG);
7533 
7534     return Op;
7535   }
7536   }
7537 }
7538 
7539 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7540 // offset (the offset that is included in bounds checking and swizzling, to be
7541 // split between the instruction's voffset and immoffset fields) and soffset
7542 // (the offset that is excluded from bounds checking and swizzling, to go in
7543 // the instruction's soffset field).  This function takes the first kind of
7544 // offset and figures out how to split it between voffset and immoffset.
7545 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7546     SDValue Offset, SelectionDAG &DAG) const {
7547   SDLoc DL(Offset);
7548   const unsigned MaxImm = 4095;
7549   SDValue N0 = Offset;
7550   ConstantSDNode *C1 = nullptr;
7551 
7552   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7553     N0 = SDValue();
7554   else if (DAG.isBaseWithConstantOffset(N0)) {
7555     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7556     N0 = N0.getOperand(0);
7557   }
7558 
7559   if (C1) {
7560     unsigned ImmOffset = C1->getZExtValue();
7561     // If the immediate value is too big for the immoffset field, put the value
7562     // and -4096 into the immoffset field so that the value that is copied/added
7563     // for the voffset field is a multiple of 4096, and it stands more chance
7564     // of being CSEd with the copy/add for another similar load/store.
7565     // However, do not do that rounding down to a multiple of 4096 if that is a
7566     // negative number, as it appears to be illegal to have a negative offset
7567     // in the vgpr, even if adding the immediate offset makes it positive.
7568     unsigned Overflow = ImmOffset & ~MaxImm;
7569     ImmOffset -= Overflow;
7570     if ((int32_t)Overflow < 0) {
7571       Overflow += ImmOffset;
7572       ImmOffset = 0;
7573     }
7574     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7575     if (Overflow) {
7576       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7577       if (!N0)
7578         N0 = OverflowVal;
7579       else {
7580         SDValue Ops[] = { N0, OverflowVal };
7581         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7582       }
7583     }
7584   }
7585   if (!N0)
7586     N0 = DAG.getConstant(0, DL, MVT::i32);
7587   if (!C1)
7588     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7589   return {N0, SDValue(C1, 0)};
7590 }
7591 
7592 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7593 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7594 // pointed to by Offsets.
7595 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7596                                         SelectionDAG &DAG, SDValue *Offsets,
7597                                         unsigned Align) const {
7598   SDLoc DL(CombinedOffset);
7599   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7600     uint32_t Imm = C->getZExtValue();
7601     uint32_t SOffset, ImmOffset;
7602     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7603       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7604       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7605       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7606       return SOffset + ImmOffset;
7607     }
7608   }
7609   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7610     SDValue N0 = CombinedOffset.getOperand(0);
7611     SDValue N1 = CombinedOffset.getOperand(1);
7612     uint32_t SOffset, ImmOffset;
7613     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7614     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7615                                                 Subtarget, Align)) {
7616       Offsets[0] = N0;
7617       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7618       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7619       return 0;
7620     }
7621   }
7622   Offsets[0] = CombinedOffset;
7623   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7624   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7625   return 0;
7626 }
7627 
7628 // Handle 8 bit and 16 bit buffer loads
7629 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7630                                                      EVT LoadVT, SDLoc DL,
7631                                                      ArrayRef<SDValue> Ops,
7632                                                      MemSDNode *M) const {
7633   EVT IntVT = LoadVT.changeTypeToInteger();
7634   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7635          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7636 
7637   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7638   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7639                                                Ops, IntVT,
7640                                                M->getMemOperand());
7641   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7642   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7643 
7644   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7645 }
7646 
7647 // Handle 8 bit and 16 bit buffer stores
7648 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7649                                                       EVT VDataType, SDLoc DL,
7650                                                       SDValue Ops[],
7651                                                       MemSDNode *M) const {
7652   if (VDataType == MVT::f16)
7653     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7654 
7655   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7656   Ops[1] = BufferStoreExt;
7657   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7658                                  AMDGPUISD::BUFFER_STORE_SHORT;
7659   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7660   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7661                                      M->getMemOperand());
7662 }
7663 
7664 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7665                                  ISD::LoadExtType ExtType, SDValue Op,
7666                                  const SDLoc &SL, EVT VT) {
7667   if (VT.bitsLT(Op.getValueType()))
7668     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7669 
7670   switch (ExtType) {
7671   case ISD::SEXTLOAD:
7672     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7673   case ISD::ZEXTLOAD:
7674     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7675   case ISD::EXTLOAD:
7676     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7677   case ISD::NON_EXTLOAD:
7678     return Op;
7679   }
7680 
7681   llvm_unreachable("invalid ext type");
7682 }
7683 
7684 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7685   SelectionDAG &DAG = DCI.DAG;
7686   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7687     return SDValue();
7688 
7689   // FIXME: Constant loads should all be marked invariant.
7690   unsigned AS = Ld->getAddressSpace();
7691   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7692       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7693       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7694     return SDValue();
7695 
7696   // Don't do this early, since it may interfere with adjacent load merging for
7697   // illegal types. We can avoid losing alignment information for exotic types
7698   // pre-legalize.
7699   EVT MemVT = Ld->getMemoryVT();
7700   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7701       MemVT.getSizeInBits() >= 32)
7702     return SDValue();
7703 
7704   SDLoc SL(Ld);
7705 
7706   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7707          "unexpected vector extload");
7708 
7709   // TODO: Drop only high part of range.
7710   SDValue Ptr = Ld->getBasePtr();
7711   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7712                                 MVT::i32, SL, Ld->getChain(), Ptr,
7713                                 Ld->getOffset(),
7714                                 Ld->getPointerInfo(), MVT::i32,
7715                                 Ld->getAlignment(),
7716                                 Ld->getMemOperand()->getFlags(),
7717                                 Ld->getAAInfo(),
7718                                 nullptr); // Drop ranges
7719 
7720   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7721   if (MemVT.isFloatingPoint()) {
7722     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7723            "unexpected fp extload");
7724     TruncVT = MemVT.changeTypeToInteger();
7725   }
7726 
7727   SDValue Cvt = NewLoad;
7728   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7729     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7730                       DAG.getValueType(TruncVT));
7731   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7732              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7733     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7734   } else {
7735     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7736   }
7737 
7738   EVT VT = Ld->getValueType(0);
7739   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7740 
7741   DCI.AddToWorklist(Cvt.getNode());
7742 
7743   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7744   // the appropriate extension from the 32-bit load.
7745   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7746   DCI.AddToWorklist(Cvt.getNode());
7747 
7748   // Handle conversion back to floating point if necessary.
7749   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7750 
7751   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7752 }
7753 
7754 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7755   SDLoc DL(Op);
7756   LoadSDNode *Load = cast<LoadSDNode>(Op);
7757   ISD::LoadExtType ExtType = Load->getExtensionType();
7758   EVT MemVT = Load->getMemoryVT();
7759 
7760   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7761     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7762       return SDValue();
7763 
7764     // FIXME: Copied from PPC
7765     // First, load into 32 bits, then truncate to 1 bit.
7766 
7767     SDValue Chain = Load->getChain();
7768     SDValue BasePtr = Load->getBasePtr();
7769     MachineMemOperand *MMO = Load->getMemOperand();
7770 
7771     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7772 
7773     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7774                                    BasePtr, RealMemVT, MMO);
7775 
7776     if (!MemVT.isVector()) {
7777       SDValue Ops[] = {
7778         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7779         NewLD.getValue(1)
7780       };
7781 
7782       return DAG.getMergeValues(Ops, DL);
7783     }
7784 
7785     SmallVector<SDValue, 3> Elts;
7786     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7787       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7788                                 DAG.getConstant(I, DL, MVT::i32));
7789 
7790       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7791     }
7792 
7793     SDValue Ops[] = {
7794       DAG.getBuildVector(MemVT, DL, Elts),
7795       NewLD.getValue(1)
7796     };
7797 
7798     return DAG.getMergeValues(Ops, DL);
7799   }
7800 
7801   if (!MemVT.isVector())
7802     return SDValue();
7803 
7804   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7805          "Custom lowering for non-i32 vectors hasn't been implemented.");
7806 
7807   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7808                                       MemVT, *Load->getMemOperand())) {
7809     SDValue Ops[2];
7810     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7811     return DAG.getMergeValues(Ops, DL);
7812   }
7813 
7814   unsigned Alignment = Load->getAlignment();
7815   unsigned AS = Load->getAddressSpace();
7816   if (Subtarget->hasLDSMisalignedBug() &&
7817       AS == AMDGPUAS::FLAT_ADDRESS &&
7818       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7819     return SplitVectorLoad(Op, DAG);
7820   }
7821 
7822   MachineFunction &MF = DAG.getMachineFunction();
7823   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7824   // If there is a possibilty that flat instruction access scratch memory
7825   // then we need to use the same legalization rules we use for private.
7826   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7827       !Subtarget->hasMultiDwordFlatScratchAddressing())
7828     AS = MFI->hasFlatScratchInit() ?
7829          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7830 
7831   unsigned NumElements = MemVT.getVectorNumElements();
7832 
7833   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7834       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7835     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7836       if (MemVT.isPow2VectorType())
7837         return SDValue();
7838       if (NumElements == 3)
7839         return WidenVectorLoad(Op, DAG);
7840       return SplitVectorLoad(Op, DAG);
7841     }
7842     // Non-uniform loads will be selected to MUBUF instructions, so they
7843     // have the same legalization requirements as global and private
7844     // loads.
7845     //
7846   }
7847 
7848   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7849       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7850       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7851     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7852         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7853         Alignment >= 4 && NumElements < 32) {
7854       if (MemVT.isPow2VectorType())
7855         return SDValue();
7856       if (NumElements == 3)
7857         return WidenVectorLoad(Op, DAG);
7858       return SplitVectorLoad(Op, DAG);
7859     }
7860     // Non-uniform loads will be selected to MUBUF instructions, so they
7861     // have the same legalization requirements as global and private
7862     // loads.
7863     //
7864   }
7865   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7866       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7867       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7868       AS == AMDGPUAS::FLAT_ADDRESS) {
7869     if (NumElements > 4)
7870       return SplitVectorLoad(Op, DAG);
7871     // v3 loads not supported on SI.
7872     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7873       return WidenVectorLoad(Op, DAG);
7874     // v3 and v4 loads are supported for private and global memory.
7875     return SDValue();
7876   }
7877   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7878     // Depending on the setting of the private_element_size field in the
7879     // resource descriptor, we can only make private accesses up to a certain
7880     // size.
7881     switch (Subtarget->getMaxPrivateElementSize()) {
7882     case 4: {
7883       SDValue Ops[2];
7884       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7885       return DAG.getMergeValues(Ops, DL);
7886     }
7887     case 8:
7888       if (NumElements > 2)
7889         return SplitVectorLoad(Op, DAG);
7890       return SDValue();
7891     case 16:
7892       // Same as global/flat
7893       if (NumElements > 4)
7894         return SplitVectorLoad(Op, DAG);
7895       // v3 loads not supported on SI.
7896       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7897         return WidenVectorLoad(Op, DAG);
7898       return SDValue();
7899     default:
7900       llvm_unreachable("unsupported private_element_size");
7901     }
7902   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7903     // Use ds_read_b128 if possible.
7904     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7905         MemVT.getStoreSize() == 16)
7906       return SDValue();
7907 
7908     if (NumElements > 2)
7909       return SplitVectorLoad(Op, DAG);
7910 
7911     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7912     // address is negative, then the instruction is incorrectly treated as
7913     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7914     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7915     // load later in the SILoadStoreOptimizer.
7916     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7917         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7918         Load->getAlignment() < 8) {
7919       return SplitVectorLoad(Op, DAG);
7920     }
7921   }
7922   return SDValue();
7923 }
7924 
7925 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7926   EVT VT = Op.getValueType();
7927   assert(VT.getSizeInBits() == 64);
7928 
7929   SDLoc DL(Op);
7930   SDValue Cond = Op.getOperand(0);
7931 
7932   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7933   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7934 
7935   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7936   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7937 
7938   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7939   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7940 
7941   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7942 
7943   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7944   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7945 
7946   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7947 
7948   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7949   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7950 }
7951 
7952 // Catch division cases where we can use shortcuts with rcp and rsq
7953 // instructions.
7954 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7955                                               SelectionDAG &DAG) const {
7956   SDLoc SL(Op);
7957   SDValue LHS = Op.getOperand(0);
7958   SDValue RHS = Op.getOperand(1);
7959   EVT VT = Op.getValueType();
7960   const SDNodeFlags Flags = Op->getFlags();
7961 
7962   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7963                             Flags.hasApproximateFuncs();
7964 
7965   // Without !fpmath accuracy information, we can't do more because we don't
7966   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7967   if (!AllowInaccurateRcp)
7968     return SDValue();
7969 
7970   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7971     if (CLHS->isExactlyValue(1.0)) {
7972       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7973       // the CI documentation has a worst case error of 1 ulp.
7974       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7975       // use it as long as we aren't trying to use denormals.
7976       //
7977       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7978 
7979       // 1.0 / sqrt(x) -> rsq(x)
7980 
7981       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7982       // error seems really high at 2^29 ULP.
7983       if (RHS.getOpcode() == ISD::FSQRT)
7984         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7985 
7986       // 1.0 / x -> rcp(x)
7987       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7988     }
7989 
7990     // Same as for 1.0, but expand the sign out of the constant.
7991     if (CLHS->isExactlyValue(-1.0)) {
7992       // -1.0 / x -> rcp (fneg x)
7993       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7994       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7995     }
7996   }
7997 
7998   // Turn into multiply by the reciprocal.
7999   // x / y -> x * (1.0 / y)
8000   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8001   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8002 }
8003 
8004 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8005                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8006                           SDNodeFlags Flags) {
8007   if (GlueChain->getNumValues() <= 1) {
8008     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8009   }
8010 
8011   assert(GlueChain->getNumValues() == 3);
8012 
8013   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8014   switch (Opcode) {
8015   default: llvm_unreachable("no chain equivalent for opcode");
8016   case ISD::FMUL:
8017     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8018     break;
8019   }
8020 
8021   return DAG.getNode(Opcode, SL, VTList,
8022                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8023                      Flags);
8024 }
8025 
8026 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8027                            EVT VT, SDValue A, SDValue B, SDValue C,
8028                            SDValue GlueChain, SDNodeFlags Flags) {
8029   if (GlueChain->getNumValues() <= 1) {
8030     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8031   }
8032 
8033   assert(GlueChain->getNumValues() == 3);
8034 
8035   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8036   switch (Opcode) {
8037   default: llvm_unreachable("no chain equivalent for opcode");
8038   case ISD::FMA:
8039     Opcode = AMDGPUISD::FMA_W_CHAIN;
8040     break;
8041   }
8042 
8043   return DAG.getNode(Opcode, SL, VTList,
8044                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8045                      Flags);
8046 }
8047 
8048 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8049   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8050     return FastLowered;
8051 
8052   SDLoc SL(Op);
8053   SDValue Src0 = Op.getOperand(0);
8054   SDValue Src1 = Op.getOperand(1);
8055 
8056   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8057   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8058 
8059   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8060   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8061 
8062   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8063   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8064 
8065   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8066 }
8067 
8068 // Faster 2.5 ULP division that does not support denormals.
8069 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8070   SDLoc SL(Op);
8071   SDValue LHS = Op.getOperand(1);
8072   SDValue RHS = Op.getOperand(2);
8073 
8074   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8075 
8076   const APFloat K0Val(BitsToFloat(0x6f800000));
8077   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8078 
8079   const APFloat K1Val(BitsToFloat(0x2f800000));
8080   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8081 
8082   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8083 
8084   EVT SetCCVT =
8085     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8086 
8087   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8088 
8089   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8090 
8091   // TODO: Should this propagate fast-math-flags?
8092   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8093 
8094   // rcp does not support denormals.
8095   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8096 
8097   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8098 
8099   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8100 }
8101 
8102 // Returns immediate value for setting the F32 denorm mode when using the
8103 // S_DENORM_MODE instruction.
8104 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8105                                           const SDLoc &SL, const GCNSubtarget *ST) {
8106   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8107   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8108                                 ? FP_DENORM_FLUSH_NONE
8109                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8110 
8111   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8112   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8113 }
8114 
8115 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8116   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8117     return FastLowered;
8118 
8119   // The selection matcher assumes anything with a chain selecting to a
8120   // mayRaiseFPException machine instruction. Since we're introducing a chain
8121   // here, we need to explicitly report nofpexcept for the regular fdiv
8122   // lowering.
8123   SDNodeFlags Flags = Op->getFlags();
8124   Flags.setNoFPExcept(true);
8125 
8126   SDLoc SL(Op);
8127   SDValue LHS = Op.getOperand(0);
8128   SDValue RHS = Op.getOperand(1);
8129 
8130   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8131 
8132   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8133 
8134   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8135                                           {RHS, RHS, LHS}, Flags);
8136   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8137                                         {LHS, RHS, LHS}, Flags);
8138 
8139   // Denominator is scaled to not be denormal, so using rcp is ok.
8140   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8141                                   DenominatorScaled, Flags);
8142   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8143                                      DenominatorScaled, Flags);
8144 
8145   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8146                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8147                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8148   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8149 
8150   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8151 
8152   if (!HasFP32Denormals) {
8153     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8154     // lowering. The chain dependence is insufficient, and we need glue. We do
8155     // not need the glue variants in a strictfp function.
8156 
8157     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8158 
8159     SDNode *EnableDenorm;
8160     if (Subtarget->hasDenormModeInst()) {
8161       const SDValue EnableDenormValue =
8162           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8163 
8164       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8165                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8166     } else {
8167       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8168                                                         SL, MVT::i32);
8169       EnableDenorm =
8170           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8171                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8172     }
8173 
8174     SDValue Ops[3] = {
8175       NegDivScale0,
8176       SDValue(EnableDenorm, 0),
8177       SDValue(EnableDenorm, 1)
8178     };
8179 
8180     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8181   }
8182 
8183   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8184                              ApproxRcp, One, NegDivScale0, Flags);
8185 
8186   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8187                              ApproxRcp, Fma0, Flags);
8188 
8189   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8190                            Fma1, Fma1, Flags);
8191 
8192   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8193                              NumeratorScaled, Mul, Flags);
8194 
8195   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8196                              Fma2, Fma1, Mul, Fma2, Flags);
8197 
8198   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8199                              NumeratorScaled, Fma3, Flags);
8200 
8201   if (!HasFP32Denormals) {
8202     SDNode *DisableDenorm;
8203     if (Subtarget->hasDenormModeInst()) {
8204       const SDValue DisableDenormValue =
8205           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8206 
8207       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8208                                   Fma4.getValue(1), DisableDenormValue,
8209                                   Fma4.getValue(2)).getNode();
8210     } else {
8211       const SDValue DisableDenormValue =
8212           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8213 
8214       DisableDenorm = DAG.getMachineNode(
8215           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8216           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8217     }
8218 
8219     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8220                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8221     DAG.setRoot(OutputChain);
8222   }
8223 
8224   SDValue Scale = NumeratorScaled.getValue(1);
8225   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8226                              {Fma4, Fma1, Fma3, Scale}, Flags);
8227 
8228   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8229 }
8230 
8231 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8232   if (DAG.getTarget().Options.UnsafeFPMath)
8233     return lowerFastUnsafeFDIV(Op, DAG);
8234 
8235   SDLoc SL(Op);
8236   SDValue X = Op.getOperand(0);
8237   SDValue Y = Op.getOperand(1);
8238 
8239   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8240 
8241   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8242 
8243   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8244 
8245   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8246 
8247   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8248 
8249   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8250 
8251   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8252 
8253   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8254 
8255   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8256 
8257   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8258   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8259 
8260   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8261                              NegDivScale0, Mul, DivScale1);
8262 
8263   SDValue Scale;
8264 
8265   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8266     // Workaround a hardware bug on SI where the condition output from div_scale
8267     // is not usable.
8268 
8269     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8270 
8271     // Figure out if the scale to use for div_fmas.
8272     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8273     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8274     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8275     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8276 
8277     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8278     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8279 
8280     SDValue Scale0Hi
8281       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8282     SDValue Scale1Hi
8283       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8284 
8285     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8286     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8287     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8288   } else {
8289     Scale = DivScale1.getValue(1);
8290   }
8291 
8292   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8293                              Fma4, Fma3, Mul, Scale);
8294 
8295   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8296 }
8297 
8298 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8299   EVT VT = Op.getValueType();
8300 
8301   if (VT == MVT::f32)
8302     return LowerFDIV32(Op, DAG);
8303 
8304   if (VT == MVT::f64)
8305     return LowerFDIV64(Op, DAG);
8306 
8307   if (VT == MVT::f16)
8308     return LowerFDIV16(Op, DAG);
8309 
8310   llvm_unreachable("Unexpected type for fdiv");
8311 }
8312 
8313 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8314   SDLoc DL(Op);
8315   StoreSDNode *Store = cast<StoreSDNode>(Op);
8316   EVT VT = Store->getMemoryVT();
8317 
8318   if (VT == MVT::i1) {
8319     return DAG.getTruncStore(Store->getChain(), DL,
8320        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8321        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8322   }
8323 
8324   assert(VT.isVector() &&
8325          Store->getValue().getValueType().getScalarType() == MVT::i32);
8326 
8327   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8328                                       VT, *Store->getMemOperand())) {
8329     return expandUnalignedStore(Store, DAG);
8330   }
8331 
8332   unsigned AS = Store->getAddressSpace();
8333   if (Subtarget->hasLDSMisalignedBug() &&
8334       AS == AMDGPUAS::FLAT_ADDRESS &&
8335       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8336     return SplitVectorStore(Op, DAG);
8337   }
8338 
8339   MachineFunction &MF = DAG.getMachineFunction();
8340   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8341   // If there is a possibilty that flat instruction access scratch memory
8342   // then we need to use the same legalization rules we use for private.
8343   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8344       !Subtarget->hasMultiDwordFlatScratchAddressing())
8345     AS = MFI->hasFlatScratchInit() ?
8346          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8347 
8348   unsigned NumElements = VT.getVectorNumElements();
8349   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8350       AS == AMDGPUAS::FLAT_ADDRESS) {
8351     if (NumElements > 4)
8352       return SplitVectorStore(Op, DAG);
8353     // v3 stores not supported on SI.
8354     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8355       return SplitVectorStore(Op, DAG);
8356     return SDValue();
8357   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8358     switch (Subtarget->getMaxPrivateElementSize()) {
8359     case 4:
8360       return scalarizeVectorStore(Store, DAG);
8361     case 8:
8362       if (NumElements > 2)
8363         return SplitVectorStore(Op, DAG);
8364       return SDValue();
8365     case 16:
8366       if (NumElements > 4 || NumElements == 3)
8367         return SplitVectorStore(Op, DAG);
8368       return SDValue();
8369     default:
8370       llvm_unreachable("unsupported private_element_size");
8371     }
8372   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8373     // Use ds_write_b128 if possible.
8374     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8375         VT.getStoreSize() == 16 && NumElements != 3)
8376       return SDValue();
8377 
8378     if (NumElements > 2)
8379       return SplitVectorStore(Op, DAG);
8380 
8381     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8382     // address is negative, then the instruction is incorrectly treated as
8383     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8384     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8385     // store later in the SILoadStoreOptimizer.
8386     if (!Subtarget->hasUsableDSOffset() &&
8387         NumElements == 2 && VT.getStoreSize() == 8 &&
8388         Store->getAlignment() < 8) {
8389       return SplitVectorStore(Op, DAG);
8390     }
8391 
8392     return SDValue();
8393   } else {
8394     llvm_unreachable("unhandled address space");
8395   }
8396 }
8397 
8398 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8399   SDLoc DL(Op);
8400   EVT VT = Op.getValueType();
8401   SDValue Arg = Op.getOperand(0);
8402   SDValue TrigVal;
8403 
8404   // Propagate fast-math flags so that the multiply we introduce can be folded
8405   // if Arg is already the result of a multiply by constant.
8406   auto Flags = Op->getFlags();
8407 
8408   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8409 
8410   if (Subtarget->hasTrigReducedRange()) {
8411     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8412     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8413   } else {
8414     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8415   }
8416 
8417   switch (Op.getOpcode()) {
8418   case ISD::FCOS:
8419     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8420   case ISD::FSIN:
8421     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8422   default:
8423     llvm_unreachable("Wrong trig opcode");
8424   }
8425 }
8426 
8427 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8428   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8429   assert(AtomicNode->isCompareAndSwap());
8430   unsigned AS = AtomicNode->getAddressSpace();
8431 
8432   // No custom lowering required for local address space
8433   if (!isFlatGlobalAddrSpace(AS))
8434     return Op;
8435 
8436   // Non-local address space requires custom lowering for atomic compare
8437   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8438   SDLoc DL(Op);
8439   SDValue ChainIn = Op.getOperand(0);
8440   SDValue Addr = Op.getOperand(1);
8441   SDValue Old = Op.getOperand(2);
8442   SDValue New = Op.getOperand(3);
8443   EVT VT = Op.getValueType();
8444   MVT SimpleVT = VT.getSimpleVT();
8445   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8446 
8447   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8448   SDValue Ops[] = { ChainIn, Addr, NewOld };
8449 
8450   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8451                                  Ops, VT, AtomicNode->getMemOperand());
8452 }
8453 
8454 //===----------------------------------------------------------------------===//
8455 // Custom DAG optimizations
8456 //===----------------------------------------------------------------------===//
8457 
8458 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8459                                                      DAGCombinerInfo &DCI) const {
8460   EVT VT = N->getValueType(0);
8461   EVT ScalarVT = VT.getScalarType();
8462   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8463     return SDValue();
8464 
8465   SelectionDAG &DAG = DCI.DAG;
8466   SDLoc DL(N);
8467 
8468   SDValue Src = N->getOperand(0);
8469   EVT SrcVT = Src.getValueType();
8470 
8471   // TODO: We could try to match extracting the higher bytes, which would be
8472   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8473   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8474   // about in practice.
8475   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8476     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8477       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8478       DCI.AddToWorklist(Cvt.getNode());
8479 
8480       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8481       if (ScalarVT != MVT::f32) {
8482         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8483                           DAG.getTargetConstant(0, DL, MVT::i32));
8484       }
8485       return Cvt;
8486     }
8487   }
8488 
8489   return SDValue();
8490 }
8491 
8492 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8493 
8494 // This is a variant of
8495 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8496 //
8497 // The normal DAG combiner will do this, but only if the add has one use since
8498 // that would increase the number of instructions.
8499 //
8500 // This prevents us from seeing a constant offset that can be folded into a
8501 // memory instruction's addressing mode. If we know the resulting add offset of
8502 // a pointer can be folded into an addressing offset, we can replace the pointer
8503 // operand with the add of new constant offset. This eliminates one of the uses,
8504 // and may allow the remaining use to also be simplified.
8505 //
8506 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8507                                                unsigned AddrSpace,
8508                                                EVT MemVT,
8509                                                DAGCombinerInfo &DCI) const {
8510   SDValue N0 = N->getOperand(0);
8511   SDValue N1 = N->getOperand(1);
8512 
8513   // We only do this to handle cases where it's profitable when there are
8514   // multiple uses of the add, so defer to the standard combine.
8515   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8516       N0->hasOneUse())
8517     return SDValue();
8518 
8519   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8520   if (!CN1)
8521     return SDValue();
8522 
8523   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8524   if (!CAdd)
8525     return SDValue();
8526 
8527   // If the resulting offset is too large, we can't fold it into the addressing
8528   // mode offset.
8529   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8530   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8531 
8532   AddrMode AM;
8533   AM.HasBaseReg = true;
8534   AM.BaseOffs = Offset.getSExtValue();
8535   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8536     return SDValue();
8537 
8538   SelectionDAG &DAG = DCI.DAG;
8539   SDLoc SL(N);
8540   EVT VT = N->getValueType(0);
8541 
8542   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8543   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8544 
8545   SDNodeFlags Flags;
8546   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8547                           (N0.getOpcode() == ISD::OR ||
8548                            N0->getFlags().hasNoUnsignedWrap()));
8549 
8550   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8551 }
8552 
8553 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8554                                                   DAGCombinerInfo &DCI) const {
8555   SDValue Ptr = N->getBasePtr();
8556   SelectionDAG &DAG = DCI.DAG;
8557   SDLoc SL(N);
8558 
8559   // TODO: We could also do this for multiplies.
8560   if (Ptr.getOpcode() == ISD::SHL) {
8561     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8562                                           N->getMemoryVT(), DCI);
8563     if (NewPtr) {
8564       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8565 
8566       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8567       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8568     }
8569   }
8570 
8571   return SDValue();
8572 }
8573 
8574 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8575   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8576          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8577          (Opc == ISD::XOR && Val == 0);
8578 }
8579 
8580 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8581 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8582 // integer combine opportunities since most 64-bit operations are decomposed
8583 // this way.  TODO: We won't want this for SALU especially if it is an inline
8584 // immediate.
8585 SDValue SITargetLowering::splitBinaryBitConstantOp(
8586   DAGCombinerInfo &DCI,
8587   const SDLoc &SL,
8588   unsigned Opc, SDValue LHS,
8589   const ConstantSDNode *CRHS) const {
8590   uint64_t Val = CRHS->getZExtValue();
8591   uint32_t ValLo = Lo_32(Val);
8592   uint32_t ValHi = Hi_32(Val);
8593   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8594 
8595     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8596          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8597         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8598     // If we need to materialize a 64-bit immediate, it will be split up later
8599     // anyway. Avoid creating the harder to understand 64-bit immediate
8600     // materialization.
8601     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8602   }
8603 
8604   return SDValue();
8605 }
8606 
8607 // Returns true if argument is a boolean value which is not serialized into
8608 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8609 static bool isBoolSGPR(SDValue V) {
8610   if (V.getValueType() != MVT::i1)
8611     return false;
8612   switch (V.getOpcode()) {
8613   default: break;
8614   case ISD::SETCC:
8615   case ISD::AND:
8616   case ISD::OR:
8617   case ISD::XOR:
8618   case AMDGPUISD::FP_CLASS:
8619     return true;
8620   }
8621   return false;
8622 }
8623 
8624 // If a constant has all zeroes or all ones within each byte return it.
8625 // Otherwise return 0.
8626 static uint32_t getConstantPermuteMask(uint32_t C) {
8627   // 0xff for any zero byte in the mask
8628   uint32_t ZeroByteMask = 0;
8629   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8630   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8631   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8632   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8633   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8634   if ((NonZeroByteMask & C) != NonZeroByteMask)
8635     return 0; // Partial bytes selected.
8636   return C;
8637 }
8638 
8639 // Check if a node selects whole bytes from its operand 0 starting at a byte
8640 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8641 // or -1 if not succeeded.
8642 // Note byte select encoding:
8643 // value 0-3 selects corresponding source byte;
8644 // value 0xc selects zero;
8645 // value 0xff selects 0xff.
8646 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8647   assert(V.getValueSizeInBits() == 32);
8648 
8649   if (V.getNumOperands() != 2)
8650     return ~0;
8651 
8652   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8653   if (!N1)
8654     return ~0;
8655 
8656   uint32_t C = N1->getZExtValue();
8657 
8658   switch (V.getOpcode()) {
8659   default:
8660     break;
8661   case ISD::AND:
8662     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8663       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8664     }
8665     break;
8666 
8667   case ISD::OR:
8668     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8669       return (0x03020100 & ~ConstMask) | ConstMask;
8670     }
8671     break;
8672 
8673   case ISD::SHL:
8674     if (C % 8)
8675       return ~0;
8676 
8677     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8678 
8679   case ISD::SRL:
8680     if (C % 8)
8681       return ~0;
8682 
8683     return uint32_t(0x0c0c0c0c03020100ull >> C);
8684   }
8685 
8686   return ~0;
8687 }
8688 
8689 SDValue SITargetLowering::performAndCombine(SDNode *N,
8690                                             DAGCombinerInfo &DCI) const {
8691   if (DCI.isBeforeLegalize())
8692     return SDValue();
8693 
8694   SelectionDAG &DAG = DCI.DAG;
8695   EVT VT = N->getValueType(0);
8696   SDValue LHS = N->getOperand(0);
8697   SDValue RHS = N->getOperand(1);
8698 
8699 
8700   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8701   if (VT == MVT::i64 && CRHS) {
8702     if (SDValue Split
8703         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8704       return Split;
8705   }
8706 
8707   if (CRHS && VT == MVT::i32) {
8708     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8709     // nb = number of trailing zeroes in mask
8710     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8711     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8712     uint64_t Mask = CRHS->getZExtValue();
8713     unsigned Bits = countPopulation(Mask);
8714     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8715         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8716       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8717         unsigned Shift = CShift->getZExtValue();
8718         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8719         unsigned Offset = NB + Shift;
8720         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8721           SDLoc SL(N);
8722           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8723                                     LHS->getOperand(0),
8724                                     DAG.getConstant(Offset, SL, MVT::i32),
8725                                     DAG.getConstant(Bits, SL, MVT::i32));
8726           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8727           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8728                                     DAG.getValueType(NarrowVT));
8729           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8730                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8731           return Shl;
8732         }
8733       }
8734     }
8735 
8736     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8737     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8738         isa<ConstantSDNode>(LHS.getOperand(2))) {
8739       uint32_t Sel = getConstantPermuteMask(Mask);
8740       if (!Sel)
8741         return SDValue();
8742 
8743       // Select 0xc for all zero bytes
8744       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8745       SDLoc DL(N);
8746       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8747                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8748     }
8749   }
8750 
8751   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8752   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8753   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8754     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8755     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8756 
8757     SDValue X = LHS.getOperand(0);
8758     SDValue Y = RHS.getOperand(0);
8759     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8760       return SDValue();
8761 
8762     if (LCC == ISD::SETO) {
8763       if (X != LHS.getOperand(1))
8764         return SDValue();
8765 
8766       if (RCC == ISD::SETUNE) {
8767         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8768         if (!C1 || !C1->isInfinity() || C1->isNegative())
8769           return SDValue();
8770 
8771         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8772                               SIInstrFlags::N_SUBNORMAL |
8773                               SIInstrFlags::N_ZERO |
8774                               SIInstrFlags::P_ZERO |
8775                               SIInstrFlags::P_SUBNORMAL |
8776                               SIInstrFlags::P_NORMAL;
8777 
8778         static_assert(((~(SIInstrFlags::S_NAN |
8779                           SIInstrFlags::Q_NAN |
8780                           SIInstrFlags::N_INFINITY |
8781                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8782                       "mask not equal");
8783 
8784         SDLoc DL(N);
8785         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8786                            X, DAG.getConstant(Mask, DL, MVT::i32));
8787       }
8788     }
8789   }
8790 
8791   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8792     std::swap(LHS, RHS);
8793 
8794   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8795       RHS.hasOneUse()) {
8796     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8797     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8798     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8799     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8800     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8801         (RHS.getOperand(0) == LHS.getOperand(0) &&
8802          LHS.getOperand(0) == LHS.getOperand(1))) {
8803       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8804       unsigned NewMask = LCC == ISD::SETO ?
8805         Mask->getZExtValue() & ~OrdMask :
8806         Mask->getZExtValue() & OrdMask;
8807 
8808       SDLoc DL(N);
8809       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8810                          DAG.getConstant(NewMask, DL, MVT::i32));
8811     }
8812   }
8813 
8814   if (VT == MVT::i32 &&
8815       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8816     // and x, (sext cc from i1) => select cc, x, 0
8817     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8818       std::swap(LHS, RHS);
8819     if (isBoolSGPR(RHS.getOperand(0)))
8820       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8821                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8822   }
8823 
8824   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8825   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8826   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8827       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8828     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8829     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8830     if (LHSMask != ~0u && RHSMask != ~0u) {
8831       // Canonicalize the expression in an attempt to have fewer unique masks
8832       // and therefore fewer registers used to hold the masks.
8833       if (LHSMask > RHSMask) {
8834         std::swap(LHSMask, RHSMask);
8835         std::swap(LHS, RHS);
8836       }
8837 
8838       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8839       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8840       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8841       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8842 
8843       // Check of we need to combine values from two sources within a byte.
8844       if (!(LHSUsedLanes & RHSUsedLanes) &&
8845           // If we select high and lower word keep it for SDWA.
8846           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8847           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8848         // Each byte in each mask is either selector mask 0-3, or has higher
8849         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8850         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8851         // mask which is not 0xff wins. By anding both masks we have a correct
8852         // result except that 0x0c shall be corrected to give 0x0c only.
8853         uint32_t Mask = LHSMask & RHSMask;
8854         for (unsigned I = 0; I < 32; I += 8) {
8855           uint32_t ByteSel = 0xff << I;
8856           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8857             Mask &= (0x0c << I) & 0xffffffff;
8858         }
8859 
8860         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8861         // or 0x0c.
8862         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8863         SDLoc DL(N);
8864 
8865         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8866                            LHS.getOperand(0), RHS.getOperand(0),
8867                            DAG.getConstant(Sel, DL, MVT::i32));
8868       }
8869     }
8870   }
8871 
8872   return SDValue();
8873 }
8874 
8875 SDValue SITargetLowering::performOrCombine(SDNode *N,
8876                                            DAGCombinerInfo &DCI) const {
8877   SelectionDAG &DAG = DCI.DAG;
8878   SDValue LHS = N->getOperand(0);
8879   SDValue RHS = N->getOperand(1);
8880 
8881   EVT VT = N->getValueType(0);
8882   if (VT == MVT::i1) {
8883     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8884     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8885         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8886       SDValue Src = LHS.getOperand(0);
8887       if (Src != RHS.getOperand(0))
8888         return SDValue();
8889 
8890       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8891       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8892       if (!CLHS || !CRHS)
8893         return SDValue();
8894 
8895       // Only 10 bits are used.
8896       static const uint32_t MaxMask = 0x3ff;
8897 
8898       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8899       SDLoc DL(N);
8900       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8901                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8902     }
8903 
8904     return SDValue();
8905   }
8906 
8907   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8908   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8909       LHS.getOpcode() == AMDGPUISD::PERM &&
8910       isa<ConstantSDNode>(LHS.getOperand(2))) {
8911     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8912     if (!Sel)
8913       return SDValue();
8914 
8915     Sel |= LHS.getConstantOperandVal(2);
8916     SDLoc DL(N);
8917     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8918                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8919   }
8920 
8921   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8922   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8923   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8924       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8925     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8926     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8927     if (LHSMask != ~0u && RHSMask != ~0u) {
8928       // Canonicalize the expression in an attempt to have fewer unique masks
8929       // and therefore fewer registers used to hold the masks.
8930       if (LHSMask > RHSMask) {
8931         std::swap(LHSMask, RHSMask);
8932         std::swap(LHS, RHS);
8933       }
8934 
8935       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8936       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8937       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8938       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8939 
8940       // Check of we need to combine values from two sources within a byte.
8941       if (!(LHSUsedLanes & RHSUsedLanes) &&
8942           // If we select high and lower word keep it for SDWA.
8943           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8944           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8945         // Kill zero bytes selected by other mask. Zero value is 0xc.
8946         LHSMask &= ~RHSUsedLanes;
8947         RHSMask &= ~LHSUsedLanes;
8948         // Add 4 to each active LHS lane
8949         LHSMask |= LHSUsedLanes & 0x04040404;
8950         // Combine masks
8951         uint32_t Sel = LHSMask | RHSMask;
8952         SDLoc DL(N);
8953 
8954         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8955                            LHS.getOperand(0), RHS.getOperand(0),
8956                            DAG.getConstant(Sel, DL, MVT::i32));
8957       }
8958     }
8959   }
8960 
8961   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
8962     return SDValue();
8963 
8964   // TODO: This could be a generic combine with a predicate for extracting the
8965   // high half of an integer being free.
8966 
8967   // (or i64:x, (zero_extend i32:y)) ->
8968   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8969   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8970       RHS.getOpcode() != ISD::ZERO_EXTEND)
8971     std::swap(LHS, RHS);
8972 
8973   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8974     SDValue ExtSrc = RHS.getOperand(0);
8975     EVT SrcVT = ExtSrc.getValueType();
8976     if (SrcVT == MVT::i32) {
8977       SDLoc SL(N);
8978       SDValue LowLHS, HiBits;
8979       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8980       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8981 
8982       DCI.AddToWorklist(LowOr.getNode());
8983       DCI.AddToWorklist(HiBits.getNode());
8984 
8985       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8986                                 LowOr, HiBits);
8987       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8988     }
8989   }
8990 
8991   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8992   if (CRHS) {
8993     if (SDValue Split
8994           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8995       return Split;
8996   }
8997 
8998   return SDValue();
8999 }
9000 
9001 SDValue SITargetLowering::performXorCombine(SDNode *N,
9002                                             DAGCombinerInfo &DCI) const {
9003   EVT VT = N->getValueType(0);
9004   if (VT != MVT::i64)
9005     return SDValue();
9006 
9007   SDValue LHS = N->getOperand(0);
9008   SDValue RHS = N->getOperand(1);
9009 
9010   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9011   if (CRHS) {
9012     if (SDValue Split
9013           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9014       return Split;
9015   }
9016 
9017   return SDValue();
9018 }
9019 
9020 // Instructions that will be lowered with a final instruction that zeros the
9021 // high result bits.
9022 // XXX - probably only need to list legal operations.
9023 static bool fp16SrcZerosHighBits(unsigned Opc) {
9024   switch (Opc) {
9025   case ISD::FADD:
9026   case ISD::FSUB:
9027   case ISD::FMUL:
9028   case ISD::FDIV:
9029   case ISD::FREM:
9030   case ISD::FMA:
9031   case ISD::FMAD:
9032   case ISD::FCANONICALIZE:
9033   case ISD::FP_ROUND:
9034   case ISD::UINT_TO_FP:
9035   case ISD::SINT_TO_FP:
9036   case ISD::FABS:
9037     // Fabs is lowered to a bit operation, but it's an and which will clear the
9038     // high bits anyway.
9039   case ISD::FSQRT:
9040   case ISD::FSIN:
9041   case ISD::FCOS:
9042   case ISD::FPOWI:
9043   case ISD::FPOW:
9044   case ISD::FLOG:
9045   case ISD::FLOG2:
9046   case ISD::FLOG10:
9047   case ISD::FEXP:
9048   case ISD::FEXP2:
9049   case ISD::FCEIL:
9050   case ISD::FTRUNC:
9051   case ISD::FRINT:
9052   case ISD::FNEARBYINT:
9053   case ISD::FROUND:
9054   case ISD::FFLOOR:
9055   case ISD::FMINNUM:
9056   case ISD::FMAXNUM:
9057   case AMDGPUISD::FRACT:
9058   case AMDGPUISD::CLAMP:
9059   case AMDGPUISD::COS_HW:
9060   case AMDGPUISD::SIN_HW:
9061   case AMDGPUISD::FMIN3:
9062   case AMDGPUISD::FMAX3:
9063   case AMDGPUISD::FMED3:
9064   case AMDGPUISD::FMAD_FTZ:
9065   case AMDGPUISD::RCP:
9066   case AMDGPUISD::RSQ:
9067   case AMDGPUISD::RCP_IFLAG:
9068   case AMDGPUISD::LDEXP:
9069     return true;
9070   default:
9071     // fcopysign, select and others may be lowered to 32-bit bit operations
9072     // which don't zero the high bits.
9073     return false;
9074   }
9075 }
9076 
9077 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9078                                                    DAGCombinerInfo &DCI) const {
9079   if (!Subtarget->has16BitInsts() ||
9080       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9081     return SDValue();
9082 
9083   EVT VT = N->getValueType(0);
9084   if (VT != MVT::i32)
9085     return SDValue();
9086 
9087   SDValue Src = N->getOperand(0);
9088   if (Src.getValueType() != MVT::i16)
9089     return SDValue();
9090 
9091   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9092   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9093   if (Src.getOpcode() == ISD::BITCAST) {
9094     SDValue BCSrc = Src.getOperand(0);
9095     if (BCSrc.getValueType() == MVT::f16 &&
9096         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9097       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9098   }
9099 
9100   return SDValue();
9101 }
9102 
9103 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9104                                                         DAGCombinerInfo &DCI)
9105                                                         const {
9106   SDValue Src = N->getOperand(0);
9107   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9108 
9109   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9110       VTSign->getVT() == MVT::i8) ||
9111       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9112       VTSign->getVT() == MVT::i16)) &&
9113       Src.hasOneUse()) {
9114     auto *M = cast<MemSDNode>(Src);
9115     SDValue Ops[] = {
9116       Src.getOperand(0), // Chain
9117       Src.getOperand(1), // rsrc
9118       Src.getOperand(2), // vindex
9119       Src.getOperand(3), // voffset
9120       Src.getOperand(4), // soffset
9121       Src.getOperand(5), // offset
9122       Src.getOperand(6),
9123       Src.getOperand(7)
9124     };
9125     // replace with BUFFER_LOAD_BYTE/SHORT
9126     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9127                                          Src.getOperand(0).getValueType());
9128     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9129                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9130     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9131                                                           ResList,
9132                                                           Ops, M->getMemoryVT(),
9133                                                           M->getMemOperand());
9134     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9135                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9136   }
9137   return SDValue();
9138 }
9139 
9140 SDValue SITargetLowering::performClassCombine(SDNode *N,
9141                                               DAGCombinerInfo &DCI) const {
9142   SelectionDAG &DAG = DCI.DAG;
9143   SDValue Mask = N->getOperand(1);
9144 
9145   // fp_class x, 0 -> false
9146   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9147     if (CMask->isNullValue())
9148       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9149   }
9150 
9151   if (N->getOperand(0).isUndef())
9152     return DAG.getUNDEF(MVT::i1);
9153 
9154   return SDValue();
9155 }
9156 
9157 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9158                                             DAGCombinerInfo &DCI) const {
9159   EVT VT = N->getValueType(0);
9160   SDValue N0 = N->getOperand(0);
9161 
9162   if (N0.isUndef())
9163     return N0;
9164 
9165   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9166                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9167     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9168                            N->getFlags());
9169   }
9170 
9171   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9172     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9173                            N0.getOperand(0), N->getFlags());
9174   }
9175 
9176   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9177 }
9178 
9179 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9180                                        unsigned MaxDepth) const {
9181   unsigned Opcode = Op.getOpcode();
9182   if (Opcode == ISD::FCANONICALIZE)
9183     return true;
9184 
9185   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9186     auto F = CFP->getValueAPF();
9187     if (F.isNaN() && F.isSignaling())
9188       return false;
9189     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9190   }
9191 
9192   // If source is a result of another standard FP operation it is already in
9193   // canonical form.
9194   if (MaxDepth == 0)
9195     return false;
9196 
9197   switch (Opcode) {
9198   // These will flush denorms if required.
9199   case ISD::FADD:
9200   case ISD::FSUB:
9201   case ISD::FMUL:
9202   case ISD::FCEIL:
9203   case ISD::FFLOOR:
9204   case ISD::FMA:
9205   case ISD::FMAD:
9206   case ISD::FSQRT:
9207   case ISD::FDIV:
9208   case ISD::FREM:
9209   case ISD::FP_ROUND:
9210   case ISD::FP_EXTEND:
9211   case AMDGPUISD::FMUL_LEGACY:
9212   case AMDGPUISD::FMAD_FTZ:
9213   case AMDGPUISD::RCP:
9214   case AMDGPUISD::RSQ:
9215   case AMDGPUISD::RSQ_CLAMP:
9216   case AMDGPUISD::RCP_LEGACY:
9217   case AMDGPUISD::RCP_IFLAG:
9218   case AMDGPUISD::TRIG_PREOP:
9219   case AMDGPUISD::DIV_SCALE:
9220   case AMDGPUISD::DIV_FMAS:
9221   case AMDGPUISD::DIV_FIXUP:
9222   case AMDGPUISD::FRACT:
9223   case AMDGPUISD::LDEXP:
9224   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9225   case AMDGPUISD::CVT_F32_UBYTE0:
9226   case AMDGPUISD::CVT_F32_UBYTE1:
9227   case AMDGPUISD::CVT_F32_UBYTE2:
9228   case AMDGPUISD::CVT_F32_UBYTE3:
9229     return true;
9230 
9231   // It can/will be lowered or combined as a bit operation.
9232   // Need to check their input recursively to handle.
9233   case ISD::FNEG:
9234   case ISD::FABS:
9235   case ISD::FCOPYSIGN:
9236     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9237 
9238   case ISD::FSIN:
9239   case ISD::FCOS:
9240   case ISD::FSINCOS:
9241     return Op.getValueType().getScalarType() != MVT::f16;
9242 
9243   case ISD::FMINNUM:
9244   case ISD::FMAXNUM:
9245   case ISD::FMINNUM_IEEE:
9246   case ISD::FMAXNUM_IEEE:
9247   case AMDGPUISD::CLAMP:
9248   case AMDGPUISD::FMED3:
9249   case AMDGPUISD::FMAX3:
9250   case AMDGPUISD::FMIN3: {
9251     // FIXME: Shouldn't treat the generic operations different based these.
9252     // However, we aren't really required to flush the result from
9253     // minnum/maxnum..
9254 
9255     // snans will be quieted, so we only need to worry about denormals.
9256     if (Subtarget->supportsMinMaxDenormModes() ||
9257         denormalsEnabledForType(DAG, Op.getValueType()))
9258       return true;
9259 
9260     // Flushing may be required.
9261     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9262     // targets need to check their input recursively.
9263 
9264     // FIXME: Does this apply with clamp? It's implemented with max.
9265     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9266       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9267         return false;
9268     }
9269 
9270     return true;
9271   }
9272   case ISD::SELECT: {
9273     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9274            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9275   }
9276   case ISD::BUILD_VECTOR: {
9277     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9278       SDValue SrcOp = Op.getOperand(i);
9279       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9280         return false;
9281     }
9282 
9283     return true;
9284   }
9285   case ISD::EXTRACT_VECTOR_ELT:
9286   case ISD::EXTRACT_SUBVECTOR: {
9287     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9288   }
9289   case ISD::INSERT_VECTOR_ELT: {
9290     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9291            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9292   }
9293   case ISD::UNDEF:
9294     // Could be anything.
9295     return false;
9296 
9297   case ISD::BITCAST: {
9298     // Hack round the mess we make when legalizing extract_vector_elt
9299     SDValue Src = Op.getOperand(0);
9300     if (Src.getValueType() == MVT::i16 &&
9301         Src.getOpcode() == ISD::TRUNCATE) {
9302       SDValue TruncSrc = Src.getOperand(0);
9303       if (TruncSrc.getValueType() == MVT::i32 &&
9304           TruncSrc.getOpcode() == ISD::BITCAST &&
9305           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9306         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9307       }
9308     }
9309 
9310     return false;
9311   }
9312   case ISD::INTRINSIC_WO_CHAIN: {
9313     unsigned IntrinsicID
9314       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9315     // TODO: Handle more intrinsics
9316     switch (IntrinsicID) {
9317     case Intrinsic::amdgcn_cvt_pkrtz:
9318     case Intrinsic::amdgcn_cubeid:
9319     case Intrinsic::amdgcn_frexp_mant:
9320     case Intrinsic::amdgcn_fdot2:
9321     case Intrinsic::amdgcn_rcp:
9322     case Intrinsic::amdgcn_rsq:
9323     case Intrinsic::amdgcn_rsq_clamp:
9324     case Intrinsic::amdgcn_rcp_legacy:
9325     case Intrinsic::amdgcn_rsq_legacy:
9326       return true;
9327     default:
9328       break;
9329     }
9330 
9331     LLVM_FALLTHROUGH;
9332   }
9333   default:
9334     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9335            DAG.isKnownNeverSNaN(Op);
9336   }
9337 
9338   llvm_unreachable("invalid operation");
9339 }
9340 
9341 // Constant fold canonicalize.
9342 SDValue SITargetLowering::getCanonicalConstantFP(
9343   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9344   // Flush denormals to 0 if not enabled.
9345   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9346     return DAG.getConstantFP(0.0, SL, VT);
9347 
9348   if (C.isNaN()) {
9349     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9350     if (C.isSignaling()) {
9351       // Quiet a signaling NaN.
9352       // FIXME: Is this supposed to preserve payload bits?
9353       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9354     }
9355 
9356     // Make sure it is the canonical NaN bitpattern.
9357     //
9358     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9359     // immediate?
9360     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9361       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9362   }
9363 
9364   // Already canonical.
9365   return DAG.getConstantFP(C, SL, VT);
9366 }
9367 
9368 static bool vectorEltWillFoldAway(SDValue Op) {
9369   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9370 }
9371 
9372 SDValue SITargetLowering::performFCanonicalizeCombine(
9373   SDNode *N,
9374   DAGCombinerInfo &DCI) const {
9375   SelectionDAG &DAG = DCI.DAG;
9376   SDValue N0 = N->getOperand(0);
9377   EVT VT = N->getValueType(0);
9378 
9379   // fcanonicalize undef -> qnan
9380   if (N0.isUndef()) {
9381     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9382     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9383   }
9384 
9385   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9386     EVT VT = N->getValueType(0);
9387     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9388   }
9389 
9390   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9391   //                                                   (fcanonicalize k)
9392   //
9393   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9394 
9395   // TODO: This could be better with wider vectors that will be split to v2f16,
9396   // and to consider uses since there aren't that many packed operations.
9397   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9398       isTypeLegal(MVT::v2f16)) {
9399     SDLoc SL(N);
9400     SDValue NewElts[2];
9401     SDValue Lo = N0.getOperand(0);
9402     SDValue Hi = N0.getOperand(1);
9403     EVT EltVT = Lo.getValueType();
9404 
9405     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9406       for (unsigned I = 0; I != 2; ++I) {
9407         SDValue Op = N0.getOperand(I);
9408         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9409           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9410                                               CFP->getValueAPF());
9411         } else if (Op.isUndef()) {
9412           // Handled below based on what the other operand is.
9413           NewElts[I] = Op;
9414         } else {
9415           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9416         }
9417       }
9418 
9419       // If one half is undef, and one is constant, perfer a splat vector rather
9420       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9421       // cheaper to use and may be free with a packed operation.
9422       if (NewElts[0].isUndef()) {
9423         if (isa<ConstantFPSDNode>(NewElts[1]))
9424           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9425             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9426       }
9427 
9428       if (NewElts[1].isUndef()) {
9429         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9430           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9431       }
9432 
9433       return DAG.getBuildVector(VT, SL, NewElts);
9434     }
9435   }
9436 
9437   unsigned SrcOpc = N0.getOpcode();
9438 
9439   // If it's free to do so, push canonicalizes further up the source, which may
9440   // find a canonical source.
9441   //
9442   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9443   // sNaNs.
9444   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9445     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9446     if (CRHS && N0.hasOneUse()) {
9447       SDLoc SL(N);
9448       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9449                                    N0.getOperand(0));
9450       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9451       DCI.AddToWorklist(Canon0.getNode());
9452 
9453       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9454     }
9455   }
9456 
9457   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9458 }
9459 
9460 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9461   switch (Opc) {
9462   case ISD::FMAXNUM:
9463   case ISD::FMAXNUM_IEEE:
9464     return AMDGPUISD::FMAX3;
9465   case ISD::SMAX:
9466     return AMDGPUISD::SMAX3;
9467   case ISD::UMAX:
9468     return AMDGPUISD::UMAX3;
9469   case ISD::FMINNUM:
9470   case ISD::FMINNUM_IEEE:
9471     return AMDGPUISD::FMIN3;
9472   case ISD::SMIN:
9473     return AMDGPUISD::SMIN3;
9474   case ISD::UMIN:
9475     return AMDGPUISD::UMIN3;
9476   default:
9477     llvm_unreachable("Not a min/max opcode");
9478   }
9479 }
9480 
9481 SDValue SITargetLowering::performIntMed3ImmCombine(
9482   SelectionDAG &DAG, const SDLoc &SL,
9483   SDValue Op0, SDValue Op1, bool Signed) const {
9484   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9485   if (!K1)
9486     return SDValue();
9487 
9488   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9489   if (!K0)
9490     return SDValue();
9491 
9492   if (Signed) {
9493     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9494       return SDValue();
9495   } else {
9496     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9497       return SDValue();
9498   }
9499 
9500   EVT VT = K0->getValueType(0);
9501   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9502   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9503     return DAG.getNode(Med3Opc, SL, VT,
9504                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9505   }
9506 
9507   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9508   MVT NVT = MVT::i32;
9509   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9510 
9511   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9512   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9513   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9514 
9515   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9516   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9517 }
9518 
9519 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9520   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9521     return C;
9522 
9523   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9524     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9525       return C;
9526   }
9527 
9528   return nullptr;
9529 }
9530 
9531 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9532                                                   const SDLoc &SL,
9533                                                   SDValue Op0,
9534                                                   SDValue Op1) const {
9535   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9536   if (!K1)
9537     return SDValue();
9538 
9539   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9540   if (!K0)
9541     return SDValue();
9542 
9543   // Ordered >= (although NaN inputs should have folded away by now).
9544   if (K0->getValueAPF() > K1->getValueAPF())
9545     return SDValue();
9546 
9547   const MachineFunction &MF = DAG.getMachineFunction();
9548   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9549 
9550   // TODO: Check IEEE bit enabled?
9551   EVT VT = Op0.getValueType();
9552   if (Info->getMode().DX10Clamp) {
9553     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9554     // hardware fmed3 behavior converting to a min.
9555     // FIXME: Should this be allowing -0.0?
9556     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9557       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9558   }
9559 
9560   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9561   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9562     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9563     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9564     // then give the other result, which is different from med3 with a NaN
9565     // input.
9566     SDValue Var = Op0.getOperand(0);
9567     if (!DAG.isKnownNeverSNaN(Var))
9568       return SDValue();
9569 
9570     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9571 
9572     if ((!K0->hasOneUse() ||
9573          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9574         (!K1->hasOneUse() ||
9575          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9576       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9577                          Var, SDValue(K0, 0), SDValue(K1, 0));
9578     }
9579   }
9580 
9581   return SDValue();
9582 }
9583 
9584 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9585                                                DAGCombinerInfo &DCI) const {
9586   SelectionDAG &DAG = DCI.DAG;
9587 
9588   EVT VT = N->getValueType(0);
9589   unsigned Opc = N->getOpcode();
9590   SDValue Op0 = N->getOperand(0);
9591   SDValue Op1 = N->getOperand(1);
9592 
9593   // Only do this if the inner op has one use since this will just increases
9594   // register pressure for no benefit.
9595 
9596   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9597       !VT.isVector() &&
9598       (VT == MVT::i32 || VT == MVT::f32 ||
9599        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9600     // max(max(a, b), c) -> max3(a, b, c)
9601     // min(min(a, b), c) -> min3(a, b, c)
9602     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9603       SDLoc DL(N);
9604       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9605                          DL,
9606                          N->getValueType(0),
9607                          Op0.getOperand(0),
9608                          Op0.getOperand(1),
9609                          Op1);
9610     }
9611 
9612     // Try commuted.
9613     // max(a, max(b, c)) -> max3(a, b, c)
9614     // min(a, min(b, c)) -> min3(a, b, c)
9615     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9616       SDLoc DL(N);
9617       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9618                          DL,
9619                          N->getValueType(0),
9620                          Op0,
9621                          Op1.getOperand(0),
9622                          Op1.getOperand(1));
9623     }
9624   }
9625 
9626   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9627   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9628     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9629       return Med3;
9630   }
9631 
9632   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9633     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9634       return Med3;
9635   }
9636 
9637   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9638   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9639        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9640        (Opc == AMDGPUISD::FMIN_LEGACY &&
9641         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9642       (VT == MVT::f32 || VT == MVT::f64 ||
9643        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9644        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9645       Op0.hasOneUse()) {
9646     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9647       return Res;
9648   }
9649 
9650   return SDValue();
9651 }
9652 
9653 static bool isClampZeroToOne(SDValue A, SDValue B) {
9654   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9655     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9656       // FIXME: Should this be allowing -0.0?
9657       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9658              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9659     }
9660   }
9661 
9662   return false;
9663 }
9664 
9665 // FIXME: Should only worry about snans for version with chain.
9666 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9667                                               DAGCombinerInfo &DCI) const {
9668   EVT VT = N->getValueType(0);
9669   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9670   // NaNs. With a NaN input, the order of the operands may change the result.
9671 
9672   SelectionDAG &DAG = DCI.DAG;
9673   SDLoc SL(N);
9674 
9675   SDValue Src0 = N->getOperand(0);
9676   SDValue Src1 = N->getOperand(1);
9677   SDValue Src2 = N->getOperand(2);
9678 
9679   if (isClampZeroToOne(Src0, Src1)) {
9680     // const_a, const_b, x -> clamp is safe in all cases including signaling
9681     // nans.
9682     // FIXME: Should this be allowing -0.0?
9683     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9684   }
9685 
9686   const MachineFunction &MF = DAG.getMachineFunction();
9687   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9688 
9689   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9690   // handling no dx10-clamp?
9691   if (Info->getMode().DX10Clamp) {
9692     // If NaNs is clamped to 0, we are free to reorder the inputs.
9693 
9694     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9695       std::swap(Src0, Src1);
9696 
9697     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9698       std::swap(Src1, Src2);
9699 
9700     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9701       std::swap(Src0, Src1);
9702 
9703     if (isClampZeroToOne(Src1, Src2))
9704       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9705   }
9706 
9707   return SDValue();
9708 }
9709 
9710 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9711                                                  DAGCombinerInfo &DCI) const {
9712   SDValue Src0 = N->getOperand(0);
9713   SDValue Src1 = N->getOperand(1);
9714   if (Src0.isUndef() && Src1.isUndef())
9715     return DCI.DAG.getUNDEF(N->getValueType(0));
9716   return SDValue();
9717 }
9718 
9719 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9720 // expanded into a set of cmp/select instructions.
9721 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9722                                                 unsigned NumElem,
9723                                                 bool IsDivergentIdx) {
9724   if (UseDivergentRegisterIndexing)
9725     return false;
9726 
9727   unsigned VecSize = EltSize * NumElem;
9728 
9729   // Sub-dword vectors of size 2 dword or less have better implementation.
9730   if (VecSize <= 64 && EltSize < 32)
9731     return false;
9732 
9733   // Always expand the rest of sub-dword instructions, otherwise it will be
9734   // lowered via memory.
9735   if (EltSize < 32)
9736     return true;
9737 
9738   // Always do this if var-idx is divergent, otherwise it will become a loop.
9739   if (IsDivergentIdx)
9740     return true;
9741 
9742   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9743   unsigned NumInsts = NumElem /* Number of compares */ +
9744                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9745   return NumInsts <= 16;
9746 }
9747 
9748 static bool shouldExpandVectorDynExt(SDNode *N) {
9749   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9750   if (isa<ConstantSDNode>(Idx))
9751     return false;
9752 
9753   SDValue Vec = N->getOperand(0);
9754   EVT VecVT = Vec.getValueType();
9755   EVT EltVT = VecVT.getVectorElementType();
9756   unsigned EltSize = EltVT.getSizeInBits();
9757   unsigned NumElem = VecVT.getVectorNumElements();
9758 
9759   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9760                                                     Idx->isDivergent());
9761 }
9762 
9763 SDValue SITargetLowering::performExtractVectorEltCombine(
9764   SDNode *N, DAGCombinerInfo &DCI) const {
9765   SDValue Vec = N->getOperand(0);
9766   SelectionDAG &DAG = DCI.DAG;
9767 
9768   EVT VecVT = Vec.getValueType();
9769   EVT EltVT = VecVT.getVectorElementType();
9770 
9771   if ((Vec.getOpcode() == ISD::FNEG ||
9772        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9773     SDLoc SL(N);
9774     EVT EltVT = N->getValueType(0);
9775     SDValue Idx = N->getOperand(1);
9776     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9777                               Vec.getOperand(0), Idx);
9778     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9779   }
9780 
9781   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9782   //    =>
9783   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9784   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9785   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9786   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9787     SDLoc SL(N);
9788     EVT EltVT = N->getValueType(0);
9789     SDValue Idx = N->getOperand(1);
9790     unsigned Opc = Vec.getOpcode();
9791 
9792     switch(Opc) {
9793     default:
9794       break;
9795       // TODO: Support other binary operations.
9796     case ISD::FADD:
9797     case ISD::FSUB:
9798     case ISD::FMUL:
9799     case ISD::ADD:
9800     case ISD::UMIN:
9801     case ISD::UMAX:
9802     case ISD::SMIN:
9803     case ISD::SMAX:
9804     case ISD::FMAXNUM:
9805     case ISD::FMINNUM:
9806     case ISD::FMAXNUM_IEEE:
9807     case ISD::FMINNUM_IEEE: {
9808       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9809                                  Vec.getOperand(0), Idx);
9810       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9811                                  Vec.getOperand(1), Idx);
9812 
9813       DCI.AddToWorklist(Elt0.getNode());
9814       DCI.AddToWorklist(Elt1.getNode());
9815       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9816     }
9817     }
9818   }
9819 
9820   unsigned VecSize = VecVT.getSizeInBits();
9821   unsigned EltSize = EltVT.getSizeInBits();
9822 
9823   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9824   if (::shouldExpandVectorDynExt(N)) {
9825     SDLoc SL(N);
9826     SDValue Idx = N->getOperand(1);
9827     SDValue V;
9828     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9829       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9830       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9831       if (I == 0)
9832         V = Elt;
9833       else
9834         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9835     }
9836     return V;
9837   }
9838 
9839   if (!DCI.isBeforeLegalize())
9840     return SDValue();
9841 
9842   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9843   // elements. This exposes more load reduction opportunities by replacing
9844   // multiple small extract_vector_elements with a single 32-bit extract.
9845   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9846   if (isa<MemSDNode>(Vec) &&
9847       EltSize <= 16 &&
9848       EltVT.isByteSized() &&
9849       VecSize > 32 &&
9850       VecSize % 32 == 0 &&
9851       Idx) {
9852     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9853 
9854     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9855     unsigned EltIdx = BitIndex / 32;
9856     unsigned LeftoverBitIdx = BitIndex % 32;
9857     SDLoc SL(N);
9858 
9859     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9860     DCI.AddToWorklist(Cast.getNode());
9861 
9862     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9863                               DAG.getConstant(EltIdx, SL, MVT::i32));
9864     DCI.AddToWorklist(Elt.getNode());
9865     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9866                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9867     DCI.AddToWorklist(Srl.getNode());
9868 
9869     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9870     DCI.AddToWorklist(Trunc.getNode());
9871     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9872   }
9873 
9874   return SDValue();
9875 }
9876 
9877 SDValue
9878 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9879                                                 DAGCombinerInfo &DCI) const {
9880   SDValue Vec = N->getOperand(0);
9881   SDValue Idx = N->getOperand(2);
9882   EVT VecVT = Vec.getValueType();
9883   EVT EltVT = VecVT.getVectorElementType();
9884 
9885   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9886   // => BUILD_VECTOR n x select (e, const-idx)
9887   if (!::shouldExpandVectorDynExt(N))
9888     return SDValue();
9889 
9890   SelectionDAG &DAG = DCI.DAG;
9891   SDLoc SL(N);
9892   SDValue Ins = N->getOperand(1);
9893   EVT IdxVT = Idx.getValueType();
9894 
9895   SmallVector<SDValue, 16> Ops;
9896   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9897     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9898     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9899     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9900     Ops.push_back(V);
9901   }
9902 
9903   return DAG.getBuildVector(VecVT, SL, Ops);
9904 }
9905 
9906 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9907                                           const SDNode *N0,
9908                                           const SDNode *N1) const {
9909   EVT VT = N0->getValueType(0);
9910 
9911   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9912   // support denormals ever.
9913   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9914        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9915         getSubtarget()->hasMadF16())) &&
9916        isOperationLegal(ISD::FMAD, VT))
9917     return ISD::FMAD;
9918 
9919   const TargetOptions &Options = DAG.getTarget().Options;
9920   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9921        (N0->getFlags().hasAllowContract() &&
9922         N1->getFlags().hasAllowContract())) &&
9923       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9924     return ISD::FMA;
9925   }
9926 
9927   return 0;
9928 }
9929 
9930 // For a reassociatable opcode perform:
9931 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9932 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9933                                                SelectionDAG &DAG) const {
9934   EVT VT = N->getValueType(0);
9935   if (VT != MVT::i32 && VT != MVT::i64)
9936     return SDValue();
9937 
9938   unsigned Opc = N->getOpcode();
9939   SDValue Op0 = N->getOperand(0);
9940   SDValue Op1 = N->getOperand(1);
9941 
9942   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9943     return SDValue();
9944 
9945   if (Op0->isDivergent())
9946     std::swap(Op0, Op1);
9947 
9948   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9949     return SDValue();
9950 
9951   SDValue Op2 = Op1.getOperand(1);
9952   Op1 = Op1.getOperand(0);
9953   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9954     return SDValue();
9955 
9956   if (Op1->isDivergent())
9957     std::swap(Op1, Op2);
9958 
9959   // If either operand is constant this will conflict with
9960   // DAGCombiner::ReassociateOps().
9961   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9962       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9963     return SDValue();
9964 
9965   SDLoc SL(N);
9966   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9967   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9968 }
9969 
9970 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9971                            EVT VT,
9972                            SDValue N0, SDValue N1, SDValue N2,
9973                            bool Signed) {
9974   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9975   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9976   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9977   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9978 }
9979 
9980 SDValue SITargetLowering::performAddCombine(SDNode *N,
9981                                             DAGCombinerInfo &DCI) const {
9982   SelectionDAG &DAG = DCI.DAG;
9983   EVT VT = N->getValueType(0);
9984   SDLoc SL(N);
9985   SDValue LHS = N->getOperand(0);
9986   SDValue RHS = N->getOperand(1);
9987 
9988   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9989       && Subtarget->hasMad64_32() &&
9990       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9991       VT.getScalarSizeInBits() <= 64) {
9992     if (LHS.getOpcode() != ISD::MUL)
9993       std::swap(LHS, RHS);
9994 
9995     SDValue MulLHS = LHS.getOperand(0);
9996     SDValue MulRHS = LHS.getOperand(1);
9997     SDValue AddRHS = RHS;
9998 
9999     // TODO: Maybe restrict if SGPR inputs.
10000     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10001         numBitsUnsigned(MulRHS, DAG) <= 32) {
10002       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10003       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10004       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10005       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10006     }
10007 
10008     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10009       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10010       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10011       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10012       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10013     }
10014 
10015     return SDValue();
10016   }
10017 
10018   if (SDValue V = reassociateScalarOps(N, DAG)) {
10019     return V;
10020   }
10021 
10022   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10023     return SDValue();
10024 
10025   // add x, zext (setcc) => addcarry x, 0, setcc
10026   // add x, sext (setcc) => subcarry x, 0, setcc
10027   unsigned Opc = LHS.getOpcode();
10028   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10029       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10030     std::swap(RHS, LHS);
10031 
10032   Opc = RHS.getOpcode();
10033   switch (Opc) {
10034   default: break;
10035   case ISD::ZERO_EXTEND:
10036   case ISD::SIGN_EXTEND:
10037   case ISD::ANY_EXTEND: {
10038     auto Cond = RHS.getOperand(0);
10039     // If this won't be a real VOPC output, we would still need to insert an
10040     // extra instruction anyway.
10041     if (!isBoolSGPR(Cond))
10042       break;
10043     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10044     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10045     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10046     return DAG.getNode(Opc, SL, VTList, Args);
10047   }
10048   case ISD::ADDCARRY: {
10049     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10050     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10051     if (!C || C->getZExtValue() != 0) break;
10052     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10053     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10054   }
10055   }
10056   return SDValue();
10057 }
10058 
10059 SDValue SITargetLowering::performSubCombine(SDNode *N,
10060                                             DAGCombinerInfo &DCI) const {
10061   SelectionDAG &DAG = DCI.DAG;
10062   EVT VT = N->getValueType(0);
10063 
10064   if (VT != MVT::i32)
10065     return SDValue();
10066 
10067   SDLoc SL(N);
10068   SDValue LHS = N->getOperand(0);
10069   SDValue RHS = N->getOperand(1);
10070 
10071   // sub x, zext (setcc) => subcarry x, 0, setcc
10072   // sub x, sext (setcc) => addcarry x, 0, setcc
10073   unsigned Opc = RHS.getOpcode();
10074   switch (Opc) {
10075   default: break;
10076   case ISD::ZERO_EXTEND:
10077   case ISD::SIGN_EXTEND:
10078   case ISD::ANY_EXTEND: {
10079     auto Cond = RHS.getOperand(0);
10080     // If this won't be a real VOPC output, we would still need to insert an
10081     // extra instruction anyway.
10082     if (!isBoolSGPR(Cond))
10083       break;
10084     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10085     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10086     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10087     return DAG.getNode(Opc, SL, VTList, Args);
10088   }
10089   }
10090 
10091   if (LHS.getOpcode() == ISD::SUBCARRY) {
10092     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10093     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10094     if (!C || !C->isNullValue())
10095       return SDValue();
10096     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10097     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10098   }
10099   return SDValue();
10100 }
10101 
10102 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10103   DAGCombinerInfo &DCI) const {
10104 
10105   if (N->getValueType(0) != MVT::i32)
10106     return SDValue();
10107 
10108   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10109   if (!C || C->getZExtValue() != 0)
10110     return SDValue();
10111 
10112   SelectionDAG &DAG = DCI.DAG;
10113   SDValue LHS = N->getOperand(0);
10114 
10115   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10116   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10117   unsigned LHSOpc = LHS.getOpcode();
10118   unsigned Opc = N->getOpcode();
10119   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10120       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10121     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10122     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10123   }
10124   return SDValue();
10125 }
10126 
10127 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10128                                              DAGCombinerInfo &DCI) const {
10129   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10130     return SDValue();
10131 
10132   SelectionDAG &DAG = DCI.DAG;
10133   EVT VT = N->getValueType(0);
10134 
10135   SDLoc SL(N);
10136   SDValue LHS = N->getOperand(0);
10137   SDValue RHS = N->getOperand(1);
10138 
10139   // These should really be instruction patterns, but writing patterns with
10140   // source modiifiers is a pain.
10141 
10142   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10143   if (LHS.getOpcode() == ISD::FADD) {
10144     SDValue A = LHS.getOperand(0);
10145     if (A == LHS.getOperand(1)) {
10146       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10147       if (FusedOp != 0) {
10148         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10149         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10150       }
10151     }
10152   }
10153 
10154   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10155   if (RHS.getOpcode() == ISD::FADD) {
10156     SDValue A = RHS.getOperand(0);
10157     if (A == RHS.getOperand(1)) {
10158       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10159       if (FusedOp != 0) {
10160         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10161         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10162       }
10163     }
10164   }
10165 
10166   return SDValue();
10167 }
10168 
10169 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10170                                              DAGCombinerInfo &DCI) const {
10171   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10172     return SDValue();
10173 
10174   SelectionDAG &DAG = DCI.DAG;
10175   SDLoc SL(N);
10176   EVT VT = N->getValueType(0);
10177   assert(!VT.isVector());
10178 
10179   // Try to get the fneg to fold into the source modifier. This undoes generic
10180   // DAG combines and folds them into the mad.
10181   //
10182   // Only do this if we are not trying to support denormals. v_mad_f32 does
10183   // not support denormals ever.
10184   SDValue LHS = N->getOperand(0);
10185   SDValue RHS = N->getOperand(1);
10186   if (LHS.getOpcode() == ISD::FADD) {
10187     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10188     SDValue A = LHS.getOperand(0);
10189     if (A == LHS.getOperand(1)) {
10190       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10191       if (FusedOp != 0){
10192         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10193         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10194 
10195         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10196       }
10197     }
10198   }
10199 
10200   if (RHS.getOpcode() == ISD::FADD) {
10201     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10202 
10203     SDValue A = RHS.getOperand(0);
10204     if (A == RHS.getOperand(1)) {
10205       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10206       if (FusedOp != 0){
10207         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10208         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10209       }
10210     }
10211   }
10212 
10213   return SDValue();
10214 }
10215 
10216 SDValue SITargetLowering::performFMACombine(SDNode *N,
10217                                             DAGCombinerInfo &DCI) const {
10218   SelectionDAG &DAG = DCI.DAG;
10219   EVT VT = N->getValueType(0);
10220   SDLoc SL(N);
10221 
10222   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10223     return SDValue();
10224 
10225   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10226   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10227   SDValue Op1 = N->getOperand(0);
10228   SDValue Op2 = N->getOperand(1);
10229   SDValue FMA = N->getOperand(2);
10230 
10231   if (FMA.getOpcode() != ISD::FMA ||
10232       Op1.getOpcode() != ISD::FP_EXTEND ||
10233       Op2.getOpcode() != ISD::FP_EXTEND)
10234     return SDValue();
10235 
10236   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10237   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10238   // is sufficient to allow generaing fdot2.
10239   const TargetOptions &Options = DAG.getTarget().Options;
10240   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10241       (N->getFlags().hasAllowContract() &&
10242        FMA->getFlags().hasAllowContract())) {
10243     Op1 = Op1.getOperand(0);
10244     Op2 = Op2.getOperand(0);
10245     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10246         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10247       return SDValue();
10248 
10249     SDValue Vec1 = Op1.getOperand(0);
10250     SDValue Idx1 = Op1.getOperand(1);
10251     SDValue Vec2 = Op2.getOperand(0);
10252 
10253     SDValue FMAOp1 = FMA.getOperand(0);
10254     SDValue FMAOp2 = FMA.getOperand(1);
10255     SDValue FMAAcc = FMA.getOperand(2);
10256 
10257     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10258         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10259       return SDValue();
10260 
10261     FMAOp1 = FMAOp1.getOperand(0);
10262     FMAOp2 = FMAOp2.getOperand(0);
10263     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10264         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10265       return SDValue();
10266 
10267     SDValue Vec3 = FMAOp1.getOperand(0);
10268     SDValue Vec4 = FMAOp2.getOperand(0);
10269     SDValue Idx2 = FMAOp1.getOperand(1);
10270 
10271     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10272         // Idx1 and Idx2 cannot be the same.
10273         Idx1 == Idx2)
10274       return SDValue();
10275 
10276     if (Vec1 == Vec2 || Vec3 == Vec4)
10277       return SDValue();
10278 
10279     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10280       return SDValue();
10281 
10282     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10283         (Vec1 == Vec4 && Vec2 == Vec3)) {
10284       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10285                          DAG.getTargetConstant(0, SL, MVT::i1));
10286     }
10287   }
10288   return SDValue();
10289 }
10290 
10291 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10292                                               DAGCombinerInfo &DCI) const {
10293   SelectionDAG &DAG = DCI.DAG;
10294   SDLoc SL(N);
10295 
10296   SDValue LHS = N->getOperand(0);
10297   SDValue RHS = N->getOperand(1);
10298   EVT VT = LHS.getValueType();
10299   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10300 
10301   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10302   if (!CRHS) {
10303     CRHS = dyn_cast<ConstantSDNode>(LHS);
10304     if (CRHS) {
10305       std::swap(LHS, RHS);
10306       CC = getSetCCSwappedOperands(CC);
10307     }
10308   }
10309 
10310   if (CRHS) {
10311     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10312         isBoolSGPR(LHS.getOperand(0))) {
10313       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10314       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10315       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10316       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10317       if ((CRHS->isAllOnesValue() &&
10318            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10319           (CRHS->isNullValue() &&
10320            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10321         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10322                            DAG.getConstant(-1, SL, MVT::i1));
10323       if ((CRHS->isAllOnesValue() &&
10324            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10325           (CRHS->isNullValue() &&
10326            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10327         return LHS.getOperand(0);
10328     }
10329 
10330     uint64_t CRHSVal = CRHS->getZExtValue();
10331     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10332         LHS.getOpcode() == ISD::SELECT &&
10333         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10334         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10335         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10336         isBoolSGPR(LHS.getOperand(0))) {
10337       // Given CT != FT:
10338       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10339       // setcc (select cc, CT, CF), CF, ne => cc
10340       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10341       // setcc (select cc, CT, CF), CT, eq => cc
10342       uint64_t CT = LHS.getConstantOperandVal(1);
10343       uint64_t CF = LHS.getConstantOperandVal(2);
10344 
10345       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10346           (CT == CRHSVal && CC == ISD::SETNE))
10347         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10348                            DAG.getConstant(-1, SL, MVT::i1));
10349       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10350           (CT == CRHSVal && CC == ISD::SETEQ))
10351         return LHS.getOperand(0);
10352     }
10353   }
10354 
10355   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10356                                            VT != MVT::f16))
10357     return SDValue();
10358 
10359   // Match isinf/isfinite pattern
10360   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10361   // (fcmp one (fabs x), inf) -> (fp_class x,
10362   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10363   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10364     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10365     if (!CRHS)
10366       return SDValue();
10367 
10368     const APFloat &APF = CRHS->getValueAPF();
10369     if (APF.isInfinity() && !APF.isNegative()) {
10370       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10371                                  SIInstrFlags::N_INFINITY;
10372       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10373                                     SIInstrFlags::P_ZERO |
10374                                     SIInstrFlags::N_NORMAL |
10375                                     SIInstrFlags::P_NORMAL |
10376                                     SIInstrFlags::N_SUBNORMAL |
10377                                     SIInstrFlags::P_SUBNORMAL;
10378       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10379       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10380                          DAG.getConstant(Mask, SL, MVT::i32));
10381     }
10382   }
10383 
10384   return SDValue();
10385 }
10386 
10387 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10388                                                      DAGCombinerInfo &DCI) const {
10389   SelectionDAG &DAG = DCI.DAG;
10390   SDLoc SL(N);
10391   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10392 
10393   SDValue Src = N->getOperand(0);
10394   SDValue Shift = N->getOperand(0);
10395 
10396   // TODO: Extend type shouldn't matter (assuming legal types).
10397   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10398     Shift = Shift.getOperand(0);
10399 
10400   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10401     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10402     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10403     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10404     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10405     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10406     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10407       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10408                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10409 
10410       unsigned ShiftOffset = 8 * Offset;
10411       if (Shift.getOpcode() == ISD::SHL)
10412         ShiftOffset -= C->getZExtValue();
10413       else
10414         ShiftOffset += C->getZExtValue();
10415 
10416       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10417         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10418                            MVT::f32, Shift);
10419       }
10420     }
10421   }
10422 
10423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10424   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10425   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10426     // We simplified Src. If this node is not dead, visit it again so it is
10427     // folded properly.
10428     if (N->getOpcode() != ISD::DELETED_NODE)
10429       DCI.AddToWorklist(N);
10430     return SDValue(N, 0);
10431   }
10432 
10433   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10434   if (SDValue DemandedSrc =
10435           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10436     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10437 
10438   return SDValue();
10439 }
10440 
10441 SDValue SITargetLowering::performClampCombine(SDNode *N,
10442                                               DAGCombinerInfo &DCI) const {
10443   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10444   if (!CSrc)
10445     return SDValue();
10446 
10447   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10448   const APFloat &F = CSrc->getValueAPF();
10449   APFloat Zero = APFloat::getZero(F.getSemantics());
10450   if (F < Zero ||
10451       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10452     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10453   }
10454 
10455   APFloat One(F.getSemantics(), "1.0");
10456   if (F > One)
10457     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10458 
10459   return SDValue(CSrc, 0);
10460 }
10461 
10462 
10463 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10464                                             DAGCombinerInfo &DCI) const {
10465   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10466     return SDValue();
10467   switch (N->getOpcode()) {
10468   default:
10469     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10470   case ISD::ADD:
10471     return performAddCombine(N, DCI);
10472   case ISD::SUB:
10473     return performSubCombine(N, DCI);
10474   case ISD::ADDCARRY:
10475   case ISD::SUBCARRY:
10476     return performAddCarrySubCarryCombine(N, DCI);
10477   case ISD::FADD:
10478     return performFAddCombine(N, DCI);
10479   case ISD::FSUB:
10480     return performFSubCombine(N, DCI);
10481   case ISD::SETCC:
10482     return performSetCCCombine(N, DCI);
10483   case ISD::FMAXNUM:
10484   case ISD::FMINNUM:
10485   case ISD::FMAXNUM_IEEE:
10486   case ISD::FMINNUM_IEEE:
10487   case ISD::SMAX:
10488   case ISD::SMIN:
10489   case ISD::UMAX:
10490   case ISD::UMIN:
10491   case AMDGPUISD::FMIN_LEGACY:
10492   case AMDGPUISD::FMAX_LEGACY:
10493     return performMinMaxCombine(N, DCI);
10494   case ISD::FMA:
10495     return performFMACombine(N, DCI);
10496   case ISD::LOAD: {
10497     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10498       return Widended;
10499     LLVM_FALLTHROUGH;
10500   }
10501   case ISD::STORE:
10502   case ISD::ATOMIC_LOAD:
10503   case ISD::ATOMIC_STORE:
10504   case ISD::ATOMIC_CMP_SWAP:
10505   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10506   case ISD::ATOMIC_SWAP:
10507   case ISD::ATOMIC_LOAD_ADD:
10508   case ISD::ATOMIC_LOAD_SUB:
10509   case ISD::ATOMIC_LOAD_AND:
10510   case ISD::ATOMIC_LOAD_OR:
10511   case ISD::ATOMIC_LOAD_XOR:
10512   case ISD::ATOMIC_LOAD_NAND:
10513   case ISD::ATOMIC_LOAD_MIN:
10514   case ISD::ATOMIC_LOAD_MAX:
10515   case ISD::ATOMIC_LOAD_UMIN:
10516   case ISD::ATOMIC_LOAD_UMAX:
10517   case ISD::ATOMIC_LOAD_FADD:
10518   case AMDGPUISD::ATOMIC_INC:
10519   case AMDGPUISD::ATOMIC_DEC:
10520   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10521   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10522     if (DCI.isBeforeLegalize())
10523       break;
10524     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10525   case ISD::AND:
10526     return performAndCombine(N, DCI);
10527   case ISD::OR:
10528     return performOrCombine(N, DCI);
10529   case ISD::XOR:
10530     return performXorCombine(N, DCI);
10531   case ISD::ZERO_EXTEND:
10532     return performZeroExtendCombine(N, DCI);
10533   case ISD::SIGN_EXTEND_INREG:
10534     return performSignExtendInRegCombine(N , DCI);
10535   case AMDGPUISD::FP_CLASS:
10536     return performClassCombine(N, DCI);
10537   case ISD::FCANONICALIZE:
10538     return performFCanonicalizeCombine(N, DCI);
10539   case AMDGPUISD::RCP:
10540     return performRcpCombine(N, DCI);
10541   case AMDGPUISD::FRACT:
10542   case AMDGPUISD::RSQ:
10543   case AMDGPUISD::RCP_LEGACY:
10544   case AMDGPUISD::RCP_IFLAG:
10545   case AMDGPUISD::RSQ_CLAMP:
10546   case AMDGPUISD::LDEXP: {
10547     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10548     SDValue Src = N->getOperand(0);
10549     if (Src.isUndef())
10550       return Src;
10551     break;
10552   }
10553   case ISD::SINT_TO_FP:
10554   case ISD::UINT_TO_FP:
10555     return performUCharToFloatCombine(N, DCI);
10556   case AMDGPUISD::CVT_F32_UBYTE0:
10557   case AMDGPUISD::CVT_F32_UBYTE1:
10558   case AMDGPUISD::CVT_F32_UBYTE2:
10559   case AMDGPUISD::CVT_F32_UBYTE3:
10560     return performCvtF32UByteNCombine(N, DCI);
10561   case AMDGPUISD::FMED3:
10562     return performFMed3Combine(N, DCI);
10563   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10564     return performCvtPkRTZCombine(N, DCI);
10565   case AMDGPUISD::CLAMP:
10566     return performClampCombine(N, DCI);
10567   case ISD::SCALAR_TO_VECTOR: {
10568     SelectionDAG &DAG = DCI.DAG;
10569     EVT VT = N->getValueType(0);
10570 
10571     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10572     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10573       SDLoc SL(N);
10574       SDValue Src = N->getOperand(0);
10575       EVT EltVT = Src.getValueType();
10576       if (EltVT == MVT::f16)
10577         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10578 
10579       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10580       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10581     }
10582 
10583     break;
10584   }
10585   case ISD::EXTRACT_VECTOR_ELT:
10586     return performExtractVectorEltCombine(N, DCI);
10587   case ISD::INSERT_VECTOR_ELT:
10588     return performInsertVectorEltCombine(N, DCI);
10589   }
10590   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10591 }
10592 
10593 /// Helper function for adjustWritemask
10594 static unsigned SubIdx2Lane(unsigned Idx) {
10595   switch (Idx) {
10596   default: return 0;
10597   case AMDGPU::sub0: return 0;
10598   case AMDGPU::sub1: return 1;
10599   case AMDGPU::sub2: return 2;
10600   case AMDGPU::sub3: return 3;
10601   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10602   }
10603 }
10604 
10605 /// Adjust the writemask of MIMG instructions
10606 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10607                                           SelectionDAG &DAG) const {
10608   unsigned Opcode = Node->getMachineOpcode();
10609 
10610   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10611   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10612   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10613     return Node; // not implemented for D16
10614 
10615   SDNode *Users[5] = { nullptr };
10616   unsigned Lane = 0;
10617   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10618   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10619   unsigned NewDmask = 0;
10620   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10621   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10622   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10623                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10624   unsigned TFCLane = 0;
10625   bool HasChain = Node->getNumValues() > 1;
10626 
10627   if (OldDmask == 0) {
10628     // These are folded out, but on the chance it happens don't assert.
10629     return Node;
10630   }
10631 
10632   unsigned OldBitsSet = countPopulation(OldDmask);
10633   // Work out which is the TFE/LWE lane if that is enabled.
10634   if (UsesTFC) {
10635     TFCLane = OldBitsSet;
10636   }
10637 
10638   // Try to figure out the used register components
10639   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10640        I != E; ++I) {
10641 
10642     // Don't look at users of the chain.
10643     if (I.getUse().getResNo() != 0)
10644       continue;
10645 
10646     // Abort if we can't understand the usage
10647     if (!I->isMachineOpcode() ||
10648         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10649       return Node;
10650 
10651     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10652     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10653     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10654     // set, etc.
10655     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10656 
10657     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10658     if (UsesTFC && Lane == TFCLane) {
10659       Users[Lane] = *I;
10660     } else {
10661       // Set which texture component corresponds to the lane.
10662       unsigned Comp;
10663       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10664         Comp = countTrailingZeros(Dmask);
10665         Dmask &= ~(1 << Comp);
10666       }
10667 
10668       // Abort if we have more than one user per component.
10669       if (Users[Lane])
10670         return Node;
10671 
10672       Users[Lane] = *I;
10673       NewDmask |= 1 << Comp;
10674     }
10675   }
10676 
10677   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10678   bool NoChannels = !NewDmask;
10679   if (NoChannels) {
10680     if (!UsesTFC) {
10681       // No uses of the result and not using TFC. Then do nothing.
10682       return Node;
10683     }
10684     // If the original dmask has one channel - then nothing to do
10685     if (OldBitsSet == 1)
10686       return Node;
10687     // Use an arbitrary dmask - required for the instruction to work
10688     NewDmask = 1;
10689   }
10690   // Abort if there's no change
10691   if (NewDmask == OldDmask)
10692     return Node;
10693 
10694   unsigned BitsSet = countPopulation(NewDmask);
10695 
10696   // Check for TFE or LWE - increase the number of channels by one to account
10697   // for the extra return value
10698   // This will need adjustment for D16 if this is also included in
10699   // adjustWriteMask (this function) but at present D16 are excluded.
10700   unsigned NewChannels = BitsSet + UsesTFC;
10701 
10702   int NewOpcode =
10703       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10704   assert(NewOpcode != -1 &&
10705          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10706          "failed to find equivalent MIMG op");
10707 
10708   // Adjust the writemask in the node
10709   SmallVector<SDValue, 12> Ops;
10710   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10711   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10712   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10713 
10714   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10715 
10716   MVT ResultVT = NewChannels == 1 ?
10717     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10718                            NewChannels == 5 ? 8 : NewChannels);
10719   SDVTList NewVTList = HasChain ?
10720     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10721 
10722 
10723   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10724                                               NewVTList, Ops);
10725 
10726   if (HasChain) {
10727     // Update chain.
10728     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10729     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10730   }
10731 
10732   if (NewChannels == 1) {
10733     assert(Node->hasNUsesOfValue(1, 0));
10734     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10735                                       SDLoc(Node), Users[Lane]->getValueType(0),
10736                                       SDValue(NewNode, 0));
10737     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10738     return nullptr;
10739   }
10740 
10741   // Update the users of the node with the new indices
10742   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10743     SDNode *User = Users[i];
10744     if (!User) {
10745       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10746       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10747       if (i || !NoChannels)
10748         continue;
10749     } else {
10750       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10751       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10752     }
10753 
10754     switch (Idx) {
10755     default: break;
10756     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10757     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10758     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10759     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10760     }
10761   }
10762 
10763   DAG.RemoveDeadNode(Node);
10764   return nullptr;
10765 }
10766 
10767 static bool isFrameIndexOp(SDValue Op) {
10768   if (Op.getOpcode() == ISD::AssertZext)
10769     Op = Op.getOperand(0);
10770 
10771   return isa<FrameIndexSDNode>(Op);
10772 }
10773 
10774 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10775 /// with frame index operands.
10776 /// LLVM assumes that inputs are to these instructions are registers.
10777 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10778                                                         SelectionDAG &DAG) const {
10779   if (Node->getOpcode() == ISD::CopyToReg) {
10780     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10781     SDValue SrcVal = Node->getOperand(2);
10782 
10783     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10784     // to try understanding copies to physical registers.
10785     if (SrcVal.getValueType() == MVT::i1 &&
10786         Register::isPhysicalRegister(DestReg->getReg())) {
10787       SDLoc SL(Node);
10788       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10789       SDValue VReg = DAG.getRegister(
10790         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10791 
10792       SDNode *Glued = Node->getGluedNode();
10793       SDValue ToVReg
10794         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10795                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10796       SDValue ToResultReg
10797         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10798                            VReg, ToVReg.getValue(1));
10799       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10800       DAG.RemoveDeadNode(Node);
10801       return ToResultReg.getNode();
10802     }
10803   }
10804 
10805   SmallVector<SDValue, 8> Ops;
10806   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10807     if (!isFrameIndexOp(Node->getOperand(i))) {
10808       Ops.push_back(Node->getOperand(i));
10809       continue;
10810     }
10811 
10812     SDLoc DL(Node);
10813     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10814                                      Node->getOperand(i).getValueType(),
10815                                      Node->getOperand(i)), 0));
10816   }
10817 
10818   return DAG.UpdateNodeOperands(Node, Ops);
10819 }
10820 
10821 /// Fold the instructions after selecting them.
10822 /// Returns null if users were already updated.
10823 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10824                                           SelectionDAG &DAG) const {
10825   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10826   unsigned Opcode = Node->getMachineOpcode();
10827 
10828   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10829       !TII->isGather4(Opcode)) {
10830     return adjustWritemask(Node, DAG);
10831   }
10832 
10833   if (Opcode == AMDGPU::INSERT_SUBREG ||
10834       Opcode == AMDGPU::REG_SEQUENCE) {
10835     legalizeTargetIndependentNode(Node, DAG);
10836     return Node;
10837   }
10838 
10839   switch (Opcode) {
10840   case AMDGPU::V_DIV_SCALE_F32:
10841   case AMDGPU::V_DIV_SCALE_F64: {
10842     // Satisfy the operand register constraint when one of the inputs is
10843     // undefined. Ordinarily each undef value will have its own implicit_def of
10844     // a vreg, so force these to use a single register.
10845     SDValue Src0 = Node->getOperand(0);
10846     SDValue Src1 = Node->getOperand(1);
10847     SDValue Src2 = Node->getOperand(2);
10848 
10849     if ((Src0.isMachineOpcode() &&
10850          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10851         (Src0 == Src1 || Src0 == Src2))
10852       break;
10853 
10854     MVT VT = Src0.getValueType().getSimpleVT();
10855     const TargetRegisterClass *RC =
10856         getRegClassFor(VT, Src0.getNode()->isDivergent());
10857 
10858     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10859     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10860 
10861     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10862                                       UndefReg, Src0, SDValue());
10863 
10864     // src0 must be the same register as src1 or src2, even if the value is
10865     // undefined, so make sure we don't violate this constraint.
10866     if (Src0.isMachineOpcode() &&
10867         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10868       if (Src1.isMachineOpcode() &&
10869           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10870         Src0 = Src1;
10871       else if (Src2.isMachineOpcode() &&
10872                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10873         Src0 = Src2;
10874       else {
10875         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10876         Src0 = UndefReg;
10877         Src1 = UndefReg;
10878       }
10879     } else
10880       break;
10881 
10882     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10883     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10884       Ops.push_back(Node->getOperand(I));
10885 
10886     Ops.push_back(ImpDef.getValue(1));
10887     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10888   }
10889   default:
10890     break;
10891   }
10892 
10893   return Node;
10894 }
10895 
10896 /// Assign the register class depending on the number of
10897 /// bits set in the writemask
10898 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10899                                                      SDNode *Node) const {
10900   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10901 
10902   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10903 
10904   if (TII->isVOP3(MI.getOpcode())) {
10905     // Make sure constant bus requirements are respected.
10906     TII->legalizeOperandsVOP3(MRI, MI);
10907 
10908     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10909     // This saves a chain-copy of registers and better ballance register
10910     // use between vgpr and agpr as agpr tuples tend to be big.
10911     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10912       unsigned Opc = MI.getOpcode();
10913       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10914       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10915                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10916         if (I == -1)
10917           break;
10918         MachineOperand &Op = MI.getOperand(I);
10919         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10920              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10921             !Register::isVirtualRegister(Op.getReg()) ||
10922             !TRI->isAGPR(MRI, Op.getReg()))
10923           continue;
10924         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10925         if (!Src || !Src->isCopy() ||
10926             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10927           continue;
10928         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10929         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10930         // All uses of agpr64 and agpr32 can also accept vgpr except for
10931         // v_accvgpr_read, but we do not produce agpr reads during selection,
10932         // so no use checks are needed.
10933         MRI.setRegClass(Op.getReg(), NewRC);
10934       }
10935     }
10936 
10937     return;
10938   }
10939 
10940   // Replace unused atomics with the no return version.
10941   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10942   if (NoRetAtomicOp != -1) {
10943     if (!Node->hasAnyUseOfValue(0)) {
10944       MI.setDesc(TII->get(NoRetAtomicOp));
10945       MI.RemoveOperand(0);
10946       return;
10947     }
10948 
10949     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10950     // instruction, because the return type of these instructions is a vec2 of
10951     // the memory type, so it can be tied to the input operand.
10952     // This means these instructions always have a use, so we need to add a
10953     // special case to check if the atomic has only one extract_subreg use,
10954     // which itself has no uses.
10955     if ((Node->hasNUsesOfValue(1, 0) &&
10956          Node->use_begin()->isMachineOpcode() &&
10957          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10958          !Node->use_begin()->hasAnyUseOfValue(0))) {
10959       Register Def = MI.getOperand(0).getReg();
10960 
10961       // Change this into a noret atomic.
10962       MI.setDesc(TII->get(NoRetAtomicOp));
10963       MI.RemoveOperand(0);
10964 
10965       // If we only remove the def operand from the atomic instruction, the
10966       // extract_subreg will be left with a use of a vreg without a def.
10967       // So we need to insert an implicit_def to avoid machine verifier
10968       // errors.
10969       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10970               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10971     }
10972     return;
10973   }
10974 }
10975 
10976 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10977                               uint64_t Val) {
10978   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10979   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10980 }
10981 
10982 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10983                                                 const SDLoc &DL,
10984                                                 SDValue Ptr) const {
10985   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10986 
10987   // Build the half of the subregister with the constants before building the
10988   // full 128-bit register. If we are building multiple resource descriptors,
10989   // this will allow CSEing of the 2-component register.
10990   const SDValue Ops0[] = {
10991     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10992     buildSMovImm32(DAG, DL, 0),
10993     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10994     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10995     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10996   };
10997 
10998   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10999                                                 MVT::v2i32, Ops0), 0);
11000 
11001   // Combine the constants and the pointer.
11002   const SDValue Ops1[] = {
11003     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11004     Ptr,
11005     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11006     SubRegHi,
11007     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11008   };
11009 
11010   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11011 }
11012 
11013 /// Return a resource descriptor with the 'Add TID' bit enabled
11014 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11015 ///        of the resource descriptor) to create an offset, which is added to
11016 ///        the resource pointer.
11017 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11018                                            SDValue Ptr, uint32_t RsrcDword1,
11019                                            uint64_t RsrcDword2And3) const {
11020   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11021   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11022   if (RsrcDword1) {
11023     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11024                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11025                     0);
11026   }
11027 
11028   SDValue DataLo = buildSMovImm32(DAG, DL,
11029                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11030   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11031 
11032   const SDValue Ops[] = {
11033     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11034     PtrLo,
11035     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11036     PtrHi,
11037     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11038     DataLo,
11039     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11040     DataHi,
11041     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11042   };
11043 
11044   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11045 }
11046 
11047 //===----------------------------------------------------------------------===//
11048 //                         SI Inline Assembly Support
11049 //===----------------------------------------------------------------------===//
11050 
11051 std::pair<unsigned, const TargetRegisterClass *>
11052 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11053                                                StringRef Constraint,
11054                                                MVT VT) const {
11055   const TargetRegisterClass *RC = nullptr;
11056   if (Constraint.size() == 1) {
11057     const unsigned BitWidth = VT.getSizeInBits();
11058     switch (Constraint[0]) {
11059     default:
11060       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11061     case 's':
11062     case 'r':
11063       switch (BitWidth) {
11064       case 16:
11065         RC = &AMDGPU::SReg_32RegClass;
11066         break;
11067       case 64:
11068         RC = &AMDGPU::SGPR_64RegClass;
11069         break;
11070       default:
11071         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11072         if (!RC)
11073           return std::make_pair(0U, nullptr);
11074         break;
11075       }
11076       break;
11077     case 'v':
11078       switch (BitWidth) {
11079       case 16:
11080         RC = &AMDGPU::VGPR_32RegClass;
11081         break;
11082       default:
11083         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11084         if (!RC)
11085           return std::make_pair(0U, nullptr);
11086         break;
11087       }
11088       break;
11089     case 'a':
11090       if (!Subtarget->hasMAIInsts())
11091         break;
11092       switch (BitWidth) {
11093       case 16:
11094         RC = &AMDGPU::AGPR_32RegClass;
11095         break;
11096       default:
11097         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11098         if (!RC)
11099           return std::make_pair(0U, nullptr);
11100         break;
11101       }
11102       break;
11103     }
11104     // We actually support i128, i16 and f16 as inline parameters
11105     // even if they are not reported as legal
11106     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11107                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11108       return std::make_pair(0U, RC);
11109   }
11110 
11111   if (Constraint.size() > 1) {
11112     if (Constraint[1] == 'v') {
11113       RC = &AMDGPU::VGPR_32RegClass;
11114     } else if (Constraint[1] == 's') {
11115       RC = &AMDGPU::SGPR_32RegClass;
11116     } else if (Constraint[1] == 'a') {
11117       RC = &AMDGPU::AGPR_32RegClass;
11118     }
11119 
11120     if (RC) {
11121       uint32_t Idx;
11122       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11123       if (!Failed && Idx < RC->getNumRegs())
11124         return std::make_pair(RC->getRegister(Idx), RC);
11125     }
11126   }
11127 
11128   // FIXME: Returns VS_32 for physical SGPR constraints
11129   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11130 }
11131 
11132 SITargetLowering::ConstraintType
11133 SITargetLowering::getConstraintType(StringRef Constraint) const {
11134   if (Constraint.size() == 1) {
11135     switch (Constraint[0]) {
11136     default: break;
11137     case 's':
11138     case 'v':
11139     case 'a':
11140       return C_RegisterClass;
11141     case 'A':
11142       return C_Other;
11143     }
11144   }
11145   return TargetLowering::getConstraintType(Constraint);
11146 }
11147 
11148 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11149                                                     std::string &Constraint,
11150                                                     std::vector<SDValue> &Ops,
11151                                                     SelectionDAG &DAG) const {
11152   if (Constraint.length() == 1 && Constraint[0] == 'A') {
11153     LowerAsmOperandForConstraintA(Op, Ops, DAG);
11154   } else {
11155     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11156   }
11157 }
11158 
11159 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op,
11160                                                      std::vector<SDValue> &Ops,
11161                                                      SelectionDAG &DAG) const {
11162   unsigned Size = Op.getScalarValueSizeInBits();
11163   if (Size > 64)
11164     return;
11165 
11166   uint64_t Val;
11167   bool IsConst = false;
11168   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11169     Val = C->getSExtValue();
11170     IsConst = true;
11171   } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11172     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11173     IsConst = true;
11174   } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11175     if (Size != 16 || Op.getNumOperands() != 2)
11176       return;
11177     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11178       return;
11179     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11180       Val = C->getSExtValue();
11181       IsConst = true;
11182     } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11183       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11184       IsConst = true;
11185     }
11186   }
11187 
11188   if (IsConst) {
11189     bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11190     if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11191         (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11192         (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11193       // Clear unused bits of fp constants
11194       if (!AMDGPU::isInlinableIntLiteral(Val)) {
11195         unsigned UnusedBits = 64 - Size;
11196         Val = (Val << UnusedBits) >> UnusedBits;
11197       }
11198       auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64);
11199       Ops.push_back(Res);
11200     }
11201   }
11202 }
11203 
11204 // Figure out which registers should be reserved for stack access. Only after
11205 // the function is legalized do we know all of the non-spill stack objects or if
11206 // calls are present.
11207 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11208   MachineRegisterInfo &MRI = MF.getRegInfo();
11209   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11210   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11211   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11212 
11213   if (Info->isEntryFunction()) {
11214     // Callable functions have fixed registers used for stack access.
11215     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11216   }
11217 
11218   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11219                              Info->getStackPtrOffsetReg()));
11220   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11221     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11222 
11223   // We need to worry about replacing the default register with itself in case
11224   // of MIR testcases missing the MFI.
11225   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11226     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11227 
11228   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11229     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11230 
11231   Info->limitOccupancy(MF);
11232 
11233   if (ST.isWave32() && !MF.empty()) {
11234     // Add VCC_HI def because many instructions marked as imp-use VCC where
11235     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11236     // having a use of undef.
11237 
11238     const SIInstrInfo *TII = ST.getInstrInfo();
11239     DebugLoc DL;
11240 
11241     MachineBasicBlock &MBB = MF.front();
11242     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11243     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11244 
11245     for (auto &MBB : MF) {
11246       for (auto &MI : MBB) {
11247         TII->fixImplicitOperands(MI);
11248       }
11249     }
11250   }
11251 
11252   TargetLoweringBase::finalizeLowering(MF);
11253 
11254   // Allocate a VGPR for future SGPR Spill if
11255   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11256   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11257   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11258       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11259     Info->reserveVGPRforSGPRSpills(MF);
11260 }
11261 
11262 void SITargetLowering::computeKnownBitsForFrameIndex(
11263   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11264   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11265 
11266   // Set the high bits to zero based on the maximum allowed scratch size per
11267   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11268   // calculation won't overflow, so assume the sign bit is never set.
11269   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11270 }
11271 
11272 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11273   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11274   const Align CacheLineAlign = Align(64);
11275 
11276   // Pre-GFX10 target did not benefit from loop alignment
11277   if (!ML || DisableLoopAlignment ||
11278       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11279       getSubtarget()->hasInstFwdPrefetchBug())
11280     return PrefAlign;
11281 
11282   // On GFX10 I$ is 4 x 64 bytes cache lines.
11283   // By default prefetcher keeps one cache line behind and reads two ahead.
11284   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11285   // behind and one ahead.
11286   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11287   // If loop fits 64 bytes it always spans no more than two cache lines and
11288   // does not need an alignment.
11289   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11290   // Else if loop is less or equal 192 bytes we need two lines behind.
11291 
11292   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11293   const MachineBasicBlock *Header = ML->getHeader();
11294   if (Header->getAlignment() != PrefAlign)
11295     return Header->getAlignment(); // Already processed.
11296 
11297   unsigned LoopSize = 0;
11298   for (const MachineBasicBlock *MBB : ML->blocks()) {
11299     // If inner loop block is aligned assume in average half of the alignment
11300     // size to be added as nops.
11301     if (MBB != Header)
11302       LoopSize += MBB->getAlignment().value() / 2;
11303 
11304     for (const MachineInstr &MI : *MBB) {
11305       LoopSize += TII->getInstSizeInBytes(MI);
11306       if (LoopSize > 192)
11307         return PrefAlign;
11308     }
11309   }
11310 
11311   if (LoopSize <= 64)
11312     return PrefAlign;
11313 
11314   if (LoopSize <= 128)
11315     return CacheLineAlign;
11316 
11317   // If any of parent loops is surrounded by prefetch instructions do not
11318   // insert new for inner loop, which would reset parent's settings.
11319   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11320     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11321       auto I = Exit->getFirstNonDebugInstr();
11322       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11323         return CacheLineAlign;
11324     }
11325   }
11326 
11327   MachineBasicBlock *Pre = ML->getLoopPreheader();
11328   MachineBasicBlock *Exit = ML->getExitBlock();
11329 
11330   if (Pre && Exit) {
11331     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11332             TII->get(AMDGPU::S_INST_PREFETCH))
11333       .addImm(1); // prefetch 2 lines behind PC
11334 
11335     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11336             TII->get(AMDGPU::S_INST_PREFETCH))
11337       .addImm(2); // prefetch 1 line behind PC
11338   }
11339 
11340   return CacheLineAlign;
11341 }
11342 
11343 LLVM_ATTRIBUTE_UNUSED
11344 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11345   assert(N->getOpcode() == ISD::CopyFromReg);
11346   do {
11347     // Follow the chain until we find an INLINEASM node.
11348     N = N->getOperand(0).getNode();
11349     if (N->getOpcode() == ISD::INLINEASM ||
11350         N->getOpcode() == ISD::INLINEASM_BR)
11351       return true;
11352   } while (N->getOpcode() == ISD::CopyFromReg);
11353   return false;
11354 }
11355 
11356 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11357   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11358 {
11359   switch (N->getOpcode()) {
11360     case ISD::CopyFromReg:
11361     {
11362       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11363       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11364       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11365       Register Reg = R->getReg();
11366 
11367       // FIXME: Why does this need to consider isLiveIn?
11368       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11369         return !TRI->isSGPRReg(MRI, Reg);
11370 
11371       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11372         return KDA->isDivergent(V);
11373 
11374       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11375       return !TRI->isSGPRReg(MRI, Reg);
11376     }
11377     break;
11378     case ISD::LOAD: {
11379       const LoadSDNode *L = cast<LoadSDNode>(N);
11380       unsigned AS = L->getAddressSpace();
11381       // A flat load may access private memory.
11382       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11383     } break;
11384     case ISD::CALLSEQ_END:
11385     return true;
11386     break;
11387     case ISD::INTRINSIC_WO_CHAIN:
11388     {
11389 
11390     }
11391       return AMDGPU::isIntrinsicSourceOfDivergence(
11392       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11393     case ISD::INTRINSIC_W_CHAIN:
11394       return AMDGPU::isIntrinsicSourceOfDivergence(
11395       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11396   }
11397   return false;
11398 }
11399 
11400 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11401                                                EVT VT) const {
11402   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11403   case MVT::f32:
11404     return hasFP32Denormals(DAG.getMachineFunction());
11405   case MVT::f64:
11406   case MVT::f16:
11407     return hasFP64FP16Denormals(DAG.getMachineFunction());
11408   default:
11409     return false;
11410   }
11411 }
11412 
11413 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11414                                                     const SelectionDAG &DAG,
11415                                                     bool SNaN,
11416                                                     unsigned Depth) const {
11417   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11418     const MachineFunction &MF = DAG.getMachineFunction();
11419     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11420 
11421     if (Info->getMode().DX10Clamp)
11422       return true; // Clamped to 0.
11423     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11424   }
11425 
11426   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11427                                                             SNaN, Depth);
11428 }
11429 
11430 TargetLowering::AtomicExpansionKind
11431 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11432   switch (RMW->getOperation()) {
11433   case AtomicRMWInst::FAdd: {
11434     Type *Ty = RMW->getType();
11435 
11436     // We don't have a way to support 16-bit atomics now, so just leave them
11437     // as-is.
11438     if (Ty->isHalfTy())
11439       return AtomicExpansionKind::None;
11440 
11441     if (!Ty->isFloatTy())
11442       return AtomicExpansionKind::CmpXChg;
11443 
11444     // TODO: Do have these for flat. Older targets also had them for buffers.
11445     unsigned AS = RMW->getPointerAddressSpace();
11446 
11447     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11448       return RMW->use_empty() ? AtomicExpansionKind::None :
11449                                 AtomicExpansionKind::CmpXChg;
11450     }
11451 
11452     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11453       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11454   }
11455   default:
11456     break;
11457   }
11458 
11459   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11460 }
11461 
11462 const TargetRegisterClass *
11463 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11464   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11465   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11466   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11467     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11468                                                : &AMDGPU::SReg_32RegClass;
11469   if (!TRI->isSGPRClass(RC) && !isDivergent)
11470     return TRI->getEquivalentSGPRClass(RC);
11471   else if (TRI->isSGPRClass(RC) && isDivergent)
11472     return TRI->getEquivalentVGPRClass(RC);
11473 
11474   return RC;
11475 }
11476 
11477 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11478 // uniform values (as produced by the mask results of control flow intrinsics)
11479 // used outside of divergent blocks. The phi users need to also be treated as
11480 // always uniform.
11481 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11482                       unsigned WaveSize) {
11483   // FIXME: We asssume we never cast the mask results of a control flow
11484   // intrinsic.
11485   // Early exit if the type won't be consistent as a compile time hack.
11486   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11487   if (!IT || IT->getBitWidth() != WaveSize)
11488     return false;
11489 
11490   if (!isa<Instruction>(V))
11491     return false;
11492   if (!Visited.insert(V).second)
11493     return false;
11494   bool Result = false;
11495   for (auto U : V->users()) {
11496     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11497       if (V == U->getOperand(1)) {
11498         switch (Intrinsic->getIntrinsicID()) {
11499         default:
11500           Result = false;
11501           break;
11502         case Intrinsic::amdgcn_if_break:
11503         case Intrinsic::amdgcn_if:
11504         case Intrinsic::amdgcn_else:
11505           Result = true;
11506           break;
11507         }
11508       }
11509       if (V == U->getOperand(0)) {
11510         switch (Intrinsic->getIntrinsicID()) {
11511         default:
11512           Result = false;
11513           break;
11514         case Intrinsic::amdgcn_end_cf:
11515         case Intrinsic::amdgcn_loop:
11516           Result = true;
11517           break;
11518         }
11519       }
11520     } else {
11521       Result = hasCFUser(U, Visited, WaveSize);
11522     }
11523     if (Result)
11524       break;
11525   }
11526   return Result;
11527 }
11528 
11529 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11530                                                const Value *V) const {
11531   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11532     if (CI->isInlineAsm()) {
11533       // FIXME: This cannot give a correct answer. This should only trigger in
11534       // the case where inline asm returns mixed SGPR and VGPR results, used
11535       // outside the defining block. We don't have a specific result to
11536       // consider, so this assumes if any value is SGPR, the overall register
11537       // also needs to be SGPR.
11538       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11539       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11540           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11541       for (auto &TC : TargetConstraints) {
11542         if (TC.Type == InlineAsm::isOutput) {
11543           ComputeConstraintToUse(TC, SDValue());
11544           unsigned AssignedReg;
11545           const TargetRegisterClass *RC;
11546           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11547               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11548           if (RC) {
11549             MachineRegisterInfo &MRI = MF.getRegInfo();
11550             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11551               return true;
11552             else if (SIRI->isSGPRClass(RC))
11553               return true;
11554           }
11555         }
11556       }
11557     }
11558   }
11559   SmallPtrSet<const Value *, 16> Visited;
11560   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11561 }
11562