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::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
771   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
772   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
773   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
774   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
775   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
776   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
777 
778   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
779   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
780   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
783   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
784   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
785   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
786   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
787 
788   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
789   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
790   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
794   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
795   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
796 
797   setTargetDAGCombine(ISD::ADD);
798   setTargetDAGCombine(ISD::ADDCARRY);
799   setTargetDAGCombine(ISD::SUB);
800   setTargetDAGCombine(ISD::SUBCARRY);
801   setTargetDAGCombine(ISD::FADD);
802   setTargetDAGCombine(ISD::FSUB);
803   setTargetDAGCombine(ISD::FMINNUM);
804   setTargetDAGCombine(ISD::FMAXNUM);
805   setTargetDAGCombine(ISD::FMINNUM_IEEE);
806   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
807   setTargetDAGCombine(ISD::FMA);
808   setTargetDAGCombine(ISD::SMIN);
809   setTargetDAGCombine(ISD::SMAX);
810   setTargetDAGCombine(ISD::UMIN);
811   setTargetDAGCombine(ISD::UMAX);
812   setTargetDAGCombine(ISD::SETCC);
813   setTargetDAGCombine(ISD::AND);
814   setTargetDAGCombine(ISD::OR);
815   setTargetDAGCombine(ISD::XOR);
816   setTargetDAGCombine(ISD::SINT_TO_FP);
817   setTargetDAGCombine(ISD::UINT_TO_FP);
818   setTargetDAGCombine(ISD::FCANONICALIZE);
819   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
820   setTargetDAGCombine(ISD::ZERO_EXTEND);
821   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
822   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
823   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
824 
825   // All memory operations. Some folding on the pointer operand is done to help
826   // matching the constant offsets in the addressing modes.
827   setTargetDAGCombine(ISD::LOAD);
828   setTargetDAGCombine(ISD::STORE);
829   setTargetDAGCombine(ISD::ATOMIC_LOAD);
830   setTargetDAGCombine(ISD::ATOMIC_STORE);
831   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
832   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
833   setTargetDAGCombine(ISD::ATOMIC_SWAP);
834   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
835   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
836   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
843   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
844   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
845 
846   // FIXME: In other contexts we pretend this is a per-function property.
847   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
848 
849   setSchedulingPreference(Sched::RegPressure);
850 }
851 
852 const GCNSubtarget *SITargetLowering::getSubtarget() const {
853   return Subtarget;
854 }
855 
856 //===----------------------------------------------------------------------===//
857 // TargetLowering queries
858 //===----------------------------------------------------------------------===//
859 
860 // v_mad_mix* support a conversion from f16 to f32.
861 //
862 // There is only one special case when denormals are enabled we don't currently,
863 // where this is OK to use.
864 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
865                                        EVT DestVT, EVT SrcVT) const {
866   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
867           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
868     DestVT.getScalarType() == MVT::f32 &&
869     SrcVT.getScalarType() == MVT::f16 &&
870     // TODO: This probably only requires no input flushing?
871     !hasFP32Denormals(DAG.getMachineFunction());
872 }
873 
874 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
875   // SI has some legal vector types, but no legal vector operations. Say no
876   // shuffles are legal in order to prefer scalarizing some vector operations.
877   return false;
878 }
879 
880 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
881                                                     CallingConv::ID CC,
882                                                     EVT VT) const {
883   if (CC == CallingConv::AMDGPU_KERNEL)
884     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
885 
886   if (VT.isVector()) {
887     EVT ScalarVT = VT.getScalarType();
888     unsigned Size = ScalarVT.getSizeInBits();
889     if (Size == 32)
890       return ScalarVT.getSimpleVT();
891 
892     if (Size > 32)
893       return MVT::i32;
894 
895     if (Size == 16 && Subtarget->has16BitInsts())
896       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
897   } else if (VT.getSizeInBits() > 32)
898     return MVT::i32;
899 
900   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
901 }
902 
903 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
904                                                          CallingConv::ID CC,
905                                                          EVT VT) const {
906   if (CC == CallingConv::AMDGPU_KERNEL)
907     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
908 
909   if (VT.isVector()) {
910     unsigned NumElts = VT.getVectorNumElements();
911     EVT ScalarVT = VT.getScalarType();
912     unsigned Size = ScalarVT.getSizeInBits();
913 
914     if (Size == 32)
915       return NumElts;
916 
917     if (Size > 32)
918       return NumElts * ((Size + 31) / 32);
919 
920     if (Size == 16 && Subtarget->has16BitInsts())
921       return (NumElts + 1) / 2;
922   } else if (VT.getSizeInBits() > 32)
923     return (VT.getSizeInBits() + 31) / 32;
924 
925   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
926 }
927 
928 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
929   LLVMContext &Context, CallingConv::ID CC,
930   EVT VT, EVT &IntermediateVT,
931   unsigned &NumIntermediates, MVT &RegisterVT) const {
932   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
933     unsigned NumElts = VT.getVectorNumElements();
934     EVT ScalarVT = VT.getScalarType();
935     unsigned Size = ScalarVT.getSizeInBits();
936     if (Size == 32) {
937       RegisterVT = ScalarVT.getSimpleVT();
938       IntermediateVT = RegisterVT;
939       NumIntermediates = NumElts;
940       return NumIntermediates;
941     }
942 
943     if (Size > 32) {
944       RegisterVT = MVT::i32;
945       IntermediateVT = RegisterVT;
946       NumIntermediates = NumElts * ((Size + 31) / 32);
947       return NumIntermediates;
948     }
949 
950     // FIXME: We should fix the ABI to be the same on targets without 16-bit
951     // support, but unless we can properly handle 3-vectors, it will be still be
952     // inconsistent.
953     if (Size == 16 && Subtarget->has16BitInsts()) {
954       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
955       IntermediateVT = RegisterVT;
956       NumIntermediates = (NumElts + 1) / 2;
957       return NumIntermediates;
958     }
959   }
960 
961   return TargetLowering::getVectorTypeBreakdownForCallingConv(
962     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
963 }
964 
965 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
966   assert(DMaskLanes != 0);
967 
968   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
969     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
970     return EVT::getVectorVT(Ty->getContext(),
971                             EVT::getEVT(VT->getElementType()),
972                             NumElts);
973   }
974 
975   return EVT::getEVT(Ty);
976 }
977 
978 // Peek through TFE struct returns to only use the data size.
979 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
980   auto *ST = dyn_cast<StructType>(Ty);
981   if (!ST)
982     return memVTFromImageData(Ty, DMaskLanes);
983 
984   // Some intrinsics return an aggregate type - special case to work out the
985   // correct memVT.
986   //
987   // Only limited forms of aggregate type currently expected.
988   if (ST->getNumContainedTypes() != 2 ||
989       !ST->getContainedType(1)->isIntegerTy(32))
990     return EVT();
991   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
992 }
993 
994 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
995                                           const CallInst &CI,
996                                           MachineFunction &MF,
997                                           unsigned IntrID) const {
998   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
999           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1000     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1001                                                   (Intrinsic::ID)IntrID);
1002     if (Attr.hasFnAttribute(Attribute::ReadNone))
1003       return false;
1004 
1005     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1006 
1007     if (RsrcIntr->IsImage) {
1008       Info.ptrVal = MFI->getImagePSV(
1009         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1010         CI.getArgOperand(RsrcIntr->RsrcArg));
1011       Info.align.reset();
1012     } else {
1013       Info.ptrVal = MFI->getBufferPSV(
1014         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1015         CI.getArgOperand(RsrcIntr->RsrcArg));
1016     }
1017 
1018     Info.flags = MachineMemOperand::MODereferenceable;
1019     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1020       unsigned DMaskLanes = 4;
1021 
1022       if (RsrcIntr->IsImage) {
1023         const AMDGPU::ImageDimIntrinsicInfo *Intr
1024           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1025         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1026           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1027 
1028         if (!BaseOpcode->Gather4) {
1029           // If this isn't a gather, we may have excess loaded elements in the
1030           // IR type. Check the dmask for the real number of elements loaded.
1031           unsigned DMask
1032             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1033           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1034         }
1035 
1036         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1037       } else
1038         Info.memVT = EVT::getEVT(CI.getType());
1039 
1040       // FIXME: What does alignment mean for an image?
1041       Info.opc = ISD::INTRINSIC_W_CHAIN;
1042       Info.flags |= MachineMemOperand::MOLoad;
1043     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1044       Info.opc = ISD::INTRINSIC_VOID;
1045 
1046       Type *DataTy = CI.getArgOperand(0)->getType();
1047       if (RsrcIntr->IsImage) {
1048         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1049         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1050         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1051       } else
1052         Info.memVT = EVT::getEVT(DataTy);
1053 
1054       Info.flags |= MachineMemOperand::MOStore;
1055     } else {
1056       // Atomic
1057       Info.opc = ISD::INTRINSIC_W_CHAIN;
1058       Info.memVT = MVT::getVT(CI.getType());
1059       Info.flags = MachineMemOperand::MOLoad |
1060                    MachineMemOperand::MOStore |
1061                    MachineMemOperand::MODereferenceable;
1062 
1063       // XXX - Should this be volatile without known ordering?
1064       Info.flags |= MachineMemOperand::MOVolatile;
1065     }
1066     return true;
1067   }
1068 
1069   switch (IntrID) {
1070   case Intrinsic::amdgcn_atomic_inc:
1071   case Intrinsic::amdgcn_atomic_dec:
1072   case Intrinsic::amdgcn_ds_ordered_add:
1073   case Intrinsic::amdgcn_ds_ordered_swap:
1074   case Intrinsic::amdgcn_ds_fadd:
1075   case Intrinsic::amdgcn_ds_fmin:
1076   case Intrinsic::amdgcn_ds_fmax: {
1077     Info.opc = ISD::INTRINSIC_W_CHAIN;
1078     Info.memVT = MVT::getVT(CI.getType());
1079     Info.ptrVal = CI.getOperand(0);
1080     Info.align.reset();
1081     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1082 
1083     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1084     if (!Vol->isZero())
1085       Info.flags |= MachineMemOperand::MOVolatile;
1086 
1087     return true;
1088   }
1089   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1090     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1091 
1092     Info.opc = ISD::INTRINSIC_VOID;
1093     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1094     Info.ptrVal = MFI->getBufferPSV(
1095       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1096       CI.getArgOperand(1));
1097     Info.align.reset();
1098     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1099 
1100     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1101     if (!Vol || !Vol->isZero())
1102       Info.flags |= MachineMemOperand::MOVolatile;
1103 
1104     return true;
1105   }
1106   case Intrinsic::amdgcn_global_atomic_fadd: {
1107     Info.opc = ISD::INTRINSIC_VOID;
1108     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1109                             ->getPointerElementType());
1110     Info.ptrVal = CI.getOperand(0);
1111     Info.align.reset();
1112     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1113 
1114     return true;
1115   }
1116   case Intrinsic::amdgcn_ds_append:
1117   case Intrinsic::amdgcn_ds_consume: {
1118     Info.opc = ISD::INTRINSIC_W_CHAIN;
1119     Info.memVT = MVT::getVT(CI.getType());
1120     Info.ptrVal = CI.getOperand(0);
1121     Info.align.reset();
1122     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1123 
1124     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1125     if (!Vol->isZero())
1126       Info.flags |= MachineMemOperand::MOVolatile;
1127 
1128     return true;
1129   }
1130   case Intrinsic::amdgcn_ds_gws_init:
1131   case Intrinsic::amdgcn_ds_gws_barrier:
1132   case Intrinsic::amdgcn_ds_gws_sema_v:
1133   case Intrinsic::amdgcn_ds_gws_sema_br:
1134   case Intrinsic::amdgcn_ds_gws_sema_p:
1135   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1136     Info.opc = ISD::INTRINSIC_VOID;
1137 
1138     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1139     Info.ptrVal =
1140         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1141 
1142     // This is an abstract access, but we need to specify a type and size.
1143     Info.memVT = MVT::i32;
1144     Info.size = 4;
1145     Info.align = Align(4);
1146 
1147     Info.flags = MachineMemOperand::MOStore;
1148     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1149       Info.flags = MachineMemOperand::MOLoad;
1150     return true;
1151   }
1152   default:
1153     return false;
1154   }
1155 }
1156 
1157 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1158                                             SmallVectorImpl<Value*> &Ops,
1159                                             Type *&AccessTy) const {
1160   switch (II->getIntrinsicID()) {
1161   case Intrinsic::amdgcn_atomic_inc:
1162   case Intrinsic::amdgcn_atomic_dec:
1163   case Intrinsic::amdgcn_ds_ordered_add:
1164   case Intrinsic::amdgcn_ds_ordered_swap:
1165   case Intrinsic::amdgcn_ds_fadd:
1166   case Intrinsic::amdgcn_ds_fmin:
1167   case Intrinsic::amdgcn_ds_fmax: {
1168     Value *Ptr = II->getArgOperand(0);
1169     AccessTy = II->getType();
1170     Ops.push_back(Ptr);
1171     return true;
1172   }
1173   default:
1174     return false;
1175   }
1176 }
1177 
1178 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1179   if (!Subtarget->hasFlatInstOffsets()) {
1180     // Flat instructions do not have offsets, and only have the register
1181     // address.
1182     return AM.BaseOffs == 0 && AM.Scale == 0;
1183   }
1184 
1185   return AM.Scale == 0 &&
1186          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1187                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1188                                   /*Signed=*/false));
1189 }
1190 
1191 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1192   if (Subtarget->hasFlatGlobalInsts())
1193     return AM.Scale == 0 &&
1194            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1195                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1196                                     /*Signed=*/true));
1197 
1198   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1199       // Assume the we will use FLAT for all global memory accesses
1200       // on VI.
1201       // FIXME: This assumption is currently wrong.  On VI we still use
1202       // MUBUF instructions for the r + i addressing mode.  As currently
1203       // implemented, the MUBUF instructions only work on buffer < 4GB.
1204       // It may be possible to support > 4GB buffers with MUBUF instructions,
1205       // by setting the stride value in the resource descriptor which would
1206       // increase the size limit to (stride * 4GB).  However, this is risky,
1207       // because it has never been validated.
1208     return isLegalFlatAddressingMode(AM);
1209   }
1210 
1211   return isLegalMUBUFAddressingMode(AM);
1212 }
1213 
1214 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1215   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1216   // additionally can do r + r + i with addr64. 32-bit has more addressing
1217   // mode options. Depending on the resource constant, it can also do
1218   // (i64 r0) + (i32 r1) * (i14 i).
1219   //
1220   // Private arrays end up using a scratch buffer most of the time, so also
1221   // assume those use MUBUF instructions. Scratch loads / stores are currently
1222   // implemented as mubuf instructions with offen bit set, so slightly
1223   // different than the normal addr64.
1224   if (!isUInt<12>(AM.BaseOffs))
1225     return false;
1226 
1227   // FIXME: Since we can split immediate into soffset and immediate offset,
1228   // would it make sense to allow any immediate?
1229 
1230   switch (AM.Scale) {
1231   case 0: // r + i or just i, depending on HasBaseReg.
1232     return true;
1233   case 1:
1234     return true; // We have r + r or r + i.
1235   case 2:
1236     if (AM.HasBaseReg) {
1237       // Reject 2 * r + r.
1238       return false;
1239     }
1240 
1241     // Allow 2 * r as r + r
1242     // Or  2 * r + i is allowed as r + r + i.
1243     return true;
1244   default: // Don't allow n * r
1245     return false;
1246   }
1247 }
1248 
1249 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1250                                              const AddrMode &AM, Type *Ty,
1251                                              unsigned AS, Instruction *I) const {
1252   // No global is ever allowed as a base.
1253   if (AM.BaseGV)
1254     return false;
1255 
1256   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1257     return isLegalGlobalAddressingMode(AM);
1258 
1259   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1260       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1261       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1262     // If the offset isn't a multiple of 4, it probably isn't going to be
1263     // correctly aligned.
1264     // FIXME: Can we get the real alignment here?
1265     if (AM.BaseOffs % 4 != 0)
1266       return isLegalMUBUFAddressingMode(AM);
1267 
1268     // There are no SMRD extloads, so if we have to do a small type access we
1269     // will use a MUBUF load.
1270     // FIXME?: We also need to do this if unaligned, but we don't know the
1271     // alignment here.
1272     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1273       return isLegalGlobalAddressingMode(AM);
1274 
1275     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1276       // SMRD instructions have an 8-bit, dword offset on SI.
1277       if (!isUInt<8>(AM.BaseOffs / 4))
1278         return false;
1279     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1280       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1281       // in 8-bits, it can use a smaller encoding.
1282       if (!isUInt<32>(AM.BaseOffs / 4))
1283         return false;
1284     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1285       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1286       if (!isUInt<20>(AM.BaseOffs))
1287         return false;
1288     } else
1289       llvm_unreachable("unhandled generation");
1290 
1291     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1292       return true;
1293 
1294     if (AM.Scale == 1 && AM.HasBaseReg)
1295       return true;
1296 
1297     return false;
1298 
1299   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1300     return isLegalMUBUFAddressingMode(AM);
1301   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1302              AS == AMDGPUAS::REGION_ADDRESS) {
1303     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1304     // field.
1305     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1306     // an 8-bit dword offset but we don't know the alignment here.
1307     if (!isUInt<16>(AM.BaseOffs))
1308       return false;
1309 
1310     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1311       return true;
1312 
1313     if (AM.Scale == 1 && AM.HasBaseReg)
1314       return true;
1315 
1316     return false;
1317   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1318              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1319     // For an unknown address space, this usually means that this is for some
1320     // reason being used for pure arithmetic, and not based on some addressing
1321     // computation. We don't have instructions that compute pointers with any
1322     // addressing modes, so treat them as having no offset like flat
1323     // instructions.
1324     return isLegalFlatAddressingMode(AM);
1325   }
1326 
1327   // Assume a user alias of global for unknown address spaces.
1328   return isLegalGlobalAddressingMode(AM);
1329 }
1330 
1331 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1332                                         const SelectionDAG &DAG) const {
1333   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1334     return (MemVT.getSizeInBits() <= 4 * 32);
1335   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1336     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1337     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1338   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1339     return (MemVT.getSizeInBits() <= 2 * 32);
1340   }
1341   return true;
1342 }
1343 
1344 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1345     unsigned Size, unsigned AddrSpace, unsigned Align,
1346     MachineMemOperand::Flags Flags, bool *IsFast) const {
1347   if (IsFast)
1348     *IsFast = false;
1349 
1350   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1351       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1352     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1353     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1354     // with adjacent offsets.
1355     bool AlignedBy4 = (Align % 4 == 0);
1356     if (IsFast)
1357       *IsFast = AlignedBy4;
1358 
1359     return AlignedBy4;
1360   }
1361 
1362   // FIXME: We have to be conservative here and assume that flat operations
1363   // will access scratch.  If we had access to the IR function, then we
1364   // could determine if any private memory was used in the function.
1365   if (!Subtarget->hasUnalignedScratchAccess() &&
1366       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1367        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1368     bool AlignedBy4 = Align >= 4;
1369     if (IsFast)
1370       *IsFast = AlignedBy4;
1371 
1372     return AlignedBy4;
1373   }
1374 
1375   if (Subtarget->hasUnalignedBufferAccess()) {
1376     // If we have an uniform constant load, it still requires using a slow
1377     // buffer instruction if unaligned.
1378     if (IsFast) {
1379       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1380       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1381       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1382                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1383         Align >= 4 : Align != 2;
1384     }
1385 
1386     return true;
1387   }
1388 
1389   // Smaller than dword value must be aligned.
1390   if (Size < 32)
1391     return false;
1392 
1393   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1394   // byte-address are ignored, thus forcing Dword alignment.
1395   // This applies to private, global, and constant memory.
1396   if (IsFast)
1397     *IsFast = true;
1398 
1399   return Size >= 32 && Align >= 4;
1400 }
1401 
1402 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1403     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1404     bool *IsFast) const {
1405   if (IsFast)
1406     *IsFast = false;
1407 
1408   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1409   // which isn't a simple VT.
1410   // Until MVT is extended to handle this, simply check for the size and
1411   // rely on the condition below: allow accesses if the size is a multiple of 4.
1412   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1413                            VT.getStoreSize() > 16)) {
1414     return false;
1415   }
1416 
1417   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1418                                             Align, Flags, IsFast);
1419 }
1420 
1421 EVT SITargetLowering::getOptimalMemOpType(
1422     const MemOp &Op, const AttributeList &FuncAttributes) const {
1423   // FIXME: Should account for address space here.
1424 
1425   // The default fallback uses the private pointer size as a guess for a type to
1426   // use. Make sure we switch these to 64-bit accesses.
1427 
1428   if (Op.size() >= 16 &&
1429       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1430     return MVT::v4i32;
1431 
1432   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1433     return MVT::v2i32;
1434 
1435   // Use the default.
1436   return MVT::Other;
1437 }
1438 
1439 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1440                                            unsigned DestAS) const {
1441   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1442 }
1443 
1444 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1445   const MemSDNode *MemNode = cast<MemSDNode>(N);
1446   const Value *Ptr = MemNode->getMemOperand()->getValue();
1447   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1448   return I && I->getMetadata("amdgpu.noclobber");
1449 }
1450 
1451 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1452                                            unsigned DestAS) const {
1453   // Flat -> private/local is a simple truncate.
1454   // Flat -> global is no-op
1455   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1456     return true;
1457 
1458   return isNoopAddrSpaceCast(SrcAS, DestAS);
1459 }
1460 
1461 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1462   const MemSDNode *MemNode = cast<MemSDNode>(N);
1463 
1464   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1465 }
1466 
1467 TargetLoweringBase::LegalizeTypeAction
1468 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1469   int NumElts = VT.getVectorNumElements();
1470   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1471     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1472   return TargetLoweringBase::getPreferredVectorAction(VT);
1473 }
1474 
1475 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1476                                                          Type *Ty) const {
1477   // FIXME: Could be smarter if called for vector constants.
1478   return true;
1479 }
1480 
1481 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1482   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1483     switch (Op) {
1484     case ISD::LOAD:
1485     case ISD::STORE:
1486 
1487     // These operations are done with 32-bit instructions anyway.
1488     case ISD::AND:
1489     case ISD::OR:
1490     case ISD::XOR:
1491     case ISD::SELECT:
1492       // TODO: Extensions?
1493       return true;
1494     default:
1495       return false;
1496     }
1497   }
1498 
1499   // SimplifySetCC uses this function to determine whether or not it should
1500   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1501   if (VT == MVT::i1 && Op == ISD::SETCC)
1502     return false;
1503 
1504   return TargetLowering::isTypeDesirableForOp(Op, VT);
1505 }
1506 
1507 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1508                                                    const SDLoc &SL,
1509                                                    SDValue Chain,
1510                                                    uint64_t Offset) const {
1511   const DataLayout &DL = DAG.getDataLayout();
1512   MachineFunction &MF = DAG.getMachineFunction();
1513   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1514 
1515   const ArgDescriptor *InputPtrReg;
1516   const TargetRegisterClass *RC;
1517 
1518   std::tie(InputPtrReg, RC)
1519     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1520 
1521   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1522   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1523   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1524     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1525 
1526   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1527 }
1528 
1529 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1530                                             const SDLoc &SL) const {
1531   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1532                                                FIRST_IMPLICIT);
1533   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1534 }
1535 
1536 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1537                                          const SDLoc &SL, SDValue Val,
1538                                          bool Signed,
1539                                          const ISD::InputArg *Arg) const {
1540   // First, if it is a widened vector, narrow it.
1541   if (VT.isVector() &&
1542       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1543     EVT NarrowedVT =
1544         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1545                          VT.getVectorNumElements());
1546     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1547                       DAG.getConstant(0, SL, MVT::i32));
1548   }
1549 
1550   // Then convert the vector elements or scalar value.
1551   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1552       VT.bitsLT(MemVT)) {
1553     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1554     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1555   }
1556 
1557   if (MemVT.isFloatingPoint())
1558     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1559   else if (Signed)
1560     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1561   else
1562     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1563 
1564   return Val;
1565 }
1566 
1567 SDValue SITargetLowering::lowerKernargMemParameter(
1568   SelectionDAG &DAG, EVT VT, EVT MemVT,
1569   const SDLoc &SL, SDValue Chain,
1570   uint64_t Offset, unsigned Align, bool Signed,
1571   const ISD::InputArg *Arg) const {
1572   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1573 
1574   // Try to avoid using an extload by loading earlier than the argument address,
1575   // and extracting the relevant bits. The load should hopefully be merged with
1576   // the previous argument.
1577   if (MemVT.getStoreSize() < 4 && Align < 4) {
1578     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1579     int64_t AlignDownOffset = alignDown(Offset, 4);
1580     int64_t OffsetDiff = Offset - AlignDownOffset;
1581 
1582     EVT IntVT = MemVT.changeTypeToInteger();
1583 
1584     // TODO: If we passed in the base kernel offset we could have a better
1585     // alignment than 4, but we don't really need it.
1586     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1587     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1588                                MachineMemOperand::MODereferenceable |
1589                                MachineMemOperand::MOInvariant);
1590 
1591     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1592     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1593 
1594     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1595     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1596     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1597 
1598 
1599     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1600   }
1601 
1602   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1603   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1604                              MachineMemOperand::MODereferenceable |
1605                              MachineMemOperand::MOInvariant);
1606 
1607   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1608   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1609 }
1610 
1611 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1612                                               const SDLoc &SL, SDValue Chain,
1613                                               const ISD::InputArg &Arg) const {
1614   MachineFunction &MF = DAG.getMachineFunction();
1615   MachineFrameInfo &MFI = MF.getFrameInfo();
1616 
1617   if (Arg.Flags.isByVal()) {
1618     unsigned Size = Arg.Flags.getByValSize();
1619     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1620     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1621   }
1622 
1623   unsigned ArgOffset = VA.getLocMemOffset();
1624   unsigned ArgSize = VA.getValVT().getStoreSize();
1625 
1626   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1627 
1628   // Create load nodes to retrieve arguments from the stack.
1629   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1630   SDValue ArgValue;
1631 
1632   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1633   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1634   MVT MemVT = VA.getValVT();
1635 
1636   switch (VA.getLocInfo()) {
1637   default:
1638     break;
1639   case CCValAssign::BCvt:
1640     MemVT = VA.getLocVT();
1641     break;
1642   case CCValAssign::SExt:
1643     ExtType = ISD::SEXTLOAD;
1644     break;
1645   case CCValAssign::ZExt:
1646     ExtType = ISD::ZEXTLOAD;
1647     break;
1648   case CCValAssign::AExt:
1649     ExtType = ISD::EXTLOAD;
1650     break;
1651   }
1652 
1653   ArgValue = DAG.getExtLoad(
1654     ExtType, SL, VA.getLocVT(), Chain, FIN,
1655     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1656     MemVT);
1657   return ArgValue;
1658 }
1659 
1660 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1661   const SIMachineFunctionInfo &MFI,
1662   EVT VT,
1663   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1664   const ArgDescriptor *Reg;
1665   const TargetRegisterClass *RC;
1666 
1667   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1668   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1669 }
1670 
1671 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1672                                    CallingConv::ID CallConv,
1673                                    ArrayRef<ISD::InputArg> Ins,
1674                                    BitVector &Skipped,
1675                                    FunctionType *FType,
1676                                    SIMachineFunctionInfo *Info) {
1677   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1678     const ISD::InputArg *Arg = &Ins[I];
1679 
1680     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1681            "vector type argument should have been split");
1682 
1683     // First check if it's a PS input addr.
1684     if (CallConv == CallingConv::AMDGPU_PS &&
1685         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1686       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1687 
1688       // Inconveniently only the first part of the split is marked as isSplit,
1689       // so skip to the end. We only want to increment PSInputNum once for the
1690       // entire split argument.
1691       if (Arg->Flags.isSplit()) {
1692         while (!Arg->Flags.isSplitEnd()) {
1693           assert((!Arg->VT.isVector() ||
1694                   Arg->VT.getScalarSizeInBits() == 16) &&
1695                  "unexpected vector split in ps argument type");
1696           if (!SkipArg)
1697             Splits.push_back(*Arg);
1698           Arg = &Ins[++I];
1699         }
1700       }
1701 
1702       if (SkipArg) {
1703         // We can safely skip PS inputs.
1704         Skipped.set(Arg->getOrigArgIndex());
1705         ++PSInputNum;
1706         continue;
1707       }
1708 
1709       Info->markPSInputAllocated(PSInputNum);
1710       if (Arg->Used)
1711         Info->markPSInputEnabled(PSInputNum);
1712 
1713       ++PSInputNum;
1714     }
1715 
1716     Splits.push_back(*Arg);
1717   }
1718 }
1719 
1720 // Allocate special inputs passed in VGPRs.
1721 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1722                                                       MachineFunction &MF,
1723                                                       const SIRegisterInfo &TRI,
1724                                                       SIMachineFunctionInfo &Info) const {
1725   const LLT S32 = LLT::scalar(32);
1726   MachineRegisterInfo &MRI = MF.getRegInfo();
1727 
1728   if (Info.hasWorkItemIDX()) {
1729     Register Reg = AMDGPU::VGPR0;
1730     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1731 
1732     CCInfo.AllocateReg(Reg);
1733     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1734   }
1735 
1736   if (Info.hasWorkItemIDY()) {
1737     Register Reg = AMDGPU::VGPR1;
1738     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1739 
1740     CCInfo.AllocateReg(Reg);
1741     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1742   }
1743 
1744   if (Info.hasWorkItemIDZ()) {
1745     Register Reg = AMDGPU::VGPR2;
1746     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1747 
1748     CCInfo.AllocateReg(Reg);
1749     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1750   }
1751 }
1752 
1753 // Try to allocate a VGPR at the end of the argument list, or if no argument
1754 // VGPRs are left allocating a stack slot.
1755 // If \p Mask is is given it indicates bitfield position in the register.
1756 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1757 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1758                                          ArgDescriptor Arg = ArgDescriptor()) {
1759   if (Arg.isSet())
1760     return ArgDescriptor::createArg(Arg, Mask);
1761 
1762   ArrayRef<MCPhysReg> ArgVGPRs
1763     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1764   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1765   if (RegIdx == ArgVGPRs.size()) {
1766     // Spill to stack required.
1767     int64_t Offset = CCInfo.AllocateStack(4, 4);
1768 
1769     return ArgDescriptor::createStack(Offset, Mask);
1770   }
1771 
1772   unsigned Reg = ArgVGPRs[RegIdx];
1773   Reg = CCInfo.AllocateReg(Reg);
1774   assert(Reg != AMDGPU::NoRegister);
1775 
1776   MachineFunction &MF = CCInfo.getMachineFunction();
1777   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1778   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1779   return ArgDescriptor::createRegister(Reg, Mask);
1780 }
1781 
1782 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1783                                              const TargetRegisterClass *RC,
1784                                              unsigned NumArgRegs) {
1785   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1786   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1787   if (RegIdx == ArgSGPRs.size())
1788     report_fatal_error("ran out of SGPRs for arguments");
1789 
1790   unsigned Reg = ArgSGPRs[RegIdx];
1791   Reg = CCInfo.AllocateReg(Reg);
1792   assert(Reg != AMDGPU::NoRegister);
1793 
1794   MachineFunction &MF = CCInfo.getMachineFunction();
1795   MF.addLiveIn(Reg, RC);
1796   return ArgDescriptor::createRegister(Reg);
1797 }
1798 
1799 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1800   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1801 }
1802 
1803 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1804   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1805 }
1806 
1807 /// Allocate implicit function VGPR arguments at the end of allocated user
1808 /// arguments.
1809 void SITargetLowering::allocateSpecialInputVGPRs(
1810   CCState &CCInfo, MachineFunction &MF,
1811   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1812   const unsigned Mask = 0x3ff;
1813   ArgDescriptor Arg;
1814 
1815   if (Info.hasWorkItemIDX()) {
1816     Arg = allocateVGPR32Input(CCInfo, Mask);
1817     Info.setWorkItemIDX(Arg);
1818   }
1819 
1820   if (Info.hasWorkItemIDY()) {
1821     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1822     Info.setWorkItemIDY(Arg);
1823   }
1824 
1825   if (Info.hasWorkItemIDZ())
1826     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1827 }
1828 
1829 /// Allocate implicit function VGPR arguments in fixed registers.
1830 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1831   CCState &CCInfo, MachineFunction &MF,
1832   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1833   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1834   if (!Reg)
1835     report_fatal_error("failed to allocated VGPR for implicit arguments");
1836 
1837   const unsigned Mask = 0x3ff;
1838   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1839   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1840   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1841 }
1842 
1843 void SITargetLowering::allocateSpecialInputSGPRs(
1844   CCState &CCInfo,
1845   MachineFunction &MF,
1846   const SIRegisterInfo &TRI,
1847   SIMachineFunctionInfo &Info) const {
1848   auto &ArgInfo = Info.getArgInfo();
1849 
1850   // TODO: Unify handling with private memory pointers.
1851 
1852   if (Info.hasDispatchPtr())
1853     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1854 
1855   if (Info.hasQueuePtr())
1856     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1857 
1858   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1859   // constant offset from the kernarg segment.
1860   if (Info.hasImplicitArgPtr())
1861     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1862 
1863   if (Info.hasDispatchID())
1864     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1865 
1866   // flat_scratch_init is not applicable for non-kernel functions.
1867 
1868   if (Info.hasWorkGroupIDX())
1869     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1870 
1871   if (Info.hasWorkGroupIDY())
1872     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1873 
1874   if (Info.hasWorkGroupIDZ())
1875     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1876 }
1877 
1878 // Allocate special inputs passed in user SGPRs.
1879 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1880                                             MachineFunction &MF,
1881                                             const SIRegisterInfo &TRI,
1882                                             SIMachineFunctionInfo &Info) const {
1883   if (Info.hasImplicitBufferPtr()) {
1884     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1885     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1886     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1887   }
1888 
1889   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1890   if (Info.hasPrivateSegmentBuffer()) {
1891     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1892     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1893     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1894   }
1895 
1896   if (Info.hasDispatchPtr()) {
1897     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1898     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1899     CCInfo.AllocateReg(DispatchPtrReg);
1900   }
1901 
1902   if (Info.hasQueuePtr()) {
1903     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1904     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1905     CCInfo.AllocateReg(QueuePtrReg);
1906   }
1907 
1908   if (Info.hasKernargSegmentPtr()) {
1909     MachineRegisterInfo &MRI = MF.getRegInfo();
1910     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1911     CCInfo.AllocateReg(InputPtrReg);
1912 
1913     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1914     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1915   }
1916 
1917   if (Info.hasDispatchID()) {
1918     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1919     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1920     CCInfo.AllocateReg(DispatchIDReg);
1921   }
1922 
1923   if (Info.hasFlatScratchInit()) {
1924     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1925     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1926     CCInfo.AllocateReg(FlatScratchInitReg);
1927   }
1928 
1929   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1930   // these from the dispatch pointer.
1931 }
1932 
1933 // Allocate special input registers that are initialized per-wave.
1934 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1935                                            MachineFunction &MF,
1936                                            SIMachineFunctionInfo &Info,
1937                                            CallingConv::ID CallConv,
1938                                            bool IsShader) const {
1939   if (Info.hasWorkGroupIDX()) {
1940     unsigned Reg = Info.addWorkGroupIDX();
1941     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1942     CCInfo.AllocateReg(Reg);
1943   }
1944 
1945   if (Info.hasWorkGroupIDY()) {
1946     unsigned Reg = Info.addWorkGroupIDY();
1947     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1948     CCInfo.AllocateReg(Reg);
1949   }
1950 
1951   if (Info.hasWorkGroupIDZ()) {
1952     unsigned Reg = Info.addWorkGroupIDZ();
1953     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1954     CCInfo.AllocateReg(Reg);
1955   }
1956 
1957   if (Info.hasWorkGroupInfo()) {
1958     unsigned Reg = Info.addWorkGroupInfo();
1959     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1960     CCInfo.AllocateReg(Reg);
1961   }
1962 
1963   if (Info.hasPrivateSegmentWaveByteOffset()) {
1964     // Scratch wave offset passed in system SGPR.
1965     unsigned PrivateSegmentWaveByteOffsetReg;
1966 
1967     if (IsShader) {
1968       PrivateSegmentWaveByteOffsetReg =
1969         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1970 
1971       // This is true if the scratch wave byte offset doesn't have a fixed
1972       // location.
1973       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1974         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1975         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1976       }
1977     } else
1978       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1979 
1980     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1981     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1982   }
1983 }
1984 
1985 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1986                                      MachineFunction &MF,
1987                                      const SIRegisterInfo &TRI,
1988                                      SIMachineFunctionInfo &Info) {
1989   // Now that we've figured out where the scratch register inputs are, see if
1990   // should reserve the arguments and use them directly.
1991   MachineFrameInfo &MFI = MF.getFrameInfo();
1992   bool HasStackObjects = MFI.hasStackObjects();
1993   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1994 
1995   // Record that we know we have non-spill stack objects so we don't need to
1996   // check all stack objects later.
1997   if (HasStackObjects)
1998     Info.setHasNonSpillStackObjects(true);
1999 
2000   // Everything live out of a block is spilled with fast regalloc, so it's
2001   // almost certain that spilling will be required.
2002   if (TM.getOptLevel() == CodeGenOpt::None)
2003     HasStackObjects = true;
2004 
2005   // For now assume stack access is needed in any callee functions, so we need
2006   // the scratch registers to pass in.
2007   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2008 
2009   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2010     // If we have stack objects, we unquestionably need the private buffer
2011     // resource. For the Code Object V2 ABI, this will be the first 4 user
2012     // SGPR inputs. We can reserve those and use them directly.
2013 
2014     Register PrivateSegmentBufferReg =
2015         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2016     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2017   } else {
2018     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2019     // We tentatively reserve the last registers (skipping the last registers
2020     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2021     // we'll replace these with the ones immediately after those which were
2022     // really allocated. In the prologue copies will be inserted from the
2023     // argument to these reserved registers.
2024 
2025     // Without HSA, relocations are used for the scratch pointer and the
2026     // buffer resource setup is always inserted in the prologue. Scratch wave
2027     // offset is still in an input SGPR.
2028     Info.setScratchRSrcReg(ReservedBufferReg);
2029   }
2030 
2031   MachineRegisterInfo &MRI = MF.getRegInfo();
2032 
2033   // For entry functions we have to set up the stack pointer if we use it,
2034   // whereas non-entry functions get this "for free". This means there is no
2035   // intrinsic advantage to using S32 over S34 in cases where we do not have
2036   // calls but do need a frame pointer (i.e. if we are requested to have one
2037   // because frame pointer elimination is disabled). To keep things simple we
2038   // only ever use S32 as the call ABI stack pointer, and so using it does not
2039   // imply we need a separate frame pointer.
2040   //
2041   // Try to use s32 as the SP, but move it if it would interfere with input
2042   // arguments. This won't work with calls though.
2043   //
2044   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2045   // registers.
2046   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2047     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2048   } else {
2049     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2050 
2051     if (MFI.hasCalls())
2052       report_fatal_error("call in graphics shader with too many input SGPRs");
2053 
2054     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2055       if (!MRI.isLiveIn(Reg)) {
2056         Info.setStackPtrOffsetReg(Reg);
2057         break;
2058       }
2059     }
2060 
2061     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2062       report_fatal_error("failed to find register for SP");
2063   }
2064 
2065   // hasFP should be accurate for entry functions even before the frame is
2066   // finalized, because it does not rely on the known stack size, only
2067   // properties like whether variable sized objects are present.
2068   if (ST.getFrameLowering()->hasFP(MF)) {
2069     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2070   }
2071 }
2072 
2073 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2074   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2075   return !Info->isEntryFunction();
2076 }
2077 
2078 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2079 
2080 }
2081 
2082 void SITargetLowering::insertCopiesSplitCSR(
2083   MachineBasicBlock *Entry,
2084   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2085   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2086 
2087   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2088   if (!IStart)
2089     return;
2090 
2091   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2092   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2093   MachineBasicBlock::iterator MBBI = Entry->begin();
2094   for (const MCPhysReg *I = IStart; *I; ++I) {
2095     const TargetRegisterClass *RC = nullptr;
2096     if (AMDGPU::SReg_64RegClass.contains(*I))
2097       RC = &AMDGPU::SGPR_64RegClass;
2098     else if (AMDGPU::SReg_32RegClass.contains(*I))
2099       RC = &AMDGPU::SGPR_32RegClass;
2100     else
2101       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2102 
2103     Register NewVR = MRI->createVirtualRegister(RC);
2104     // Create copy from CSR to a virtual register.
2105     Entry->addLiveIn(*I);
2106     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2107       .addReg(*I);
2108 
2109     // Insert the copy-back instructions right before the terminator.
2110     for (auto *Exit : Exits)
2111       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2112               TII->get(TargetOpcode::COPY), *I)
2113         .addReg(NewVR);
2114   }
2115 }
2116 
2117 SDValue SITargetLowering::LowerFormalArguments(
2118     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2119     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2120     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2121   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2122 
2123   MachineFunction &MF = DAG.getMachineFunction();
2124   const Function &Fn = MF.getFunction();
2125   FunctionType *FType = MF.getFunction().getFunctionType();
2126   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2127 
2128   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2129     DiagnosticInfoUnsupported NoGraphicsHSA(
2130         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2131     DAG.getContext()->diagnose(NoGraphicsHSA);
2132     return DAG.getEntryNode();
2133   }
2134 
2135   SmallVector<ISD::InputArg, 16> Splits;
2136   SmallVector<CCValAssign, 16> ArgLocs;
2137   BitVector Skipped(Ins.size());
2138   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2139                  *DAG.getContext());
2140 
2141   bool IsShader = AMDGPU::isShader(CallConv);
2142   bool IsKernel = AMDGPU::isKernel(CallConv);
2143   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2144 
2145   if (IsShader) {
2146     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2147 
2148     // At least one interpolation mode must be enabled or else the GPU will
2149     // hang.
2150     //
2151     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2152     // set PSInputAddr, the user wants to enable some bits after the compilation
2153     // based on run-time states. Since we can't know what the final PSInputEna
2154     // will look like, so we shouldn't do anything here and the user should take
2155     // responsibility for the correct programming.
2156     //
2157     // Otherwise, the following restrictions apply:
2158     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2159     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2160     //   enabled too.
2161     if (CallConv == CallingConv::AMDGPU_PS) {
2162       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2163            ((Info->getPSInputAddr() & 0xF) == 0 &&
2164             Info->isPSInputAllocated(11))) {
2165         CCInfo.AllocateReg(AMDGPU::VGPR0);
2166         CCInfo.AllocateReg(AMDGPU::VGPR1);
2167         Info->markPSInputAllocated(0);
2168         Info->markPSInputEnabled(0);
2169       }
2170       if (Subtarget->isAmdPalOS()) {
2171         // For isAmdPalOS, the user does not enable some bits after compilation
2172         // based on run-time states; the register values being generated here are
2173         // the final ones set in hardware. Therefore we need to apply the
2174         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2175         // a bit is set in PSInputAddr but not PSInputEnable is where the
2176         // frontend set up an input arg for a particular interpolation mode, but
2177         // nothing uses that input arg. Really we should have an earlier pass
2178         // that removes such an arg.)
2179         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2180         if ((PsInputBits & 0x7F) == 0 ||
2181             ((PsInputBits & 0xF) == 0 &&
2182              (PsInputBits >> 11 & 1)))
2183           Info->markPSInputEnabled(
2184               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2185       }
2186     }
2187 
2188     assert(!Info->hasDispatchPtr() &&
2189            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2190            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2191            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2192            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2193            !Info->hasWorkItemIDZ());
2194   } else if (IsKernel) {
2195     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2196   } else {
2197     Splits.append(Ins.begin(), Ins.end());
2198   }
2199 
2200   if (IsEntryFunc) {
2201     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2202     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2203   } else {
2204     // For the fixed ABI, pass workitem IDs in the last argument register.
2205     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2206       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2207   }
2208 
2209   if (IsKernel) {
2210     analyzeFormalArgumentsCompute(CCInfo, Ins);
2211   } else {
2212     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2213     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2214   }
2215 
2216   SmallVector<SDValue, 16> Chains;
2217 
2218   // FIXME: This is the minimum kernel argument alignment. We should improve
2219   // this to the maximum alignment of the arguments.
2220   //
2221   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2222   // kern arg offset.
2223   const unsigned KernelArgBaseAlign = 16;
2224 
2225    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2226     const ISD::InputArg &Arg = Ins[i];
2227     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2228       InVals.push_back(DAG.getUNDEF(Arg.VT));
2229       continue;
2230     }
2231 
2232     CCValAssign &VA = ArgLocs[ArgIdx++];
2233     MVT VT = VA.getLocVT();
2234 
2235     if (IsEntryFunc && VA.isMemLoc()) {
2236       VT = Ins[i].VT;
2237       EVT MemVT = VA.getLocVT();
2238 
2239       const uint64_t Offset = VA.getLocMemOffset();
2240       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2241 
2242       SDValue Arg = lowerKernargMemParameter(
2243         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2244       Chains.push_back(Arg.getValue(1));
2245 
2246       auto *ParamTy =
2247         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2248       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2249           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2250                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2251         // On SI local pointers are just offsets into LDS, so they are always
2252         // less than 16-bits.  On CI and newer they could potentially be
2253         // real pointers, so we can't guarantee their size.
2254         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2255                           DAG.getValueType(MVT::i16));
2256       }
2257 
2258       InVals.push_back(Arg);
2259       continue;
2260     } else if (!IsEntryFunc && VA.isMemLoc()) {
2261       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2262       InVals.push_back(Val);
2263       if (!Arg.Flags.isByVal())
2264         Chains.push_back(Val.getValue(1));
2265       continue;
2266     }
2267 
2268     assert(VA.isRegLoc() && "Parameter must be in a register!");
2269 
2270     Register Reg = VA.getLocReg();
2271     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2272     EVT ValVT = VA.getValVT();
2273 
2274     Reg = MF.addLiveIn(Reg, RC);
2275     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2276 
2277     if (Arg.Flags.isSRet()) {
2278       // The return object should be reasonably addressable.
2279 
2280       // FIXME: This helps when the return is a real sret. If it is a
2281       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2282       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2283       unsigned NumBits
2284         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2285       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2286         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2287     }
2288 
2289     // If this is an 8 or 16-bit value, it is really passed promoted
2290     // to 32 bits. Insert an assert[sz]ext to capture this, then
2291     // truncate to the right size.
2292     switch (VA.getLocInfo()) {
2293     case CCValAssign::Full:
2294       break;
2295     case CCValAssign::BCvt:
2296       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2297       break;
2298     case CCValAssign::SExt:
2299       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2300                         DAG.getValueType(ValVT));
2301       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2302       break;
2303     case CCValAssign::ZExt:
2304       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2305                         DAG.getValueType(ValVT));
2306       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2307       break;
2308     case CCValAssign::AExt:
2309       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2310       break;
2311     default:
2312       llvm_unreachable("Unknown loc info!");
2313     }
2314 
2315     InVals.push_back(Val);
2316   }
2317 
2318   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2319     // Special inputs come after user arguments.
2320     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2321   }
2322 
2323   // Start adding system SGPRs.
2324   if (IsEntryFunc) {
2325     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2326   } else {
2327     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2328     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2329   }
2330 
2331   auto &ArgUsageInfo =
2332     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2333   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2334 
2335   unsigned StackArgSize = CCInfo.getNextStackOffset();
2336   Info->setBytesInStackArgArea(StackArgSize);
2337 
2338   return Chains.empty() ? Chain :
2339     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2340 }
2341 
2342 // TODO: If return values can't fit in registers, we should return as many as
2343 // possible in registers before passing on stack.
2344 bool SITargetLowering::CanLowerReturn(
2345   CallingConv::ID CallConv,
2346   MachineFunction &MF, bool IsVarArg,
2347   const SmallVectorImpl<ISD::OutputArg> &Outs,
2348   LLVMContext &Context) const {
2349   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2350   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2351   // for shaders. Vector types should be explicitly handled by CC.
2352   if (AMDGPU::isEntryFunctionCC(CallConv))
2353     return true;
2354 
2355   SmallVector<CCValAssign, 16> RVLocs;
2356   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2357   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2358 }
2359 
2360 SDValue
2361 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2362                               bool isVarArg,
2363                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2364                               const SmallVectorImpl<SDValue> &OutVals,
2365                               const SDLoc &DL, SelectionDAG &DAG) const {
2366   MachineFunction &MF = DAG.getMachineFunction();
2367   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2368 
2369   if (AMDGPU::isKernel(CallConv)) {
2370     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2371                                              OutVals, DL, DAG);
2372   }
2373 
2374   bool IsShader = AMDGPU::isShader(CallConv);
2375 
2376   Info->setIfReturnsVoid(Outs.empty());
2377   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2378 
2379   // CCValAssign - represent the assignment of the return value to a location.
2380   SmallVector<CCValAssign, 48> RVLocs;
2381   SmallVector<ISD::OutputArg, 48> Splits;
2382 
2383   // CCState - Info about the registers and stack slots.
2384   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2385                  *DAG.getContext());
2386 
2387   // Analyze outgoing return values.
2388   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2389 
2390   SDValue Flag;
2391   SmallVector<SDValue, 48> RetOps;
2392   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2393 
2394   // Add return address for callable functions.
2395   if (!Info->isEntryFunction()) {
2396     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2397     SDValue ReturnAddrReg = CreateLiveInRegister(
2398       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2399 
2400     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2401         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2402         MVT::i64);
2403     Chain =
2404         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2405     Flag = Chain.getValue(1);
2406     RetOps.push_back(ReturnAddrVirtualReg);
2407   }
2408 
2409   // Copy the result values into the output registers.
2410   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2411        ++I, ++RealRVLocIdx) {
2412     CCValAssign &VA = RVLocs[I];
2413     assert(VA.isRegLoc() && "Can only return in registers!");
2414     // TODO: Partially return in registers if return values don't fit.
2415     SDValue Arg = OutVals[RealRVLocIdx];
2416 
2417     // Copied from other backends.
2418     switch (VA.getLocInfo()) {
2419     case CCValAssign::Full:
2420       break;
2421     case CCValAssign::BCvt:
2422       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2423       break;
2424     case CCValAssign::SExt:
2425       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2426       break;
2427     case CCValAssign::ZExt:
2428       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2429       break;
2430     case CCValAssign::AExt:
2431       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2432       break;
2433     default:
2434       llvm_unreachable("Unknown loc info!");
2435     }
2436 
2437     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2438     Flag = Chain.getValue(1);
2439     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2440   }
2441 
2442   // FIXME: Does sret work properly?
2443   if (!Info->isEntryFunction()) {
2444     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2445     const MCPhysReg *I =
2446       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2447     if (I) {
2448       for (; *I; ++I) {
2449         if (AMDGPU::SReg_64RegClass.contains(*I))
2450           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2451         else if (AMDGPU::SReg_32RegClass.contains(*I))
2452           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2453         else
2454           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2455       }
2456     }
2457   }
2458 
2459   // Update chain and glue.
2460   RetOps[0] = Chain;
2461   if (Flag.getNode())
2462     RetOps.push_back(Flag);
2463 
2464   unsigned Opc = AMDGPUISD::ENDPGM;
2465   if (!IsWaveEnd)
2466     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2467   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2468 }
2469 
2470 SDValue SITargetLowering::LowerCallResult(
2471     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2472     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2473     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2474     SDValue ThisVal) const {
2475   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2476 
2477   // Assign locations to each value returned by this call.
2478   SmallVector<CCValAssign, 16> RVLocs;
2479   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2480                  *DAG.getContext());
2481   CCInfo.AnalyzeCallResult(Ins, RetCC);
2482 
2483   // Copy all of the result registers out of their specified physreg.
2484   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2485     CCValAssign VA = RVLocs[i];
2486     SDValue Val;
2487 
2488     if (VA.isRegLoc()) {
2489       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2490       Chain = Val.getValue(1);
2491       InFlag = Val.getValue(2);
2492     } else if (VA.isMemLoc()) {
2493       report_fatal_error("TODO: return values in memory");
2494     } else
2495       llvm_unreachable("unknown argument location type");
2496 
2497     switch (VA.getLocInfo()) {
2498     case CCValAssign::Full:
2499       break;
2500     case CCValAssign::BCvt:
2501       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2502       break;
2503     case CCValAssign::ZExt:
2504       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2505                         DAG.getValueType(VA.getValVT()));
2506       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2507       break;
2508     case CCValAssign::SExt:
2509       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2510                         DAG.getValueType(VA.getValVT()));
2511       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2512       break;
2513     case CCValAssign::AExt:
2514       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2515       break;
2516     default:
2517       llvm_unreachable("Unknown loc info!");
2518     }
2519 
2520     InVals.push_back(Val);
2521   }
2522 
2523   return Chain;
2524 }
2525 
2526 // Add code to pass special inputs required depending on used features separate
2527 // from the explicit user arguments present in the IR.
2528 void SITargetLowering::passSpecialInputs(
2529     CallLoweringInfo &CLI,
2530     CCState &CCInfo,
2531     const SIMachineFunctionInfo &Info,
2532     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2533     SmallVectorImpl<SDValue> &MemOpChains,
2534     SDValue Chain) const {
2535   // If we don't have a call site, this was a call inserted by
2536   // legalization. These can never use special inputs.
2537   if (!CLI.CB)
2538     return;
2539 
2540   SelectionDAG &DAG = CLI.DAG;
2541   const SDLoc &DL = CLI.DL;
2542 
2543   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2544   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2545 
2546   const AMDGPUFunctionArgInfo *CalleeArgInfo
2547     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2548   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2549     auto &ArgUsageInfo =
2550       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2551     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2552   }
2553 
2554   // TODO: Unify with private memory register handling. This is complicated by
2555   // the fact that at least in kernels, the input argument is not necessarily
2556   // in the same location as the input.
2557   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2558     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2559     AMDGPUFunctionArgInfo::QUEUE_PTR,
2560     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2561     AMDGPUFunctionArgInfo::DISPATCH_ID,
2562     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2563     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2564     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2565   };
2566 
2567   for (auto InputID : InputRegs) {
2568     const ArgDescriptor *OutgoingArg;
2569     const TargetRegisterClass *ArgRC;
2570 
2571     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2572     if (!OutgoingArg)
2573       continue;
2574 
2575     const ArgDescriptor *IncomingArg;
2576     const TargetRegisterClass *IncomingArgRC;
2577     std::tie(IncomingArg, IncomingArgRC)
2578       = CallerArgInfo.getPreloadedValue(InputID);
2579     assert(IncomingArgRC == ArgRC);
2580 
2581     // All special arguments are ints for now.
2582     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2583     SDValue InputReg;
2584 
2585     if (IncomingArg) {
2586       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2587     } else {
2588       // The implicit arg ptr is special because it doesn't have a corresponding
2589       // input for kernels, and is computed from the kernarg segment pointer.
2590       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2591       InputReg = getImplicitArgPtr(DAG, DL);
2592     }
2593 
2594     if (OutgoingArg->isRegister()) {
2595       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2596       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2597         report_fatal_error("failed to allocate implicit input argument");
2598     } else {
2599       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2600       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2601                                               SpecialArgOffset);
2602       MemOpChains.push_back(ArgStore);
2603     }
2604   }
2605 
2606   // Pack workitem IDs into a single register or pass it as is if already
2607   // packed.
2608   const ArgDescriptor *OutgoingArg;
2609   const TargetRegisterClass *ArgRC;
2610 
2611   std::tie(OutgoingArg, ArgRC) =
2612     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2613   if (!OutgoingArg)
2614     std::tie(OutgoingArg, ArgRC) =
2615       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2616   if (!OutgoingArg)
2617     std::tie(OutgoingArg, ArgRC) =
2618       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2619   if (!OutgoingArg)
2620     return;
2621 
2622   const ArgDescriptor *IncomingArgX
2623     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2624   const ArgDescriptor *IncomingArgY
2625     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2626   const ArgDescriptor *IncomingArgZ
2627     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2628 
2629   SDValue InputReg;
2630   SDLoc SL;
2631 
2632   // If incoming ids are not packed we need to pack them.
2633   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2634     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2635 
2636   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2637     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2638     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2639                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2640     InputReg = InputReg.getNode() ?
2641                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2642   }
2643 
2644   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2645     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2646     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2647                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2648     InputReg = InputReg.getNode() ?
2649                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2650   }
2651 
2652   if (!InputReg.getNode()) {
2653     // Workitem ids are already packed, any of present incoming arguments
2654     // will carry all required fields.
2655     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2656       IncomingArgX ? *IncomingArgX :
2657       IncomingArgY ? *IncomingArgY :
2658                      *IncomingArgZ, ~0u);
2659     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2660   }
2661 
2662   if (OutgoingArg->isRegister()) {
2663     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2664     CCInfo.AllocateReg(OutgoingArg->getRegister());
2665   } else {
2666     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2667     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2668                                             SpecialArgOffset);
2669     MemOpChains.push_back(ArgStore);
2670   }
2671 }
2672 
2673 static bool canGuaranteeTCO(CallingConv::ID CC) {
2674   return CC == CallingConv::Fast;
2675 }
2676 
2677 /// Return true if we might ever do TCO for calls with this calling convention.
2678 static bool mayTailCallThisCC(CallingConv::ID CC) {
2679   switch (CC) {
2680   case CallingConv::C:
2681     return true;
2682   default:
2683     return canGuaranteeTCO(CC);
2684   }
2685 }
2686 
2687 bool SITargetLowering::isEligibleForTailCallOptimization(
2688     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2689     const SmallVectorImpl<ISD::OutputArg> &Outs,
2690     const SmallVectorImpl<SDValue> &OutVals,
2691     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2692   if (!mayTailCallThisCC(CalleeCC))
2693     return false;
2694 
2695   MachineFunction &MF = DAG.getMachineFunction();
2696   const Function &CallerF = MF.getFunction();
2697   CallingConv::ID CallerCC = CallerF.getCallingConv();
2698   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2699   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2700 
2701   // Kernels aren't callable, and don't have a live in return address so it
2702   // doesn't make sense to do a tail call with entry functions.
2703   if (!CallerPreserved)
2704     return false;
2705 
2706   bool CCMatch = CallerCC == CalleeCC;
2707 
2708   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2709     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2710       return true;
2711     return false;
2712   }
2713 
2714   // TODO: Can we handle var args?
2715   if (IsVarArg)
2716     return false;
2717 
2718   for (const Argument &Arg : CallerF.args()) {
2719     if (Arg.hasByValAttr())
2720       return false;
2721   }
2722 
2723   LLVMContext &Ctx = *DAG.getContext();
2724 
2725   // Check that the call results are passed in the same way.
2726   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2727                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2728                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2729     return false;
2730 
2731   // The callee has to preserve all registers the caller needs to preserve.
2732   if (!CCMatch) {
2733     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2734     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2735       return false;
2736   }
2737 
2738   // Nothing more to check if the callee is taking no arguments.
2739   if (Outs.empty())
2740     return true;
2741 
2742   SmallVector<CCValAssign, 16> ArgLocs;
2743   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2744 
2745   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2746 
2747   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2748   // If the stack arguments for this call do not fit into our own save area then
2749   // the call cannot be made tail.
2750   // TODO: Is this really necessary?
2751   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2752     return false;
2753 
2754   const MachineRegisterInfo &MRI = MF.getRegInfo();
2755   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2756 }
2757 
2758 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2759   if (!CI->isTailCall())
2760     return false;
2761 
2762   const Function *ParentFn = CI->getParent()->getParent();
2763   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2764     return false;
2765   return true;
2766 }
2767 
2768 // The wave scratch offset register is used as the global base pointer.
2769 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2770                                     SmallVectorImpl<SDValue> &InVals) const {
2771   SelectionDAG &DAG = CLI.DAG;
2772   const SDLoc &DL = CLI.DL;
2773   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2774   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2775   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2776   SDValue Chain = CLI.Chain;
2777   SDValue Callee = CLI.Callee;
2778   bool &IsTailCall = CLI.IsTailCall;
2779   CallingConv::ID CallConv = CLI.CallConv;
2780   bool IsVarArg = CLI.IsVarArg;
2781   bool IsSibCall = false;
2782   bool IsThisReturn = false;
2783   MachineFunction &MF = DAG.getMachineFunction();
2784 
2785   if (Callee.isUndef() || isNullConstant(Callee)) {
2786     if (!CLI.IsTailCall) {
2787       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2788         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2789     }
2790 
2791     return Chain;
2792   }
2793 
2794   if (IsVarArg) {
2795     return lowerUnhandledCall(CLI, InVals,
2796                               "unsupported call to variadic function ");
2797   }
2798 
2799   if (!CLI.CB)
2800     report_fatal_error("unsupported libcall legalization");
2801 
2802   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2803       !CLI.CB->getCalledFunction()) {
2804     return lowerUnhandledCall(CLI, InVals,
2805                               "unsupported indirect call to function ");
2806   }
2807 
2808   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2809     return lowerUnhandledCall(CLI, InVals,
2810                               "unsupported required tail call to function ");
2811   }
2812 
2813   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2814     // Note the issue is with the CC of the calling function, not of the call
2815     // itself.
2816     return lowerUnhandledCall(CLI, InVals,
2817                           "unsupported call from graphics shader of function ");
2818   }
2819 
2820   if (IsTailCall) {
2821     IsTailCall = isEligibleForTailCallOptimization(
2822       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2823     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2824       report_fatal_error("failed to perform tail call elimination on a call "
2825                          "site marked musttail");
2826     }
2827 
2828     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2829 
2830     // A sibling call is one where we're under the usual C ABI and not planning
2831     // to change that but can still do a tail call:
2832     if (!TailCallOpt && IsTailCall)
2833       IsSibCall = true;
2834 
2835     if (IsTailCall)
2836       ++NumTailCalls;
2837   }
2838 
2839   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2840   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2841   SmallVector<SDValue, 8> MemOpChains;
2842 
2843   // Analyze operands of the call, assigning locations to each operand.
2844   SmallVector<CCValAssign, 16> ArgLocs;
2845   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2846   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2847 
2848   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2849     // With a fixed ABI, allocate fixed registers before user arguments.
2850     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2851   }
2852 
2853   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2854 
2855   // Get a count of how many bytes are to be pushed on the stack.
2856   unsigned NumBytes = CCInfo.getNextStackOffset();
2857 
2858   if (IsSibCall) {
2859     // Since we're not changing the ABI to make this a tail call, the memory
2860     // operands are already available in the caller's incoming argument space.
2861     NumBytes = 0;
2862   }
2863 
2864   // FPDiff is the byte offset of the call's argument area from the callee's.
2865   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2866   // by this amount for a tail call. In a sibling call it must be 0 because the
2867   // caller will deallocate the entire stack and the callee still expects its
2868   // arguments to begin at SP+0. Completely unused for non-tail calls.
2869   int32_t FPDiff = 0;
2870   MachineFrameInfo &MFI = MF.getFrameInfo();
2871 
2872   // Adjust the stack pointer for the new arguments...
2873   // These operations are automatically eliminated by the prolog/epilog pass
2874   if (!IsSibCall) {
2875     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2876 
2877     SmallVector<SDValue, 4> CopyFromChains;
2878 
2879     // In the HSA case, this should be an identity copy.
2880     SDValue ScratchRSrcReg
2881       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2882     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2883     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2884     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2885   }
2886 
2887   MVT PtrVT = MVT::i32;
2888 
2889   // Walk the register/memloc assignments, inserting copies/loads.
2890   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2891     CCValAssign &VA = ArgLocs[i];
2892     SDValue Arg = OutVals[i];
2893 
2894     // Promote the value if needed.
2895     switch (VA.getLocInfo()) {
2896     case CCValAssign::Full:
2897       break;
2898     case CCValAssign::BCvt:
2899       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2900       break;
2901     case CCValAssign::ZExt:
2902       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2903       break;
2904     case CCValAssign::SExt:
2905       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2906       break;
2907     case CCValAssign::AExt:
2908       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2909       break;
2910     case CCValAssign::FPExt:
2911       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2912       break;
2913     default:
2914       llvm_unreachable("Unknown loc info!");
2915     }
2916 
2917     if (VA.isRegLoc()) {
2918       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2919     } else {
2920       assert(VA.isMemLoc());
2921 
2922       SDValue DstAddr;
2923       MachinePointerInfo DstInfo;
2924 
2925       unsigned LocMemOffset = VA.getLocMemOffset();
2926       int32_t Offset = LocMemOffset;
2927 
2928       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2929       MaybeAlign Alignment;
2930 
2931       if (IsTailCall) {
2932         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2933         unsigned OpSize = Flags.isByVal() ?
2934           Flags.getByValSize() : VA.getValVT().getStoreSize();
2935 
2936         // FIXME: We can have better than the minimum byval required alignment.
2937         Alignment =
2938             Flags.isByVal()
2939                 ? Flags.getNonZeroByValAlign()
2940                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2941 
2942         Offset = Offset + FPDiff;
2943         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2944 
2945         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2946         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2947 
2948         // Make sure any stack arguments overlapping with where we're storing
2949         // are loaded before this eventual operation. Otherwise they'll be
2950         // clobbered.
2951 
2952         // FIXME: Why is this really necessary? This seems to just result in a
2953         // lot of code to copy the stack and write them back to the same
2954         // locations, which are supposed to be immutable?
2955         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2956       } else {
2957         DstAddr = PtrOff;
2958         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2959         Alignment =
2960             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2961       }
2962 
2963       if (Outs[i].Flags.isByVal()) {
2964         SDValue SizeNode =
2965             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2966         SDValue Cpy =
2967             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2968                           Outs[i].Flags.getNonZeroByValAlign(),
2969                           /*isVol = */ false, /*AlwaysInline = */ true,
2970                           /*isTailCall = */ false, DstInfo,
2971                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2972 
2973         MemOpChains.push_back(Cpy);
2974       } else {
2975         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2976                                      Alignment ? Alignment->value() : 0);
2977         MemOpChains.push_back(Store);
2978       }
2979     }
2980   }
2981 
2982   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2983     // Copy special input registers after user input arguments.
2984     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2985   }
2986 
2987   if (!MemOpChains.empty())
2988     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2989 
2990   // Build a sequence of copy-to-reg nodes chained together with token chain
2991   // and flag operands which copy the outgoing args into the appropriate regs.
2992   SDValue InFlag;
2993   for (auto &RegToPass : RegsToPass) {
2994     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2995                              RegToPass.second, InFlag);
2996     InFlag = Chain.getValue(1);
2997   }
2998 
2999 
3000   SDValue PhysReturnAddrReg;
3001   if (IsTailCall) {
3002     // Since the return is being combined with the call, we need to pass on the
3003     // return address.
3004 
3005     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3006     SDValue ReturnAddrReg = CreateLiveInRegister(
3007       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3008 
3009     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3010                                         MVT::i64);
3011     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3012     InFlag = Chain.getValue(1);
3013   }
3014 
3015   // We don't usually want to end the call-sequence here because we would tidy
3016   // the frame up *after* the call, however in the ABI-changing tail-call case
3017   // we've carefully laid out the parameters so that when sp is reset they'll be
3018   // in the correct location.
3019   if (IsTailCall && !IsSibCall) {
3020     Chain = DAG.getCALLSEQ_END(Chain,
3021                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3022                                DAG.getTargetConstant(0, DL, MVT::i32),
3023                                InFlag, DL);
3024     InFlag = Chain.getValue(1);
3025   }
3026 
3027   std::vector<SDValue> Ops;
3028   Ops.push_back(Chain);
3029   Ops.push_back(Callee);
3030   // Add a redundant copy of the callee global which will not be legalized, as
3031   // we need direct access to the callee later.
3032   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3033     const GlobalValue *GV = GSD->getGlobal();
3034     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3035   } else {
3036     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3037   }
3038 
3039   if (IsTailCall) {
3040     // Each tail call may have to adjust the stack by a different amount, so
3041     // this information must travel along with the operation for eventual
3042     // consumption by emitEpilogue.
3043     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3044 
3045     Ops.push_back(PhysReturnAddrReg);
3046   }
3047 
3048   // Add argument registers to the end of the list so that they are known live
3049   // into the call.
3050   for (auto &RegToPass : RegsToPass) {
3051     Ops.push_back(DAG.getRegister(RegToPass.first,
3052                                   RegToPass.second.getValueType()));
3053   }
3054 
3055   // Add a register mask operand representing the call-preserved registers.
3056 
3057   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3058   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3059   assert(Mask && "Missing call preserved mask for calling convention");
3060   Ops.push_back(DAG.getRegisterMask(Mask));
3061 
3062   if (InFlag.getNode())
3063     Ops.push_back(InFlag);
3064 
3065   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3066 
3067   // If we're doing a tall call, use a TC_RETURN here rather than an
3068   // actual call instruction.
3069   if (IsTailCall) {
3070     MFI.setHasTailCall();
3071     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3072   }
3073 
3074   // Returns a chain and a flag for retval copy to use.
3075   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3076   Chain = Call.getValue(0);
3077   InFlag = Call.getValue(1);
3078 
3079   uint64_t CalleePopBytes = NumBytes;
3080   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3081                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3082                              InFlag, DL);
3083   if (!Ins.empty())
3084     InFlag = Chain.getValue(1);
3085 
3086   // Handle result values, copying them out of physregs into vregs that we
3087   // return.
3088   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3089                          InVals, IsThisReturn,
3090                          IsThisReturn ? OutVals[0] : SDValue());
3091 }
3092 
3093 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3094 // except for applying the wave size scale to the increment amount.
3095 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3096     SDValue Op, SelectionDAG &DAG) const {
3097   const MachineFunction &MF = DAG.getMachineFunction();
3098   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3099 
3100   SDLoc dl(Op);
3101   EVT VT = Op.getValueType();
3102   SDValue Tmp1 = Op;
3103   SDValue Tmp2 = Op.getValue(1);
3104   SDValue Tmp3 = Op.getOperand(2);
3105   SDValue Chain = Tmp1.getOperand(0);
3106 
3107   Register SPReg = Info->getStackPtrOffsetReg();
3108 
3109   // Chain the dynamic stack allocation so that it doesn't modify the stack
3110   // pointer when other instructions are using the stack.
3111   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3112 
3113   SDValue Size  = Tmp2.getOperand(1);
3114   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3115   Chain = SP.getValue(1);
3116   unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
3117   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3118   const TargetFrameLowering *TFL = ST.getFrameLowering();
3119   unsigned Opc =
3120     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3121     ISD::ADD : ISD::SUB;
3122 
3123   SDValue ScaledSize = DAG.getNode(
3124       ISD::SHL, dl, VT, Size,
3125       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3126 
3127   unsigned StackAlign = TFL->getStackAlignment();
3128   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3129   if (Align > StackAlign) {
3130     Tmp1 = DAG.getNode(
3131       ISD::AND, dl, VT, Tmp1,
3132       DAG.getConstant(-(uint64_t)Align << ST.getWavefrontSizeLog2(), dl, VT));
3133   }
3134 
3135   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3136   Tmp2 = DAG.getCALLSEQ_END(
3137       Chain, DAG.getIntPtrConstant(0, dl, true),
3138       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3139 
3140   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3141 }
3142 
3143 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3144                                                   SelectionDAG &DAG) const {
3145   // We only handle constant sizes here to allow non-entry block, static sized
3146   // allocas. A truly dynamic value is more difficult to support because we
3147   // don't know if the size value is uniform or not. If the size isn't uniform,
3148   // we would need to do a wave reduction to get the maximum size to know how
3149   // much to increment the uniform stack pointer.
3150   SDValue Size = Op.getOperand(1);
3151   if (isa<ConstantSDNode>(Size))
3152       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3153 
3154   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3155 }
3156 
3157 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3158                                              const MachineFunction &MF) const {
3159   Register Reg = StringSwitch<Register>(RegName)
3160     .Case("m0", AMDGPU::M0)
3161     .Case("exec", AMDGPU::EXEC)
3162     .Case("exec_lo", AMDGPU::EXEC_LO)
3163     .Case("exec_hi", AMDGPU::EXEC_HI)
3164     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3165     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3166     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3167     .Default(Register());
3168 
3169   if (Reg == AMDGPU::NoRegister) {
3170     report_fatal_error(Twine("invalid register name \""
3171                              + StringRef(RegName)  + "\"."));
3172 
3173   }
3174 
3175   if (!Subtarget->hasFlatScrRegister() &&
3176        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3177     report_fatal_error(Twine("invalid register \""
3178                              + StringRef(RegName)  + "\" for subtarget."));
3179   }
3180 
3181   switch (Reg) {
3182   case AMDGPU::M0:
3183   case AMDGPU::EXEC_LO:
3184   case AMDGPU::EXEC_HI:
3185   case AMDGPU::FLAT_SCR_LO:
3186   case AMDGPU::FLAT_SCR_HI:
3187     if (VT.getSizeInBits() == 32)
3188       return Reg;
3189     break;
3190   case AMDGPU::EXEC:
3191   case AMDGPU::FLAT_SCR:
3192     if (VT.getSizeInBits() == 64)
3193       return Reg;
3194     break;
3195   default:
3196     llvm_unreachable("missing register type checking");
3197   }
3198 
3199   report_fatal_error(Twine("invalid type for register \""
3200                            + StringRef(RegName) + "\"."));
3201 }
3202 
3203 // If kill is not the last instruction, split the block so kill is always a
3204 // proper terminator.
3205 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3206                                                     MachineBasicBlock *BB) const {
3207   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3208 
3209   MachineBasicBlock::iterator SplitPoint(&MI);
3210   ++SplitPoint;
3211 
3212   if (SplitPoint == BB->end()) {
3213     // Don't bother with a new block.
3214     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3215     return BB;
3216   }
3217 
3218   MachineFunction *MF = BB->getParent();
3219   MachineBasicBlock *SplitBB
3220     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3221 
3222   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3223   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3224 
3225   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3226   BB->addSuccessor(SplitBB);
3227 
3228   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3229   return SplitBB;
3230 }
3231 
3232 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3233 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3234 // be the first instruction in the remainder block.
3235 //
3236 /// \returns { LoopBody, Remainder }
3237 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3238 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3239   MachineFunction *MF = MBB.getParent();
3240   MachineBasicBlock::iterator I(&MI);
3241 
3242   // To insert the loop we need to split the block. Move everything after this
3243   // point to a new block, and insert a new empty block between the two.
3244   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3245   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3246   MachineFunction::iterator MBBI(MBB);
3247   ++MBBI;
3248 
3249   MF->insert(MBBI, LoopBB);
3250   MF->insert(MBBI, RemainderBB);
3251 
3252   LoopBB->addSuccessor(LoopBB);
3253   LoopBB->addSuccessor(RemainderBB);
3254 
3255   // Move the rest of the block into a new block.
3256   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3257 
3258   if (InstInLoop) {
3259     auto Next = std::next(I);
3260 
3261     // Move instruction to loop body.
3262     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3263 
3264     // Move the rest of the block.
3265     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3266   } else {
3267     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3268   }
3269 
3270   MBB.addSuccessor(LoopBB);
3271 
3272   return std::make_pair(LoopBB, RemainderBB);
3273 }
3274 
3275 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3276 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3277   MachineBasicBlock *MBB = MI.getParent();
3278   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3279   auto I = MI.getIterator();
3280   auto E = std::next(I);
3281 
3282   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3283     .addImm(0);
3284 
3285   MIBundleBuilder Bundler(*MBB, I, E);
3286   finalizeBundle(*MBB, Bundler.begin());
3287 }
3288 
3289 MachineBasicBlock *
3290 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3291                                          MachineBasicBlock *BB) const {
3292   const DebugLoc &DL = MI.getDebugLoc();
3293 
3294   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3295 
3296   MachineBasicBlock *LoopBB;
3297   MachineBasicBlock *RemainderBB;
3298   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3299 
3300   // Apparently kill flags are only valid if the def is in the same block?
3301   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3302     Src->setIsKill(false);
3303 
3304   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3305 
3306   MachineBasicBlock::iterator I = LoopBB->end();
3307 
3308   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3309     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3310 
3311   // Clear TRAP_STS.MEM_VIOL
3312   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3313     .addImm(0)
3314     .addImm(EncodedReg);
3315 
3316   bundleInstWithWaitcnt(MI);
3317 
3318   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3319 
3320   // Load and check TRAP_STS.MEM_VIOL
3321   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3322     .addImm(EncodedReg);
3323 
3324   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3325   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3326     .addReg(Reg, RegState::Kill)
3327     .addImm(0);
3328   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3329     .addMBB(LoopBB);
3330 
3331   return RemainderBB;
3332 }
3333 
3334 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3335 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3336 // will only do one iteration. In the worst case, this will loop 64 times.
3337 //
3338 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3339 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3340   const SIInstrInfo *TII,
3341   MachineRegisterInfo &MRI,
3342   MachineBasicBlock &OrigBB,
3343   MachineBasicBlock &LoopBB,
3344   const DebugLoc &DL,
3345   const MachineOperand &IdxReg,
3346   unsigned InitReg,
3347   unsigned ResultReg,
3348   unsigned PhiReg,
3349   unsigned InitSaveExecReg,
3350   int Offset,
3351   bool UseGPRIdxMode,
3352   bool IsIndirectSrc) {
3353   MachineFunction *MF = OrigBB.getParent();
3354   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3355   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3356   MachineBasicBlock::iterator I = LoopBB.begin();
3357 
3358   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3359   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3360   Register NewExec = MRI.createVirtualRegister(BoolRC);
3361   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3362   Register CondReg = MRI.createVirtualRegister(BoolRC);
3363 
3364   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3365     .addReg(InitReg)
3366     .addMBB(&OrigBB)
3367     .addReg(ResultReg)
3368     .addMBB(&LoopBB);
3369 
3370   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3371     .addReg(InitSaveExecReg)
3372     .addMBB(&OrigBB)
3373     .addReg(NewExec)
3374     .addMBB(&LoopBB);
3375 
3376   // Read the next variant <- also loop target.
3377   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3378     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3379 
3380   // Compare the just read M0 value to all possible Idx values.
3381   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3382     .addReg(CurrentIdxReg)
3383     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3384 
3385   // Update EXEC, save the original EXEC value to VCC.
3386   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3387                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3388           NewExec)
3389     .addReg(CondReg, RegState::Kill);
3390 
3391   MRI.setSimpleHint(NewExec, CondReg);
3392 
3393   if (UseGPRIdxMode) {
3394     unsigned IdxReg;
3395     if (Offset == 0) {
3396       IdxReg = CurrentIdxReg;
3397     } else {
3398       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3399       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3400         .addReg(CurrentIdxReg, RegState::Kill)
3401         .addImm(Offset);
3402     }
3403     unsigned IdxMode = IsIndirectSrc ?
3404       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3405     MachineInstr *SetOn =
3406       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3407       .addReg(IdxReg, RegState::Kill)
3408       .addImm(IdxMode);
3409     SetOn->getOperand(3).setIsUndef();
3410   } else {
3411     // Move index from VCC into M0
3412     if (Offset == 0) {
3413       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3414         .addReg(CurrentIdxReg, RegState::Kill);
3415     } else {
3416       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3417         .addReg(CurrentIdxReg, RegState::Kill)
3418         .addImm(Offset);
3419     }
3420   }
3421 
3422   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3423   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3424   MachineInstr *InsertPt =
3425     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3426                                                   : AMDGPU::S_XOR_B64_term), Exec)
3427       .addReg(Exec)
3428       .addReg(NewExec);
3429 
3430   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3431   // s_cbranch_scc0?
3432 
3433   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3434   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3435     .addMBB(&LoopBB);
3436 
3437   return InsertPt->getIterator();
3438 }
3439 
3440 // This has slightly sub-optimal regalloc when the source vector is killed by
3441 // the read. The register allocator does not understand that the kill is
3442 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3443 // subregister from it, using 1 more VGPR than necessary. This was saved when
3444 // this was expanded after register allocation.
3445 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3446                                                   MachineBasicBlock &MBB,
3447                                                   MachineInstr &MI,
3448                                                   unsigned InitResultReg,
3449                                                   unsigned PhiReg,
3450                                                   int Offset,
3451                                                   bool UseGPRIdxMode,
3452                                                   bool IsIndirectSrc) {
3453   MachineFunction *MF = MBB.getParent();
3454   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3455   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3456   MachineRegisterInfo &MRI = MF->getRegInfo();
3457   const DebugLoc &DL = MI.getDebugLoc();
3458   MachineBasicBlock::iterator I(&MI);
3459 
3460   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3461   Register DstReg = MI.getOperand(0).getReg();
3462   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3463   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3464   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3465   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3466 
3467   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3468 
3469   // Save the EXEC mask
3470   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3471     .addReg(Exec);
3472 
3473   MachineBasicBlock *LoopBB;
3474   MachineBasicBlock *RemainderBB;
3475   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3476 
3477   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3478 
3479   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3480                                       InitResultReg, DstReg, PhiReg, TmpExec,
3481                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3482   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3483   MachineFunction::iterator MBBI(LoopBB);
3484   ++MBBI;
3485   MF->insert(MBBI, LandingPad);
3486   LoopBB->removeSuccessor(RemainderBB);
3487   LandingPad->addSuccessor(RemainderBB);
3488   LoopBB->addSuccessor(LandingPad);
3489   MachineBasicBlock::iterator First = LandingPad->begin();
3490   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3491     .addReg(SaveExec);
3492 
3493   return InsPt;
3494 }
3495 
3496 // Returns subreg index, offset
3497 static std::pair<unsigned, int>
3498 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3499                             const TargetRegisterClass *SuperRC,
3500                             unsigned VecReg,
3501                             int Offset) {
3502   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3503 
3504   // Skip out of bounds offsets, or else we would end up using an undefined
3505   // register.
3506   if (Offset >= NumElts || Offset < 0)
3507     return std::make_pair(AMDGPU::sub0, Offset);
3508 
3509   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3510 }
3511 
3512 // Return true if the index is an SGPR and was set.
3513 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3514                                  MachineRegisterInfo &MRI,
3515                                  MachineInstr &MI,
3516                                  int Offset,
3517                                  bool UseGPRIdxMode,
3518                                  bool IsIndirectSrc) {
3519   MachineBasicBlock *MBB = MI.getParent();
3520   const DebugLoc &DL = MI.getDebugLoc();
3521   MachineBasicBlock::iterator I(&MI);
3522 
3523   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3524   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3525 
3526   assert(Idx->getReg() != AMDGPU::NoRegister);
3527 
3528   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3529     return false;
3530 
3531   if (UseGPRIdxMode) {
3532     unsigned IdxMode = IsIndirectSrc ?
3533       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3534     if (Offset == 0) {
3535       MachineInstr *SetOn =
3536           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3537               .add(*Idx)
3538               .addImm(IdxMode);
3539 
3540       SetOn->getOperand(3).setIsUndef();
3541     } else {
3542       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3543       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3544           .add(*Idx)
3545           .addImm(Offset);
3546       MachineInstr *SetOn =
3547         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3548         .addReg(Tmp, RegState::Kill)
3549         .addImm(IdxMode);
3550 
3551       SetOn->getOperand(3).setIsUndef();
3552     }
3553 
3554     return true;
3555   }
3556 
3557   if (Offset == 0) {
3558     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3559       .add(*Idx);
3560   } else {
3561     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3562       .add(*Idx)
3563       .addImm(Offset);
3564   }
3565 
3566   return true;
3567 }
3568 
3569 // Control flow needs to be inserted if indexing with a VGPR.
3570 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3571                                           MachineBasicBlock &MBB,
3572                                           const GCNSubtarget &ST) {
3573   const SIInstrInfo *TII = ST.getInstrInfo();
3574   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3575   MachineFunction *MF = MBB.getParent();
3576   MachineRegisterInfo &MRI = MF->getRegInfo();
3577 
3578   Register Dst = MI.getOperand(0).getReg();
3579   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3580   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3581 
3582   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3583 
3584   unsigned SubReg;
3585   std::tie(SubReg, Offset)
3586     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3587 
3588   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3589 
3590   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3591     MachineBasicBlock::iterator I(&MI);
3592     const DebugLoc &DL = MI.getDebugLoc();
3593 
3594     if (UseGPRIdxMode) {
3595       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3596       // to avoid interfering with other uses, so probably requires a new
3597       // optimization pass.
3598       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3599         .addReg(SrcReg, RegState::Undef, SubReg)
3600         .addReg(SrcReg, RegState::Implicit)
3601         .addReg(AMDGPU::M0, RegState::Implicit);
3602       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3603     } else {
3604       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3605         .addReg(SrcReg, RegState::Undef, SubReg)
3606         .addReg(SrcReg, RegState::Implicit);
3607     }
3608 
3609     MI.eraseFromParent();
3610 
3611     return &MBB;
3612   }
3613 
3614   const DebugLoc &DL = MI.getDebugLoc();
3615   MachineBasicBlock::iterator I(&MI);
3616 
3617   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3618   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3619 
3620   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3621 
3622   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3623                               Offset, UseGPRIdxMode, true);
3624   MachineBasicBlock *LoopBB = InsPt->getParent();
3625 
3626   if (UseGPRIdxMode) {
3627     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3628       .addReg(SrcReg, RegState::Undef, SubReg)
3629       .addReg(SrcReg, RegState::Implicit)
3630       .addReg(AMDGPU::M0, RegState::Implicit);
3631     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3632   } else {
3633     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3634       .addReg(SrcReg, RegState::Undef, SubReg)
3635       .addReg(SrcReg, RegState::Implicit);
3636   }
3637 
3638   MI.eraseFromParent();
3639 
3640   return LoopBB;
3641 }
3642 
3643 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3644                                           MachineBasicBlock &MBB,
3645                                           const GCNSubtarget &ST) {
3646   const SIInstrInfo *TII = ST.getInstrInfo();
3647   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3648   MachineFunction *MF = MBB.getParent();
3649   MachineRegisterInfo &MRI = MF->getRegInfo();
3650 
3651   Register Dst = MI.getOperand(0).getReg();
3652   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3653   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3654   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3655   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3656   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3657 
3658   // This can be an immediate, but will be folded later.
3659   assert(Val->getReg());
3660 
3661   unsigned SubReg;
3662   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3663                                                          SrcVec->getReg(),
3664                                                          Offset);
3665   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3666 
3667   if (Idx->getReg() == AMDGPU::NoRegister) {
3668     MachineBasicBlock::iterator I(&MI);
3669     const DebugLoc &DL = MI.getDebugLoc();
3670 
3671     assert(Offset == 0);
3672 
3673     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3674         .add(*SrcVec)
3675         .add(*Val)
3676         .addImm(SubReg);
3677 
3678     MI.eraseFromParent();
3679     return &MBB;
3680   }
3681 
3682   const MCInstrDesc &MovRelDesc
3683     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3684 
3685   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3686     MachineBasicBlock::iterator I(&MI);
3687     const DebugLoc &DL = MI.getDebugLoc();
3688     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3689       .addReg(SrcVec->getReg())
3690       .add(*Val)
3691       .addImm(SubReg);
3692     if (UseGPRIdxMode)
3693       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3694 
3695     MI.eraseFromParent();
3696     return &MBB;
3697   }
3698 
3699   if (Val->isReg())
3700     MRI.clearKillFlags(Val->getReg());
3701 
3702   const DebugLoc &DL = MI.getDebugLoc();
3703 
3704   Register PhiReg = MRI.createVirtualRegister(VecRC);
3705 
3706   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3707                               Offset, UseGPRIdxMode, false);
3708   MachineBasicBlock *LoopBB = InsPt->getParent();
3709 
3710   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3711     .addReg(PhiReg)
3712     .add(*Val)
3713     .addImm(AMDGPU::sub0);
3714   if (UseGPRIdxMode)
3715     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3716 
3717   MI.eraseFromParent();
3718   return LoopBB;
3719 }
3720 
3721 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3722   MachineInstr &MI, MachineBasicBlock *BB) const {
3723 
3724   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3725   MachineFunction *MF = BB->getParent();
3726   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3727 
3728   switch (MI.getOpcode()) {
3729   case AMDGPU::S_UADDO_PSEUDO:
3730   case AMDGPU::S_USUBO_PSEUDO: {
3731     const DebugLoc &DL = MI.getDebugLoc();
3732     MachineOperand &Dest0 = MI.getOperand(0);
3733     MachineOperand &Dest1 = MI.getOperand(1);
3734     MachineOperand &Src0 = MI.getOperand(2);
3735     MachineOperand &Src1 = MI.getOperand(3);
3736 
3737     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3738                        ? AMDGPU::S_ADD_I32
3739                        : AMDGPU::S_SUB_I32;
3740     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3741 
3742     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3743         .addImm(1)
3744         .addImm(0);
3745 
3746     MI.eraseFromParent();
3747     return BB;
3748   }
3749   case AMDGPU::S_ADD_U64_PSEUDO:
3750   case AMDGPU::S_SUB_U64_PSEUDO: {
3751     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3752     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3753     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3754     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3755     const DebugLoc &DL = MI.getDebugLoc();
3756 
3757     MachineOperand &Dest = MI.getOperand(0);
3758     MachineOperand &Src0 = MI.getOperand(1);
3759     MachineOperand &Src1 = MI.getOperand(2);
3760 
3761     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3762     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3763 
3764     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3765         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3766     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3767         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3768 
3769     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3770         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3771     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3772         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3773 
3774     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3775 
3776     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3777     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3778     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3779     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3780     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3781         .addReg(DestSub0)
3782         .addImm(AMDGPU::sub0)
3783         .addReg(DestSub1)
3784         .addImm(AMDGPU::sub1);
3785     MI.eraseFromParent();
3786     return BB;
3787   }
3788   case AMDGPU::V_ADD_U64_PSEUDO:
3789   case AMDGPU::V_SUB_U64_PSEUDO: {
3790     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3791     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3792     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3793     const DebugLoc &DL = MI.getDebugLoc();
3794 
3795     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3796 
3797     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3798 
3799     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3800     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3801 
3802     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3803     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3804 
3805     MachineOperand &Dest = MI.getOperand(0);
3806     MachineOperand &Src0 = MI.getOperand(1);
3807     MachineOperand &Src1 = MI.getOperand(2);
3808 
3809     const TargetRegisterClass *Src0RC = Src0.isReg()
3810                                             ? MRI.getRegClass(Src0.getReg())
3811                                             : &AMDGPU::VReg_64RegClass;
3812     const TargetRegisterClass *Src1RC = Src1.isReg()
3813                                             ? MRI.getRegClass(Src1.getReg())
3814                                             : &AMDGPU::VReg_64RegClass;
3815 
3816     const TargetRegisterClass *Src0SubRC =
3817         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3818     const TargetRegisterClass *Src1SubRC =
3819         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3820 
3821     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3822         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3823     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3824         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3825 
3826     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3827         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3828     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3829         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3830 
3831     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
3832     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3833                                .addReg(CarryReg, RegState::Define)
3834                                .add(SrcReg0Sub0)
3835                                .add(SrcReg1Sub0)
3836                                .addImm(0); // clamp bit
3837 
3838     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3839     MachineInstr *HiHalf =
3840         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3841             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3842             .add(SrcReg0Sub1)
3843             .add(SrcReg1Sub1)
3844             .addReg(CarryReg, RegState::Kill)
3845             .addImm(0); // clamp bit
3846 
3847     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3848         .addReg(DestSub0)
3849         .addImm(AMDGPU::sub0)
3850         .addReg(DestSub1)
3851         .addImm(AMDGPU::sub1);
3852     TII->legalizeOperands(*LoHalf);
3853     TII->legalizeOperands(*HiHalf);
3854     MI.eraseFromParent();
3855     return BB;
3856   }
3857   case AMDGPU::S_ADD_CO_PSEUDO:
3858   case AMDGPU::S_SUB_CO_PSEUDO: {
3859     // This pseudo has a chance to be selected
3860     // only from uniform add/subcarry node. All the VGPR operands
3861     // therefore assumed to be splat vectors.
3862     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3863     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3864     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3865     MachineBasicBlock::iterator MII = MI;
3866     const DebugLoc &DL = MI.getDebugLoc();
3867     MachineOperand &Dest = MI.getOperand(0);
3868     MachineOperand &Src0 = MI.getOperand(2);
3869     MachineOperand &Src1 = MI.getOperand(3);
3870     MachineOperand &Src2 = MI.getOperand(4);
3871     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3872                        ? AMDGPU::S_ADDC_U32
3873                        : AMDGPU::S_SUBB_U32;
3874     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3875       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3876       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3877           .addReg(Src0.getReg());
3878       Src0.setReg(RegOp0);
3879     }
3880     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3881       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3882       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3883           .addReg(Src1.getReg());
3884       Src1.setReg(RegOp1);
3885     }
3886     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3887     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3888       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3889           .addReg(Src2.getReg());
3890       Src2.setReg(RegOp2);
3891     }
3892 
3893     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3894       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3895           .addReg(Src2.getReg())
3896           .addImm(0);
3897     } else {
3898       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3899           .addReg(Src2.getReg())
3900           .addImm(0);
3901     }
3902 
3903     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3904     MI.eraseFromParent();
3905     return BB;
3906   }
3907   case AMDGPU::SI_INIT_M0: {
3908     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3909             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3910         .add(MI.getOperand(0));
3911     MI.eraseFromParent();
3912     return BB;
3913   }
3914   case AMDGPU::SI_INIT_EXEC:
3915     // This should be before all vector instructions.
3916     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3917             AMDGPU::EXEC)
3918         .addImm(MI.getOperand(0).getImm());
3919     MI.eraseFromParent();
3920     return BB;
3921 
3922   case AMDGPU::SI_INIT_EXEC_LO:
3923     // This should be before all vector instructions.
3924     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3925             AMDGPU::EXEC_LO)
3926         .addImm(MI.getOperand(0).getImm());
3927     MI.eraseFromParent();
3928     return BB;
3929 
3930   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3931     // Extract the thread count from an SGPR input and set EXEC accordingly.
3932     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3933     //
3934     // S_BFE_U32 count, input, {shift, 7}
3935     // S_BFM_B64 exec, count, 0
3936     // S_CMP_EQ_U32 count, 64
3937     // S_CMOV_B64 exec, -1
3938     MachineInstr *FirstMI = &*BB->begin();
3939     MachineRegisterInfo &MRI = MF->getRegInfo();
3940     Register InputReg = MI.getOperand(0).getReg();
3941     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3942     bool Found = false;
3943 
3944     // Move the COPY of the input reg to the beginning, so that we can use it.
3945     for (auto I = BB->begin(); I != &MI; I++) {
3946       if (I->getOpcode() != TargetOpcode::COPY ||
3947           I->getOperand(0).getReg() != InputReg)
3948         continue;
3949 
3950       if (I == FirstMI) {
3951         FirstMI = &*++BB->begin();
3952       } else {
3953         I->removeFromParent();
3954         BB->insert(FirstMI, &*I);
3955       }
3956       Found = true;
3957       break;
3958     }
3959     assert(Found);
3960     (void)Found;
3961 
3962     // This should be before all vector instructions.
3963     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3964     bool isWave32 = getSubtarget()->isWave32();
3965     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3966     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3967         .addReg(InputReg)
3968         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3969     BuildMI(*BB, FirstMI, DebugLoc(),
3970             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3971             Exec)
3972         .addReg(CountReg)
3973         .addImm(0);
3974     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3975         .addReg(CountReg, RegState::Kill)
3976         .addImm(getSubtarget()->getWavefrontSize());
3977     BuildMI(*BB, FirstMI, DebugLoc(),
3978             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3979             Exec)
3980         .addImm(-1);
3981     MI.eraseFromParent();
3982     return BB;
3983   }
3984 
3985   case AMDGPU::GET_GROUPSTATICSIZE: {
3986     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3987            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3988     DebugLoc DL = MI.getDebugLoc();
3989     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3990         .add(MI.getOperand(0))
3991         .addImm(MFI->getLDSSize());
3992     MI.eraseFromParent();
3993     return BB;
3994   }
3995   case AMDGPU::SI_INDIRECT_SRC_V1:
3996   case AMDGPU::SI_INDIRECT_SRC_V2:
3997   case AMDGPU::SI_INDIRECT_SRC_V4:
3998   case AMDGPU::SI_INDIRECT_SRC_V8:
3999   case AMDGPU::SI_INDIRECT_SRC_V16:
4000   case AMDGPU::SI_INDIRECT_SRC_V32:
4001     return emitIndirectSrc(MI, *BB, *getSubtarget());
4002   case AMDGPU::SI_INDIRECT_DST_V1:
4003   case AMDGPU::SI_INDIRECT_DST_V2:
4004   case AMDGPU::SI_INDIRECT_DST_V4:
4005   case AMDGPU::SI_INDIRECT_DST_V8:
4006   case AMDGPU::SI_INDIRECT_DST_V16:
4007   case AMDGPU::SI_INDIRECT_DST_V32:
4008     return emitIndirectDst(MI, *BB, *getSubtarget());
4009   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4010   case AMDGPU::SI_KILL_I1_PSEUDO:
4011     return splitKillBlock(MI, BB);
4012   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4013     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4014     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4015     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4016 
4017     Register Dst = MI.getOperand(0).getReg();
4018     Register Src0 = MI.getOperand(1).getReg();
4019     Register Src1 = MI.getOperand(2).getReg();
4020     const DebugLoc &DL = MI.getDebugLoc();
4021     Register SrcCond = MI.getOperand(3).getReg();
4022 
4023     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4024     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4025     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4026     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4027 
4028     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4029       .addReg(SrcCond);
4030     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4031       .addImm(0)
4032       .addReg(Src0, 0, AMDGPU::sub0)
4033       .addImm(0)
4034       .addReg(Src1, 0, AMDGPU::sub0)
4035       .addReg(SrcCondCopy);
4036     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4037       .addImm(0)
4038       .addReg(Src0, 0, AMDGPU::sub1)
4039       .addImm(0)
4040       .addReg(Src1, 0, AMDGPU::sub1)
4041       .addReg(SrcCondCopy);
4042 
4043     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4044       .addReg(DstLo)
4045       .addImm(AMDGPU::sub0)
4046       .addReg(DstHi)
4047       .addImm(AMDGPU::sub1);
4048     MI.eraseFromParent();
4049     return BB;
4050   }
4051   case AMDGPU::SI_BR_UNDEF: {
4052     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4053     const DebugLoc &DL = MI.getDebugLoc();
4054     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4055                            .add(MI.getOperand(0));
4056     Br->getOperand(1).setIsUndef(true); // read undef SCC
4057     MI.eraseFromParent();
4058     return BB;
4059   }
4060   case AMDGPU::ADJCALLSTACKUP:
4061   case AMDGPU::ADJCALLSTACKDOWN: {
4062     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4063     MachineInstrBuilder MIB(*MF, &MI);
4064 
4065     // Add an implicit use of the frame offset reg to prevent the restore copy
4066     // inserted after the call from being reorderd after stack operations in the
4067     // the caller's frame.
4068     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4069         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4070         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4071     return BB;
4072   }
4073   case AMDGPU::SI_CALL_ISEL: {
4074     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4075     const DebugLoc &DL = MI.getDebugLoc();
4076 
4077     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4078 
4079     MachineInstrBuilder MIB;
4080     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4081 
4082     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4083       MIB.add(MI.getOperand(I));
4084 
4085     MIB.cloneMemRefs(MI);
4086     MI.eraseFromParent();
4087     return BB;
4088   }
4089   case AMDGPU::V_ADD_I32_e32:
4090   case AMDGPU::V_SUB_I32_e32:
4091   case AMDGPU::V_SUBREV_I32_e32: {
4092     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4093     const DebugLoc &DL = MI.getDebugLoc();
4094     unsigned Opc = MI.getOpcode();
4095 
4096     bool NeedClampOperand = false;
4097     if (TII->pseudoToMCOpcode(Opc) == -1) {
4098       Opc = AMDGPU::getVOPe64(Opc);
4099       NeedClampOperand = true;
4100     }
4101 
4102     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4103     if (TII->isVOP3(*I)) {
4104       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4105       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4106       I.addReg(TRI->getVCC(), RegState::Define);
4107     }
4108     I.add(MI.getOperand(1))
4109      .add(MI.getOperand(2));
4110     if (NeedClampOperand)
4111       I.addImm(0); // clamp bit for e64 encoding
4112 
4113     TII->legalizeOperands(*I);
4114 
4115     MI.eraseFromParent();
4116     return BB;
4117   }
4118   case AMDGPU::DS_GWS_INIT:
4119   case AMDGPU::DS_GWS_SEMA_V:
4120   case AMDGPU::DS_GWS_SEMA_BR:
4121   case AMDGPU::DS_GWS_SEMA_P:
4122   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4123   case AMDGPU::DS_GWS_BARRIER:
4124     // A s_waitcnt 0 is required to be the instruction immediately following.
4125     if (getSubtarget()->hasGWSAutoReplay()) {
4126       bundleInstWithWaitcnt(MI);
4127       return BB;
4128     }
4129 
4130     return emitGWSMemViolTestLoop(MI, BB);
4131   case AMDGPU::S_SETREG_B32: {
4132     if (!getSubtarget()->hasDenormModeInst())
4133       return BB;
4134 
4135     // Try to optimize cases that only set the denormal mode or rounding mode.
4136     //
4137     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4138     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4139     // instead.
4140     //
4141     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4142     // allow you to have a no side effect instruction in the output of a
4143     // sideeffecting pattern.
4144 
4145     // TODO: Should also emit a no side effects pseudo if only FP bits are
4146     // touched, even if not all of them or to a variable.
4147     unsigned ID, Offset, Width;
4148     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4149     if (ID != AMDGPU::Hwreg::ID_MODE)
4150       return BB;
4151 
4152     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4153     const unsigned SetMask = WidthMask << Offset;
4154     unsigned SetDenormOp = 0;
4155     unsigned SetRoundOp = 0;
4156 
4157     // The dedicated instructions can only set the whole denorm or round mode at
4158     // once, not a subset of bits in either.
4159     if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4160                                   AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) {
4161       // If this fully sets both the round and denorm mode, emit the two
4162       // dedicated instructions for these.
4163       assert(Offset == 0);
4164       SetRoundOp = AMDGPU::S_ROUND_MODE;
4165       SetDenormOp = AMDGPU::S_DENORM_MODE;
4166     } else if (Width == 4) {
4167       if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) {
4168         SetRoundOp = AMDGPU::S_ROUND_MODE;
4169         assert(Offset == 0);
4170       } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) {
4171         SetDenormOp = AMDGPU::S_DENORM_MODE;
4172         assert(Offset == 4);
4173       }
4174     }
4175 
4176     if (SetRoundOp || SetDenormOp) {
4177       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4178       MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4179       if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4180         unsigned ImmVal = Def->getOperand(1).getImm();
4181         if (SetRoundOp) {
4182           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4183             .addImm(ImmVal & 0xf);
4184 
4185           // If we also have the denorm mode, get just the denorm mode bits.
4186           ImmVal >>= 4;
4187         }
4188 
4189         if (SetDenormOp) {
4190           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4191             .addImm(ImmVal & 0xf);
4192         }
4193 
4194         MI.eraseFromParent();
4195       }
4196     }
4197 
4198     return BB;
4199   }
4200   default:
4201     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4202   }
4203 }
4204 
4205 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4206   return isTypeLegal(VT.getScalarType());
4207 }
4208 
4209 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4210   // This currently forces unfolding various combinations of fsub into fma with
4211   // free fneg'd operands. As long as we have fast FMA (controlled by
4212   // isFMAFasterThanFMulAndFAdd), we should perform these.
4213 
4214   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4215   // most of these combines appear to be cycle neutral but save on instruction
4216   // count / code size.
4217   return true;
4218 }
4219 
4220 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4221                                          EVT VT) const {
4222   if (!VT.isVector()) {
4223     return MVT::i1;
4224   }
4225   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4226 }
4227 
4228 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4229   // TODO: Should i16 be used always if legal? For now it would force VALU
4230   // shifts.
4231   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4232 }
4233 
4234 // Answering this is somewhat tricky and depends on the specific device which
4235 // have different rates for fma or all f64 operations.
4236 //
4237 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4238 // regardless of which device (although the number of cycles differs between
4239 // devices), so it is always profitable for f64.
4240 //
4241 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4242 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4243 // which we can always do even without fused FP ops since it returns the same
4244 // result as the separate operations and since it is always full
4245 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4246 // however does not support denormals, so we do report fma as faster if we have
4247 // a fast fma device and require denormals.
4248 //
4249 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4250                                                   EVT VT) const {
4251   VT = VT.getScalarType();
4252 
4253   switch (VT.getSimpleVT().SimpleTy) {
4254   case MVT::f32: {
4255     // This is as fast on some subtargets. However, we always have full rate f32
4256     // mad available which returns the same result as the separate operations
4257     // which we should prefer over fma. We can't use this if we want to support
4258     // denormals, so only report this in these cases.
4259     if (hasFP32Denormals(MF))
4260       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4261 
4262     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4263     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4264   }
4265   case MVT::f64:
4266     return true;
4267   case MVT::f16:
4268     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4269   default:
4270     break;
4271   }
4272 
4273   return false;
4274 }
4275 
4276 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4277                                    const SDNode *N) const {
4278   // TODO: Check future ftz flag
4279   // v_mad_f32/v_mac_f32 do not support denormals.
4280   EVT VT = N->getValueType(0);
4281   if (VT == MVT::f32)
4282     return !hasFP32Denormals(DAG.getMachineFunction());
4283   if (VT == MVT::f16) {
4284     return Subtarget->hasMadF16() &&
4285            !hasFP64FP16Denormals(DAG.getMachineFunction());
4286   }
4287 
4288   return false;
4289 }
4290 
4291 //===----------------------------------------------------------------------===//
4292 // Custom DAG Lowering Operations
4293 //===----------------------------------------------------------------------===//
4294 
4295 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4296 // wider vector type is legal.
4297 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4298                                              SelectionDAG &DAG) const {
4299   unsigned Opc = Op.getOpcode();
4300   EVT VT = Op.getValueType();
4301   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4302 
4303   SDValue Lo, Hi;
4304   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4305 
4306   SDLoc SL(Op);
4307   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4308                              Op->getFlags());
4309   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4310                              Op->getFlags());
4311 
4312   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4313 }
4314 
4315 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4316 // wider vector type is legal.
4317 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4318                                               SelectionDAG &DAG) const {
4319   unsigned Opc = Op.getOpcode();
4320   EVT VT = Op.getValueType();
4321   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4322 
4323   SDValue Lo0, Hi0;
4324   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4325   SDValue Lo1, Hi1;
4326   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4327 
4328   SDLoc SL(Op);
4329 
4330   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4331                              Op->getFlags());
4332   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4333                              Op->getFlags());
4334 
4335   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4336 }
4337 
4338 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4339                                               SelectionDAG &DAG) const {
4340   unsigned Opc = Op.getOpcode();
4341   EVT VT = Op.getValueType();
4342   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4343 
4344   SDValue Lo0, Hi0;
4345   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4346   SDValue Lo1, Hi1;
4347   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4348   SDValue Lo2, Hi2;
4349   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4350 
4351   SDLoc SL(Op);
4352 
4353   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4354                              Op->getFlags());
4355   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4356                              Op->getFlags());
4357 
4358   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4359 }
4360 
4361 
4362 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4363   switch (Op.getOpcode()) {
4364   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4365   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4366   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4367   case ISD::LOAD: {
4368     SDValue Result = LowerLOAD(Op, DAG);
4369     assert((!Result.getNode() ||
4370             Result.getNode()->getNumValues() == 2) &&
4371            "Load should return a value and a chain");
4372     return Result;
4373   }
4374 
4375   case ISD::FSIN:
4376   case ISD::FCOS:
4377     return LowerTrig(Op, DAG);
4378   case ISD::SELECT: return LowerSELECT(Op, DAG);
4379   case ISD::FDIV: return LowerFDIV(Op, DAG);
4380   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4381   case ISD::STORE: return LowerSTORE(Op, DAG);
4382   case ISD::GlobalAddress: {
4383     MachineFunction &MF = DAG.getMachineFunction();
4384     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4385     return LowerGlobalAddress(MFI, Op, DAG);
4386   }
4387   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4388   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4389   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4390   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4391   case ISD::INSERT_SUBVECTOR:
4392     return lowerINSERT_SUBVECTOR(Op, DAG);
4393   case ISD::INSERT_VECTOR_ELT:
4394     return lowerINSERT_VECTOR_ELT(Op, DAG);
4395   case ISD::EXTRACT_VECTOR_ELT:
4396     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4397   case ISD::VECTOR_SHUFFLE:
4398     return lowerVECTOR_SHUFFLE(Op, DAG);
4399   case ISD::BUILD_VECTOR:
4400     return lowerBUILD_VECTOR(Op, DAG);
4401   case ISD::FP_ROUND:
4402     return lowerFP_ROUND(Op, DAG);
4403   case ISD::TRAP:
4404     return lowerTRAP(Op, DAG);
4405   case ISD::DEBUGTRAP:
4406     return lowerDEBUGTRAP(Op, DAG);
4407   case ISD::FABS:
4408   case ISD::FNEG:
4409   case ISD::FCANONICALIZE:
4410   case ISD::BSWAP:
4411     return splitUnaryVectorOp(Op, DAG);
4412   case ISD::FMINNUM:
4413   case ISD::FMAXNUM:
4414     return lowerFMINNUM_FMAXNUM(Op, DAG);
4415   case ISD::FMA:
4416     return splitTernaryVectorOp(Op, DAG);
4417   case ISD::SHL:
4418   case ISD::SRA:
4419   case ISD::SRL:
4420   case ISD::ADD:
4421   case ISD::SUB:
4422   case ISD::MUL:
4423   case ISD::SMIN:
4424   case ISD::SMAX:
4425   case ISD::UMIN:
4426   case ISD::UMAX:
4427   case ISD::FADD:
4428   case ISD::FMUL:
4429   case ISD::FMINNUM_IEEE:
4430   case ISD::FMAXNUM_IEEE:
4431     return splitBinaryVectorOp(Op, DAG);
4432   case ISD::DYNAMIC_STACKALLOC:
4433     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4434   }
4435   return SDValue();
4436 }
4437 
4438 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4439                                        const SDLoc &DL,
4440                                        SelectionDAG &DAG, bool Unpacked) {
4441   if (!LoadVT.isVector())
4442     return Result;
4443 
4444   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4445     // Truncate to v2i16/v4i16.
4446     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4447 
4448     // Workaround legalizer not scalarizing truncate after vector op
4449     // legalization byt not creating intermediate vector trunc.
4450     SmallVector<SDValue, 4> Elts;
4451     DAG.ExtractVectorElements(Result, Elts);
4452     for (SDValue &Elt : Elts)
4453       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4454 
4455     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4456 
4457     // Bitcast to original type (v2f16/v4f16).
4458     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4459   }
4460 
4461   // Cast back to the original packed type.
4462   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4463 }
4464 
4465 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4466                                               MemSDNode *M,
4467                                               SelectionDAG &DAG,
4468                                               ArrayRef<SDValue> Ops,
4469                                               bool IsIntrinsic) const {
4470   SDLoc DL(M);
4471 
4472   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4473   EVT LoadVT = M->getValueType(0);
4474 
4475   EVT EquivLoadVT = LoadVT;
4476   if (Unpacked && LoadVT.isVector()) {
4477     EquivLoadVT = LoadVT.isVector() ?
4478       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4479                        LoadVT.getVectorNumElements()) : LoadVT;
4480   }
4481 
4482   // Change from v4f16/v2f16 to EquivLoadVT.
4483   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4484 
4485   SDValue Load
4486     = DAG.getMemIntrinsicNode(
4487       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4488       VTList, Ops, M->getMemoryVT(),
4489       M->getMemOperand());
4490   if (!Unpacked) // Just adjusted the opcode.
4491     return Load;
4492 
4493   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4494 
4495   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4496 }
4497 
4498 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4499                                              SelectionDAG &DAG,
4500                                              ArrayRef<SDValue> Ops) const {
4501   SDLoc DL(M);
4502   EVT LoadVT = M->getValueType(0);
4503   EVT EltType = LoadVT.getScalarType();
4504   EVT IntVT = LoadVT.changeTypeToInteger();
4505 
4506   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4507 
4508   unsigned Opc =
4509       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4510 
4511   if (IsD16) {
4512     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4513   }
4514 
4515   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4516   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4517     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4518 
4519   if (isTypeLegal(LoadVT)) {
4520     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4521                                M->getMemOperand(), DAG);
4522   }
4523 
4524   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4525   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4526   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4527                                         M->getMemOperand(), DAG);
4528   return DAG.getMergeValues(
4529       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4530       DL);
4531 }
4532 
4533 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4534                                   SDNode *N, SelectionDAG &DAG) {
4535   EVT VT = N->getValueType(0);
4536   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4537   int CondCode = CD->getSExtValue();
4538   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4539       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4540     return DAG.getUNDEF(VT);
4541 
4542   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4543 
4544   SDValue LHS = N->getOperand(1);
4545   SDValue RHS = N->getOperand(2);
4546 
4547   SDLoc DL(N);
4548 
4549   EVT CmpVT = LHS.getValueType();
4550   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4551     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4552       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4553     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4554     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4555   }
4556 
4557   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4558 
4559   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4560   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4561 
4562   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4563                               DAG.getCondCode(CCOpcode));
4564   if (VT.bitsEq(CCVT))
4565     return SetCC;
4566   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4567 }
4568 
4569 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4570                                   SDNode *N, SelectionDAG &DAG) {
4571   EVT VT = N->getValueType(0);
4572   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4573 
4574   int CondCode = CD->getSExtValue();
4575   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4576       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4577     return DAG.getUNDEF(VT);
4578   }
4579 
4580   SDValue Src0 = N->getOperand(1);
4581   SDValue Src1 = N->getOperand(2);
4582   EVT CmpVT = Src0.getValueType();
4583   SDLoc SL(N);
4584 
4585   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4586     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4587     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4588   }
4589 
4590   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4591   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4592   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4593   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4594   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4595                               Src1, DAG.getCondCode(CCOpcode));
4596   if (VT.bitsEq(CCVT))
4597     return SetCC;
4598   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4599 }
4600 
4601 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4602                                     SelectionDAG &DAG) {
4603   EVT VT = N->getValueType(0);
4604   SDValue Src = N->getOperand(1);
4605   SDLoc SL(N);
4606 
4607   if (Src.getOpcode() == ISD::SETCC) {
4608     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4609     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4610                        Src.getOperand(1), Src.getOperand(2));
4611   }
4612   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4613     // (ballot 0) -> 0
4614     if (Arg->isNullValue())
4615       return DAG.getConstant(0, SL, VT);
4616 
4617     // (ballot 1) -> EXEC/EXEC_LO
4618     if (Arg->isOne()) {
4619       Register Exec;
4620       if (VT.getScalarSizeInBits() == 32)
4621         Exec = AMDGPU::EXEC_LO;
4622       else if (VT.getScalarSizeInBits() == 64)
4623         Exec = AMDGPU::EXEC;
4624       else
4625         return SDValue();
4626 
4627       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4628     }
4629   }
4630 
4631   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4632   // ISD::SETNE)
4633   return DAG.getNode(
4634       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4635       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4636 }
4637 
4638 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4639                                           SmallVectorImpl<SDValue> &Results,
4640                                           SelectionDAG &DAG) const {
4641   switch (N->getOpcode()) {
4642   case ISD::INSERT_VECTOR_ELT: {
4643     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4644       Results.push_back(Res);
4645     return;
4646   }
4647   case ISD::EXTRACT_VECTOR_ELT: {
4648     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4649       Results.push_back(Res);
4650     return;
4651   }
4652   case ISD::INTRINSIC_WO_CHAIN: {
4653     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4654     switch (IID) {
4655     case Intrinsic::amdgcn_cvt_pkrtz: {
4656       SDValue Src0 = N->getOperand(1);
4657       SDValue Src1 = N->getOperand(2);
4658       SDLoc SL(N);
4659       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4660                                 Src0, Src1);
4661       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4662       return;
4663     }
4664     case Intrinsic::amdgcn_cvt_pknorm_i16:
4665     case Intrinsic::amdgcn_cvt_pknorm_u16:
4666     case Intrinsic::amdgcn_cvt_pk_i16:
4667     case Intrinsic::amdgcn_cvt_pk_u16: {
4668       SDValue Src0 = N->getOperand(1);
4669       SDValue Src1 = N->getOperand(2);
4670       SDLoc SL(N);
4671       unsigned Opcode;
4672 
4673       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4674         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4675       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4676         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4677       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4678         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4679       else
4680         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4681 
4682       EVT VT = N->getValueType(0);
4683       if (isTypeLegal(VT))
4684         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4685       else {
4686         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4687         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4688       }
4689       return;
4690     }
4691     }
4692     break;
4693   }
4694   case ISD::INTRINSIC_W_CHAIN: {
4695     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4696       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4697         // FIXME: Hacky
4698         Results.push_back(Res.getOperand(0));
4699         Results.push_back(Res.getOperand(1));
4700       } else {
4701         Results.push_back(Res);
4702         Results.push_back(Res.getValue(1));
4703       }
4704       return;
4705     }
4706 
4707     break;
4708   }
4709   case ISD::SELECT: {
4710     SDLoc SL(N);
4711     EVT VT = N->getValueType(0);
4712     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4713     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4714     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4715 
4716     EVT SelectVT = NewVT;
4717     if (NewVT.bitsLT(MVT::i32)) {
4718       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4719       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4720       SelectVT = MVT::i32;
4721     }
4722 
4723     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4724                                     N->getOperand(0), LHS, RHS);
4725 
4726     if (NewVT != SelectVT)
4727       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4728     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4729     return;
4730   }
4731   case ISD::FNEG: {
4732     if (N->getValueType(0) != MVT::v2f16)
4733       break;
4734 
4735     SDLoc SL(N);
4736     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4737 
4738     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4739                              BC,
4740                              DAG.getConstant(0x80008000, SL, MVT::i32));
4741     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4742     return;
4743   }
4744   case ISD::FABS: {
4745     if (N->getValueType(0) != MVT::v2f16)
4746       break;
4747 
4748     SDLoc SL(N);
4749     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4750 
4751     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4752                              BC,
4753                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4754     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4755     return;
4756   }
4757   default:
4758     break;
4759   }
4760 }
4761 
4762 /// Helper function for LowerBRCOND
4763 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4764 
4765   SDNode *Parent = Value.getNode();
4766   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4767        I != E; ++I) {
4768 
4769     if (I.getUse().get() != Value)
4770       continue;
4771 
4772     if (I->getOpcode() == Opcode)
4773       return *I;
4774   }
4775   return nullptr;
4776 }
4777 
4778 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4779   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4780     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4781     case Intrinsic::amdgcn_if:
4782       return AMDGPUISD::IF;
4783     case Intrinsic::amdgcn_else:
4784       return AMDGPUISD::ELSE;
4785     case Intrinsic::amdgcn_loop:
4786       return AMDGPUISD::LOOP;
4787     case Intrinsic::amdgcn_end_cf:
4788       llvm_unreachable("should not occur");
4789     default:
4790       return 0;
4791     }
4792   }
4793 
4794   // break, if_break, else_break are all only used as inputs to loop, not
4795   // directly as branch conditions.
4796   return 0;
4797 }
4798 
4799 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4800   const Triple &TT = getTargetMachine().getTargetTriple();
4801   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4802           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4803          AMDGPU::shouldEmitConstantsToTextSection(TT);
4804 }
4805 
4806 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4807   // FIXME: Either avoid relying on address space here or change the default
4808   // address space for functions to avoid the explicit check.
4809   return (GV->getValueType()->isFunctionTy() ||
4810           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4811          !shouldEmitFixup(GV) &&
4812          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4813 }
4814 
4815 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4816   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4817 }
4818 
4819 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4820   if (!GV->hasExternalLinkage())
4821     return true;
4822 
4823   const auto OS = getTargetMachine().getTargetTriple().getOS();
4824   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4825 }
4826 
4827 /// This transforms the control flow intrinsics to get the branch destination as
4828 /// last parameter, also switches branch target with BR if the need arise
4829 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4830                                       SelectionDAG &DAG) const {
4831   SDLoc DL(BRCOND);
4832 
4833   SDNode *Intr = BRCOND.getOperand(1).getNode();
4834   SDValue Target = BRCOND.getOperand(2);
4835   SDNode *BR = nullptr;
4836   SDNode *SetCC = nullptr;
4837 
4838   if (Intr->getOpcode() == ISD::SETCC) {
4839     // As long as we negate the condition everything is fine
4840     SetCC = Intr;
4841     Intr = SetCC->getOperand(0).getNode();
4842 
4843   } else {
4844     // Get the target from BR if we don't negate the condition
4845     BR = findUser(BRCOND, ISD::BR);
4846     assert(BR && "brcond missing unconditional branch user");
4847     Target = BR->getOperand(1);
4848   }
4849 
4850   unsigned CFNode = isCFIntrinsic(Intr);
4851   if (CFNode == 0) {
4852     // This is a uniform branch so we don't need to legalize.
4853     return BRCOND;
4854   }
4855 
4856   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4857                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4858 
4859   assert(!SetCC ||
4860         (SetCC->getConstantOperandVal(1) == 1 &&
4861          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4862                                                              ISD::SETNE));
4863 
4864   // operands of the new intrinsic call
4865   SmallVector<SDValue, 4> Ops;
4866   if (HaveChain)
4867     Ops.push_back(BRCOND.getOperand(0));
4868 
4869   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4870   Ops.push_back(Target);
4871 
4872   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4873 
4874   // build the new intrinsic call
4875   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4876 
4877   if (!HaveChain) {
4878     SDValue Ops[] =  {
4879       SDValue(Result, 0),
4880       BRCOND.getOperand(0)
4881     };
4882 
4883     Result = DAG.getMergeValues(Ops, DL).getNode();
4884   }
4885 
4886   if (BR) {
4887     // Give the branch instruction our target
4888     SDValue Ops[] = {
4889       BR->getOperand(0),
4890       BRCOND.getOperand(2)
4891     };
4892     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4893     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4894   }
4895 
4896   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4897 
4898   // Copy the intrinsic results to registers
4899   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4900     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4901     if (!CopyToReg)
4902       continue;
4903 
4904     Chain = DAG.getCopyToReg(
4905       Chain, DL,
4906       CopyToReg->getOperand(1),
4907       SDValue(Result, i - 1),
4908       SDValue());
4909 
4910     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4911   }
4912 
4913   // Remove the old intrinsic from the chain
4914   DAG.ReplaceAllUsesOfValueWith(
4915     SDValue(Intr, Intr->getNumValues() - 1),
4916     Intr->getOperand(0));
4917 
4918   return Chain;
4919 }
4920 
4921 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4922                                           SelectionDAG &DAG) const {
4923   MVT VT = Op.getSimpleValueType();
4924   SDLoc DL(Op);
4925   // Checking the depth
4926   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4927     return DAG.getConstant(0, DL, VT);
4928 
4929   MachineFunction &MF = DAG.getMachineFunction();
4930   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4931   // Check for kernel and shader functions
4932   if (Info->isEntryFunction())
4933     return DAG.getConstant(0, DL, VT);
4934 
4935   MachineFrameInfo &MFI = MF.getFrameInfo();
4936   // There is a call to @llvm.returnaddress in this function
4937   MFI.setReturnAddressIsTaken(true);
4938 
4939   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4940   // Get the return address reg and mark it as an implicit live-in
4941   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4942 
4943   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4944 }
4945 
4946 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4947                                             SDValue Op,
4948                                             const SDLoc &DL,
4949                                             EVT VT) const {
4950   return Op.getValueType().bitsLE(VT) ?
4951       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4952     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4953                 DAG.getTargetConstant(0, DL, MVT::i32));
4954 }
4955 
4956 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4957   assert(Op.getValueType() == MVT::f16 &&
4958          "Do not know how to custom lower FP_ROUND for non-f16 type");
4959 
4960   SDValue Src = Op.getOperand(0);
4961   EVT SrcVT = Src.getValueType();
4962   if (SrcVT != MVT::f64)
4963     return Op;
4964 
4965   SDLoc DL(Op);
4966 
4967   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4968   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4969   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4970 }
4971 
4972 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4973                                                SelectionDAG &DAG) const {
4974   EVT VT = Op.getValueType();
4975   const MachineFunction &MF = DAG.getMachineFunction();
4976   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4977   bool IsIEEEMode = Info->getMode().IEEE;
4978 
4979   // FIXME: Assert during selection that this is only selected for
4980   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4981   // mode functions, but this happens to be OK since it's only done in cases
4982   // where there is known no sNaN.
4983   if (IsIEEEMode)
4984     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4985 
4986   if (VT == MVT::v4f16)
4987     return splitBinaryVectorOp(Op, DAG);
4988   return Op;
4989 }
4990 
4991 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4992   SDLoc SL(Op);
4993   SDValue Chain = Op.getOperand(0);
4994 
4995   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4996       !Subtarget->isTrapHandlerEnabled())
4997     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4998 
4999   MachineFunction &MF = DAG.getMachineFunction();
5000   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5001   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
5002   assert(UserSGPR != AMDGPU::NoRegister);
5003   SDValue QueuePtr = CreateLiveInRegister(
5004     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5005   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5006   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5007                                    QueuePtr, SDValue());
5008   SDValue Ops[] = {
5009     ToReg,
5010     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5011     SGPR01,
5012     ToReg.getValue(1)
5013   };
5014   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5015 }
5016 
5017 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5018   SDLoc SL(Op);
5019   SDValue Chain = Op.getOperand(0);
5020   MachineFunction &MF = DAG.getMachineFunction();
5021 
5022   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5023       !Subtarget->isTrapHandlerEnabled()) {
5024     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5025                                      "debugtrap handler not supported",
5026                                      Op.getDebugLoc(),
5027                                      DS_Warning);
5028     LLVMContext &Ctx = MF.getFunction().getContext();
5029     Ctx.diagnose(NoTrap);
5030     return Chain;
5031   }
5032 
5033   SDValue Ops[] = {
5034     Chain,
5035     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5036   };
5037   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5038 }
5039 
5040 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5041                                              SelectionDAG &DAG) const {
5042   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5043   if (Subtarget->hasApertureRegs()) {
5044     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5045         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5046         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5047     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5048         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5049         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5050     unsigned Encoding =
5051         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5052         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5053         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5054 
5055     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5056     SDValue ApertureReg = SDValue(
5057         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5058     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5059     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5060   }
5061 
5062   MachineFunction &MF = DAG.getMachineFunction();
5063   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5064   Register UserSGPR = Info->getQueuePtrUserSGPR();
5065   assert(UserSGPR != AMDGPU::NoRegister);
5066 
5067   SDValue QueuePtr = CreateLiveInRegister(
5068     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5069 
5070   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5071   // private_segment_aperture_base_hi.
5072   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5073 
5074   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
5075 
5076   // TODO: Use custom target PseudoSourceValue.
5077   // TODO: We should use the value from the IR intrinsic call, but it might not
5078   // be available and how do we get it?
5079   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5080   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5081                      MinAlign(64, StructOffset),
5082                      MachineMemOperand::MODereferenceable |
5083                          MachineMemOperand::MOInvariant);
5084 }
5085 
5086 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5087                                              SelectionDAG &DAG) const {
5088   SDLoc SL(Op);
5089   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5090 
5091   SDValue Src = ASC->getOperand(0);
5092   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5093 
5094   const AMDGPUTargetMachine &TM =
5095     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5096 
5097   // flat -> local/private
5098   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5099     unsigned DestAS = ASC->getDestAddressSpace();
5100 
5101     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5102         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5103       unsigned NullVal = TM.getNullPointerValue(DestAS);
5104       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5105       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5106       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5107 
5108       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5109                          NonNull, Ptr, SegmentNullPtr);
5110     }
5111   }
5112 
5113   // local/private -> flat
5114   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5115     unsigned SrcAS = ASC->getSrcAddressSpace();
5116 
5117     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5118         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5119       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5120       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5121 
5122       SDValue NonNull
5123         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5124 
5125       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5126       SDValue CvtPtr
5127         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5128 
5129       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5130                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5131                          FlatNullPtr);
5132     }
5133   }
5134 
5135   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5136       Src.getValueType() == MVT::i64)
5137     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5138 
5139   // global <-> flat are no-ops and never emitted.
5140 
5141   const MachineFunction &MF = DAG.getMachineFunction();
5142   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5143     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5144   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5145 
5146   return DAG.getUNDEF(ASC->getValueType(0));
5147 }
5148 
5149 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5150 // the small vector and inserting them into the big vector. That is better than
5151 // the default expansion of doing it via a stack slot. Even though the use of
5152 // the stack slot would be optimized away afterwards, the stack slot itself
5153 // remains.
5154 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5155                                                 SelectionDAG &DAG) const {
5156   SDValue Vec = Op.getOperand(0);
5157   SDValue Ins = Op.getOperand(1);
5158   SDValue Idx = Op.getOperand(2);
5159   EVT VecVT = Vec.getValueType();
5160   EVT InsVT = Ins.getValueType();
5161   EVT EltVT = VecVT.getVectorElementType();
5162   unsigned InsNumElts = InsVT.getVectorNumElements();
5163   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5164   SDLoc SL(Op);
5165 
5166   for (unsigned I = 0; I != InsNumElts; ++I) {
5167     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5168                               DAG.getConstant(I, SL, MVT::i32));
5169     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5170                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5171   }
5172   return Vec;
5173 }
5174 
5175 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5176                                                  SelectionDAG &DAG) const {
5177   SDValue Vec = Op.getOperand(0);
5178   SDValue InsVal = Op.getOperand(1);
5179   SDValue Idx = Op.getOperand(2);
5180   EVT VecVT = Vec.getValueType();
5181   EVT EltVT = VecVT.getVectorElementType();
5182   unsigned VecSize = VecVT.getSizeInBits();
5183   unsigned EltSize = EltVT.getSizeInBits();
5184 
5185 
5186   assert(VecSize <= 64);
5187 
5188   unsigned NumElts = VecVT.getVectorNumElements();
5189   SDLoc SL(Op);
5190   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5191 
5192   if (NumElts == 4 && EltSize == 16 && KIdx) {
5193     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5194 
5195     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5196                                  DAG.getConstant(0, SL, MVT::i32));
5197     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5198                                  DAG.getConstant(1, SL, MVT::i32));
5199 
5200     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5201     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5202 
5203     unsigned Idx = KIdx->getZExtValue();
5204     bool InsertLo = Idx < 2;
5205     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5206       InsertLo ? LoVec : HiVec,
5207       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5208       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5209 
5210     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5211 
5212     SDValue Concat = InsertLo ?
5213       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5214       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5215 
5216     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5217   }
5218 
5219   if (isa<ConstantSDNode>(Idx))
5220     return SDValue();
5221 
5222   MVT IntVT = MVT::getIntegerVT(VecSize);
5223 
5224   // Avoid stack access for dynamic indexing.
5225   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5226 
5227   // Create a congruent vector with the target value in each element so that
5228   // the required element can be masked and ORed into the target vector.
5229   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5230                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5231 
5232   assert(isPowerOf2_32(EltSize));
5233   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5234 
5235   // Convert vector index to bit-index.
5236   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5237 
5238   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5239   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5240                             DAG.getConstant(0xffff, SL, IntVT),
5241                             ScaledIdx);
5242 
5243   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5244   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5245                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5246 
5247   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5248   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5249 }
5250 
5251 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5252                                                   SelectionDAG &DAG) const {
5253   SDLoc SL(Op);
5254 
5255   EVT ResultVT = Op.getValueType();
5256   SDValue Vec = Op.getOperand(0);
5257   SDValue Idx = Op.getOperand(1);
5258   EVT VecVT = Vec.getValueType();
5259   unsigned VecSize = VecVT.getSizeInBits();
5260   EVT EltVT = VecVT.getVectorElementType();
5261   assert(VecSize <= 64);
5262 
5263   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5264 
5265   // Make sure we do any optimizations that will make it easier to fold
5266   // source modifiers before obscuring it with bit operations.
5267 
5268   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5269   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5270     return Combined;
5271 
5272   unsigned EltSize = EltVT.getSizeInBits();
5273   assert(isPowerOf2_32(EltSize));
5274 
5275   MVT IntVT = MVT::getIntegerVT(VecSize);
5276   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5277 
5278   // Convert vector index to bit-index (* EltSize)
5279   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5280 
5281   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5282   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5283 
5284   if (ResultVT == MVT::f16) {
5285     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5286     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5287   }
5288 
5289   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5290 }
5291 
5292 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5293   assert(Elt % 2 == 0);
5294   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5295 }
5296 
5297 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5298                                               SelectionDAG &DAG) const {
5299   SDLoc SL(Op);
5300   EVT ResultVT = Op.getValueType();
5301   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5302 
5303   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5304   EVT EltVT = PackVT.getVectorElementType();
5305   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5306 
5307   // vector_shuffle <0,1,6,7> lhs, rhs
5308   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5309   //
5310   // vector_shuffle <6,7,2,3> lhs, rhs
5311   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5312   //
5313   // vector_shuffle <6,7,0,1> lhs, rhs
5314   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5315 
5316   // Avoid scalarizing when both halves are reading from consecutive elements.
5317   SmallVector<SDValue, 4> Pieces;
5318   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5319     if (elementPairIsContiguous(SVN->getMask(), I)) {
5320       const int Idx = SVN->getMaskElt(I);
5321       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5322       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5323       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5324                                     PackVT, SVN->getOperand(VecIdx),
5325                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5326       Pieces.push_back(SubVec);
5327     } else {
5328       const int Idx0 = SVN->getMaskElt(I);
5329       const int Idx1 = SVN->getMaskElt(I + 1);
5330       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5331       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5332       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5333       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5334 
5335       SDValue Vec0 = SVN->getOperand(VecIdx0);
5336       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5337                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5338 
5339       SDValue Vec1 = SVN->getOperand(VecIdx1);
5340       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5341                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5342       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5343     }
5344   }
5345 
5346   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5347 }
5348 
5349 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5350                                             SelectionDAG &DAG) const {
5351   SDLoc SL(Op);
5352   EVT VT = Op.getValueType();
5353 
5354   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5355     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5356 
5357     // Turn into pair of packed build_vectors.
5358     // TODO: Special case for constants that can be materialized with s_mov_b64.
5359     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5360                                     { Op.getOperand(0), Op.getOperand(1) });
5361     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5362                                     { Op.getOperand(2), Op.getOperand(3) });
5363 
5364     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5365     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5366 
5367     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5368     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5369   }
5370 
5371   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5372   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5373 
5374   SDValue Lo = Op.getOperand(0);
5375   SDValue Hi = Op.getOperand(1);
5376 
5377   // Avoid adding defined bits with the zero_extend.
5378   if (Hi.isUndef()) {
5379     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5380     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5381     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5382   }
5383 
5384   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5385   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5386 
5387   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5388                               DAG.getConstant(16, SL, MVT::i32));
5389   if (Lo.isUndef())
5390     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5391 
5392   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5393   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5394 
5395   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5396   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5397 }
5398 
5399 bool
5400 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5401   // We can fold offsets for anything that doesn't require a GOT relocation.
5402   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5403           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5404           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5405          !shouldEmitGOTReloc(GA->getGlobal());
5406 }
5407 
5408 static SDValue
5409 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5410                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5411                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5412   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5413   // lowered to the following code sequence:
5414   //
5415   // For constant address space:
5416   //   s_getpc_b64 s[0:1]
5417   //   s_add_u32 s0, s0, $symbol
5418   //   s_addc_u32 s1, s1, 0
5419   //
5420   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5421   //   a fixup or relocation is emitted to replace $symbol with a literal
5422   //   constant, which is a pc-relative offset from the encoding of the $symbol
5423   //   operand to the global variable.
5424   //
5425   // For global address space:
5426   //   s_getpc_b64 s[0:1]
5427   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5428   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5429   //
5430   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5431   //   fixups or relocations are emitted to replace $symbol@*@lo and
5432   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5433   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5434   //   operand to the global variable.
5435   //
5436   // What we want here is an offset from the value returned by s_getpc
5437   // (which is the address of the s_add_u32 instruction) to the global
5438   // variable, but since the encoding of $symbol starts 4 bytes after the start
5439   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5440   // small. This requires us to add 4 to the global variable offset in order to
5441   // compute the correct address.
5442   SDValue PtrLo =
5443       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5444   SDValue PtrHi;
5445   if (GAFlags == SIInstrInfo::MO_NONE) {
5446     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5447   } else {
5448     PtrHi =
5449         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5450   }
5451   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5452 }
5453 
5454 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5455                                              SDValue Op,
5456                                              SelectionDAG &DAG) const {
5457   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5458   const GlobalValue *GV = GSD->getGlobal();
5459   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5460        shouldUseLDSConstAddress(GV)) ||
5461       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5462       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5463     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5464 
5465   SDLoc DL(GSD);
5466   EVT PtrVT = Op.getValueType();
5467 
5468   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5469     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5470                                             SIInstrInfo::MO_ABS32_LO);
5471     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5472   }
5473 
5474   if (shouldEmitFixup(GV))
5475     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5476   else if (shouldEmitPCReloc(GV))
5477     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5478                                    SIInstrInfo::MO_REL32);
5479 
5480   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5481                                             SIInstrInfo::MO_GOTPCREL32);
5482 
5483   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5484   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5485   const DataLayout &DataLayout = DAG.getDataLayout();
5486   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5487   MachinePointerInfo PtrInfo
5488     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5489 
5490   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5491                      MachineMemOperand::MODereferenceable |
5492                          MachineMemOperand::MOInvariant);
5493 }
5494 
5495 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5496                                    const SDLoc &DL, SDValue V) const {
5497   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5498   // the destination register.
5499   //
5500   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5501   // so we will end up with redundant moves to m0.
5502   //
5503   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5504 
5505   // A Null SDValue creates a glue result.
5506   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5507                                   V, Chain);
5508   return SDValue(M0, 0);
5509 }
5510 
5511 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5512                                                  SDValue Op,
5513                                                  MVT VT,
5514                                                  unsigned Offset) const {
5515   SDLoc SL(Op);
5516   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5517                                            DAG.getEntryNode(), Offset, 4, false);
5518   // The local size values will have the hi 16-bits as zero.
5519   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5520                      DAG.getValueType(VT));
5521 }
5522 
5523 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5524                                         EVT VT) {
5525   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5526                                       "non-hsa intrinsic with hsa target",
5527                                       DL.getDebugLoc());
5528   DAG.getContext()->diagnose(BadIntrin);
5529   return DAG.getUNDEF(VT);
5530 }
5531 
5532 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5533                                          EVT VT) {
5534   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5535                                       "intrinsic not supported on subtarget",
5536                                       DL.getDebugLoc());
5537   DAG.getContext()->diagnose(BadIntrin);
5538   return DAG.getUNDEF(VT);
5539 }
5540 
5541 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5542                                     ArrayRef<SDValue> Elts) {
5543   assert(!Elts.empty());
5544   MVT Type;
5545   unsigned NumElts;
5546 
5547   if (Elts.size() == 1) {
5548     Type = MVT::f32;
5549     NumElts = 1;
5550   } else if (Elts.size() == 2) {
5551     Type = MVT::v2f32;
5552     NumElts = 2;
5553   } else if (Elts.size() == 3) {
5554     Type = MVT::v3f32;
5555     NumElts = 3;
5556   } else if (Elts.size() <= 4) {
5557     Type = MVT::v4f32;
5558     NumElts = 4;
5559   } else if (Elts.size() <= 8) {
5560     Type = MVT::v8f32;
5561     NumElts = 8;
5562   } else {
5563     assert(Elts.size() <= 16);
5564     Type = MVT::v16f32;
5565     NumElts = 16;
5566   }
5567 
5568   SmallVector<SDValue, 16> VecElts(NumElts);
5569   for (unsigned i = 0; i < Elts.size(); ++i) {
5570     SDValue Elt = Elts[i];
5571     if (Elt.getValueType() != MVT::f32)
5572       Elt = DAG.getBitcast(MVT::f32, Elt);
5573     VecElts[i] = Elt;
5574   }
5575   for (unsigned i = Elts.size(); i < NumElts; ++i)
5576     VecElts[i] = DAG.getUNDEF(MVT::f32);
5577 
5578   if (NumElts == 1)
5579     return VecElts[0];
5580   return DAG.getBuildVector(Type, DL, VecElts);
5581 }
5582 
5583 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5584                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5585   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5586 
5587   uint64_t Value = CachePolicyConst->getZExtValue();
5588   SDLoc DL(CachePolicy);
5589   if (GLC) {
5590     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5591     Value &= ~(uint64_t)0x1;
5592   }
5593   if (SLC) {
5594     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5595     Value &= ~(uint64_t)0x2;
5596   }
5597   if (DLC) {
5598     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5599     Value &= ~(uint64_t)0x4;
5600   }
5601 
5602   return Value == 0;
5603 }
5604 
5605 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5606                               SDValue Src, int ExtraElts) {
5607   EVT SrcVT = Src.getValueType();
5608 
5609   SmallVector<SDValue, 8> Elts;
5610 
5611   if (SrcVT.isVector())
5612     DAG.ExtractVectorElements(Src, Elts);
5613   else
5614     Elts.push_back(Src);
5615 
5616   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5617   while (ExtraElts--)
5618     Elts.push_back(Undef);
5619 
5620   return DAG.getBuildVector(CastVT, DL, Elts);
5621 }
5622 
5623 // Re-construct the required return value for a image load intrinsic.
5624 // This is more complicated due to the optional use TexFailCtrl which means the required
5625 // return type is an aggregate
5626 static SDValue constructRetValue(SelectionDAG &DAG,
5627                                  MachineSDNode *Result,
5628                                  ArrayRef<EVT> ResultTypes,
5629                                  bool IsTexFail, bool Unpacked, bool IsD16,
5630                                  int DMaskPop, int NumVDataDwords,
5631                                  const SDLoc &DL, LLVMContext &Context) {
5632   // Determine the required return type. This is the same regardless of IsTexFail flag
5633   EVT ReqRetVT = ResultTypes[0];
5634   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5635   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5636     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5637 
5638   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5639     DMaskPop : (DMaskPop + 1) / 2;
5640 
5641   MVT DataDwordVT = NumDataDwords == 1 ?
5642     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5643 
5644   MVT MaskPopVT = MaskPopDwords == 1 ?
5645     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5646 
5647   SDValue Data(Result, 0);
5648   SDValue TexFail;
5649 
5650   if (IsTexFail) {
5651     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5652     if (MaskPopVT.isVector()) {
5653       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5654                          SDValue(Result, 0), ZeroIdx);
5655     } else {
5656       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5657                          SDValue(Result, 0), ZeroIdx);
5658     }
5659 
5660     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5661                           SDValue(Result, 0),
5662                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5663   }
5664 
5665   if (DataDwordVT.isVector())
5666     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5667                           NumDataDwords - MaskPopDwords);
5668 
5669   if (IsD16)
5670     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5671 
5672   if (!ReqRetVT.isVector())
5673     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5674 
5675   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5676 
5677   if (TexFail)
5678     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5679 
5680   if (Result->getNumValues() == 1)
5681     return Data;
5682 
5683   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5684 }
5685 
5686 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5687                          SDValue *LWE, bool &IsTexFail) {
5688   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5689 
5690   uint64_t Value = TexFailCtrlConst->getZExtValue();
5691   if (Value) {
5692     IsTexFail = true;
5693   }
5694 
5695   SDLoc DL(TexFailCtrlConst);
5696   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5697   Value &= ~(uint64_t)0x1;
5698   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5699   Value &= ~(uint64_t)0x2;
5700 
5701   return Value == 0;
5702 }
5703 
5704 SDValue SITargetLowering::lowerImage(SDValue Op,
5705                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5706                                      SelectionDAG &DAG) const {
5707   SDLoc DL(Op);
5708   MachineFunction &MF = DAG.getMachineFunction();
5709   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5710   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5711       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5712   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5713   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5714       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5715   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5716       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5717   unsigned IntrOpcode = Intr->BaseOpcode;
5718   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5719 
5720   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5721   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5722   bool IsD16 = false;
5723   bool IsA16 = false;
5724   SDValue VData;
5725   int NumVDataDwords;
5726   bool AdjustRetType = false;
5727 
5728   unsigned AddrIdx; // Index of first address argument
5729   unsigned DMask;
5730   unsigned DMaskLanes = 0;
5731 
5732   if (BaseOpcode->Atomic) {
5733     VData = Op.getOperand(2);
5734 
5735     bool Is64Bit = VData.getValueType() == MVT::i64;
5736     if (BaseOpcode->AtomicX2) {
5737       SDValue VData2 = Op.getOperand(3);
5738       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5739                                  {VData, VData2});
5740       if (Is64Bit)
5741         VData = DAG.getBitcast(MVT::v4i32, VData);
5742 
5743       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5744       DMask = Is64Bit ? 0xf : 0x3;
5745       NumVDataDwords = Is64Bit ? 4 : 2;
5746       AddrIdx = 4;
5747     } else {
5748       DMask = Is64Bit ? 0x3 : 0x1;
5749       NumVDataDwords = Is64Bit ? 2 : 1;
5750       AddrIdx = 3;
5751     }
5752   } else {
5753     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5754     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5755     DMask = DMaskConst->getZExtValue();
5756     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5757 
5758     if (BaseOpcode->Store) {
5759       VData = Op.getOperand(2);
5760 
5761       MVT StoreVT = VData.getSimpleValueType();
5762       if (StoreVT.getScalarType() == MVT::f16) {
5763         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5764           return Op; // D16 is unsupported for this instruction
5765 
5766         IsD16 = true;
5767         VData = handleD16VData(VData, DAG);
5768       }
5769 
5770       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5771     } else {
5772       // Work out the num dwords based on the dmask popcount and underlying type
5773       // and whether packing is supported.
5774       MVT LoadVT = ResultTypes[0].getSimpleVT();
5775       if (LoadVT.getScalarType() == MVT::f16) {
5776         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5777           return Op; // D16 is unsupported for this instruction
5778 
5779         IsD16 = true;
5780       }
5781 
5782       // Confirm that the return type is large enough for the dmask specified
5783       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5784           (!LoadVT.isVector() && DMaskLanes > 1))
5785           return Op;
5786 
5787       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5788         NumVDataDwords = (DMaskLanes + 1) / 2;
5789       else
5790         NumVDataDwords = DMaskLanes;
5791 
5792       AdjustRetType = true;
5793     }
5794 
5795     AddrIdx = DMaskIdx + 1;
5796   }
5797 
5798   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5799   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5800   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5801   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5802                        NumCoords + NumLCM;
5803   unsigned NumMIVAddrs = NumVAddrs;
5804 
5805   SmallVector<SDValue, 4> VAddrs;
5806 
5807   // Optimize _L to _LZ when _L is zero
5808   if (LZMappingInfo) {
5809     if (auto ConstantLod =
5810          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5811       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5812         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5813         NumMIVAddrs--;               // remove 'lod'
5814       }
5815     }
5816   }
5817 
5818   // Optimize _mip away, when 'lod' is zero
5819   if (MIPMappingInfo) {
5820     if (auto ConstantLod =
5821          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5822       if (ConstantLod->isNullValue()) {
5823         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5824         NumMIVAddrs--;               // remove 'lod'
5825       }
5826     }
5827   }
5828 
5829   // Check for 16 bit addresses and pack if true.
5830   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5831   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5832   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5833   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5834     // Illegal to use a16 images
5835     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5836       return Op;
5837 
5838     IsA16 = true;
5839     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5840     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5841       SDValue AddrLo;
5842       // Push back extra arguments.
5843       if (i < DimIdx) {
5844         AddrLo = Op.getOperand(i);
5845       } else {
5846         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5847         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5848         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5849             ((NumGradients / 2) % 2 == 1 &&
5850             (i == DimIdx + (NumGradients / 2) - 1 ||
5851              i == DimIdx + NumGradients - 1))) {
5852           AddrLo = Op.getOperand(i);
5853           if (AddrLo.getValueType() != MVT::i16)
5854             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5855           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5856         } else {
5857           AddrLo = DAG.getBuildVector(VectorVT, DL,
5858                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5859           i++;
5860         }
5861         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5862       }
5863       VAddrs.push_back(AddrLo);
5864     }
5865   } else {
5866     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5867       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5868   }
5869 
5870   // If the register allocator cannot place the address registers contiguously
5871   // without introducing moves, then using the non-sequential address encoding
5872   // is always preferable, since it saves VALU instructions and is usually a
5873   // wash in terms of code size or even better.
5874   //
5875   // However, we currently have no way of hinting to the register allocator that
5876   // MIMG addresses should be placed contiguously when it is possible to do so,
5877   // so force non-NSA for the common 2-address case as a heuristic.
5878   //
5879   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5880   // allocation when possible.
5881   bool UseNSA =
5882       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5883   SDValue VAddr;
5884   if (!UseNSA)
5885     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5886 
5887   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5888   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5889   unsigned CtrlIdx; // Index of texfailctrl argument
5890   SDValue Unorm;
5891   if (!BaseOpcode->Sampler) {
5892     Unorm = True;
5893     CtrlIdx = AddrIdx + NumVAddrs + 1;
5894   } else {
5895     auto UnormConst =
5896         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5897 
5898     Unorm = UnormConst->getZExtValue() ? True : False;
5899     CtrlIdx = AddrIdx + NumVAddrs + 3;
5900   }
5901 
5902   SDValue TFE;
5903   SDValue LWE;
5904   SDValue TexFail = Op.getOperand(CtrlIdx);
5905   bool IsTexFail = false;
5906   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5907     return Op;
5908 
5909   if (IsTexFail) {
5910     if (!DMaskLanes) {
5911       // Expecting to get an error flag since TFC is on - and dmask is 0
5912       // Force dmask to be at least 1 otherwise the instruction will fail
5913       DMask = 0x1;
5914       DMaskLanes = 1;
5915       NumVDataDwords = 1;
5916     }
5917     NumVDataDwords += 1;
5918     AdjustRetType = true;
5919   }
5920 
5921   // Has something earlier tagged that the return type needs adjusting
5922   // This happens if the instruction is a load or has set TexFailCtrl flags
5923   if (AdjustRetType) {
5924     // NumVDataDwords reflects the true number of dwords required in the return type
5925     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5926       // This is a no-op load. This can be eliminated
5927       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5928       if (isa<MemSDNode>(Op))
5929         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5930       return Undef;
5931     }
5932 
5933     EVT NewVT = NumVDataDwords > 1 ?
5934                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5935                 : MVT::i32;
5936 
5937     ResultTypes[0] = NewVT;
5938     if (ResultTypes.size() == 3) {
5939       // Original result was aggregate type used for TexFailCtrl results
5940       // The actual instruction returns as a vector type which has now been
5941       // created. Remove the aggregate result.
5942       ResultTypes.erase(&ResultTypes[1]);
5943     }
5944   }
5945 
5946   SDValue GLC;
5947   SDValue SLC;
5948   SDValue DLC;
5949   if (BaseOpcode->Atomic) {
5950     GLC = True; // TODO no-return optimization
5951     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5952                           IsGFX10 ? &DLC : nullptr))
5953       return Op;
5954   } else {
5955     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5956                           IsGFX10 ? &DLC : nullptr))
5957       return Op;
5958   }
5959 
5960   SmallVector<SDValue, 26> Ops;
5961   if (BaseOpcode->Store || BaseOpcode->Atomic)
5962     Ops.push_back(VData); // vdata
5963   if (UseNSA) {
5964     for (const SDValue &Addr : VAddrs)
5965       Ops.push_back(Addr);
5966   } else {
5967     Ops.push_back(VAddr);
5968   }
5969   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5970   if (BaseOpcode->Sampler)
5971     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5972   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5973   if (IsGFX10)
5974     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5975   Ops.push_back(Unorm);
5976   if (IsGFX10)
5977     Ops.push_back(DLC);
5978   Ops.push_back(GLC);
5979   Ops.push_back(SLC);
5980   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5981                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5982   if (IsGFX10)
5983     Ops.push_back(IsA16 ? True : False);
5984   Ops.push_back(TFE);
5985   Ops.push_back(LWE);
5986   if (!IsGFX10)
5987     Ops.push_back(DimInfo->DA ? True : False);
5988   if (BaseOpcode->HasD16)
5989     Ops.push_back(IsD16 ? True : False);
5990   if (isa<MemSDNode>(Op))
5991     Ops.push_back(Op.getOperand(0)); // chain
5992 
5993   int NumVAddrDwords =
5994       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5995   int Opcode = -1;
5996 
5997   if (IsGFX10) {
5998     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5999                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6000                                           : AMDGPU::MIMGEncGfx10Default,
6001                                    NumVDataDwords, NumVAddrDwords);
6002   } else {
6003     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6004       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6005                                      NumVDataDwords, NumVAddrDwords);
6006     if (Opcode == -1)
6007       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6008                                      NumVDataDwords, NumVAddrDwords);
6009   }
6010   assert(Opcode != -1);
6011 
6012   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6013   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6014     MachineMemOperand *MemRef = MemOp->getMemOperand();
6015     DAG.setNodeMemRefs(NewNode, {MemRef});
6016   }
6017 
6018   if (BaseOpcode->AtomicX2) {
6019     SmallVector<SDValue, 1> Elt;
6020     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6021     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6022   } else if (!BaseOpcode->Store) {
6023     return constructRetValue(DAG, NewNode,
6024                              OrigResultTypes, IsTexFail,
6025                              Subtarget->hasUnpackedD16VMem(), IsD16,
6026                              DMaskLanes, NumVDataDwords, DL,
6027                              *DAG.getContext());
6028   }
6029 
6030   return SDValue(NewNode, 0);
6031 }
6032 
6033 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6034                                        SDValue Offset, SDValue CachePolicy,
6035                                        SelectionDAG &DAG) const {
6036   MachineFunction &MF = DAG.getMachineFunction();
6037 
6038   const DataLayout &DataLayout = DAG.getDataLayout();
6039   Align Alignment =
6040       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6041 
6042   MachineMemOperand *MMO = MF.getMachineMemOperand(
6043       MachinePointerInfo(),
6044       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6045           MachineMemOperand::MOInvariant,
6046       VT.getStoreSize(), Alignment);
6047 
6048   if (!Offset->isDivergent()) {
6049     SDValue Ops[] = {
6050         Rsrc,
6051         Offset, // Offset
6052         CachePolicy
6053     };
6054 
6055     // Widen vec3 load to vec4.
6056     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6057       EVT WidenedVT =
6058           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6059       auto WidenedOp = DAG.getMemIntrinsicNode(
6060           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6061           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6062       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6063                                    DAG.getVectorIdxConstant(0, DL));
6064       return Subvector;
6065     }
6066 
6067     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6068                                    DAG.getVTList(VT), Ops, VT, MMO);
6069   }
6070 
6071   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6072   // assume that the buffer is unswizzled.
6073   SmallVector<SDValue, 4> Loads;
6074   unsigned NumLoads = 1;
6075   MVT LoadVT = VT.getSimpleVT();
6076   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6077   assert((LoadVT.getScalarType() == MVT::i32 ||
6078           LoadVT.getScalarType() == MVT::f32));
6079 
6080   if (NumElts == 8 || NumElts == 16) {
6081     NumLoads = NumElts / 4;
6082     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6083   }
6084 
6085   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6086   SDValue Ops[] = {
6087       DAG.getEntryNode(),                               // Chain
6088       Rsrc,                                             // rsrc
6089       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6090       {},                                               // voffset
6091       {},                                               // soffset
6092       {},                                               // offset
6093       CachePolicy,                                      // cachepolicy
6094       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6095   };
6096 
6097   // Use the alignment to ensure that the required offsets will fit into the
6098   // immediate offsets.
6099   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
6100 
6101   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6102   for (unsigned i = 0; i < NumLoads; ++i) {
6103     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6104     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6105                                         LoadVT, MMO, DAG));
6106   }
6107 
6108   if (NumElts == 8 || NumElts == 16)
6109     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6110 
6111   return Loads[0];
6112 }
6113 
6114 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6115                                                   SelectionDAG &DAG) const {
6116   MachineFunction &MF = DAG.getMachineFunction();
6117   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6118 
6119   EVT VT = Op.getValueType();
6120   SDLoc DL(Op);
6121   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6122 
6123   // TODO: Should this propagate fast-math-flags?
6124 
6125   switch (IntrinsicID) {
6126   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6127     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6128       return emitNonHSAIntrinsicError(DAG, DL, VT);
6129     return getPreloadedValue(DAG, *MFI, VT,
6130                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6131   }
6132   case Intrinsic::amdgcn_dispatch_ptr:
6133   case Intrinsic::amdgcn_queue_ptr: {
6134     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6135       DiagnosticInfoUnsupported BadIntrin(
6136           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6137           DL.getDebugLoc());
6138       DAG.getContext()->diagnose(BadIntrin);
6139       return DAG.getUNDEF(VT);
6140     }
6141 
6142     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6143       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6144     return getPreloadedValue(DAG, *MFI, VT, RegID);
6145   }
6146   case Intrinsic::amdgcn_implicitarg_ptr: {
6147     if (MFI->isEntryFunction())
6148       return getImplicitArgPtr(DAG, DL);
6149     return getPreloadedValue(DAG, *MFI, VT,
6150                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6151   }
6152   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6153     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6154       // This only makes sense to call in a kernel, so just lower to null.
6155       return DAG.getConstant(0, DL, VT);
6156     }
6157 
6158     return getPreloadedValue(DAG, *MFI, VT,
6159                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6160   }
6161   case Intrinsic::amdgcn_dispatch_id: {
6162     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6163   }
6164   case Intrinsic::amdgcn_rcp:
6165     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6166   case Intrinsic::amdgcn_rsq:
6167     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6168   case Intrinsic::amdgcn_rsq_legacy:
6169     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6170       return emitRemovedIntrinsicError(DAG, DL, VT);
6171     return SDValue();
6172   case Intrinsic::amdgcn_rcp_legacy:
6173     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6174       return emitRemovedIntrinsicError(DAG, DL, VT);
6175     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6176   case Intrinsic::amdgcn_rsq_clamp: {
6177     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6178       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6179 
6180     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6181     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6182     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6183 
6184     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6185     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6186                               DAG.getConstantFP(Max, DL, VT));
6187     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6188                        DAG.getConstantFP(Min, DL, VT));
6189   }
6190   case Intrinsic::r600_read_ngroups_x:
6191     if (Subtarget->isAmdHsaOS())
6192       return emitNonHSAIntrinsicError(DAG, DL, VT);
6193 
6194     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6195                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6196   case Intrinsic::r600_read_ngroups_y:
6197     if (Subtarget->isAmdHsaOS())
6198       return emitNonHSAIntrinsicError(DAG, DL, VT);
6199 
6200     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6201                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6202   case Intrinsic::r600_read_ngroups_z:
6203     if (Subtarget->isAmdHsaOS())
6204       return emitNonHSAIntrinsicError(DAG, DL, VT);
6205 
6206     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6207                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6208   case Intrinsic::r600_read_global_size_x:
6209     if (Subtarget->isAmdHsaOS())
6210       return emitNonHSAIntrinsicError(DAG, DL, VT);
6211 
6212     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6213                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6214   case Intrinsic::r600_read_global_size_y:
6215     if (Subtarget->isAmdHsaOS())
6216       return emitNonHSAIntrinsicError(DAG, DL, VT);
6217 
6218     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6219                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6220   case Intrinsic::r600_read_global_size_z:
6221     if (Subtarget->isAmdHsaOS())
6222       return emitNonHSAIntrinsicError(DAG, DL, VT);
6223 
6224     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6225                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6226   case Intrinsic::r600_read_local_size_x:
6227     if (Subtarget->isAmdHsaOS())
6228       return emitNonHSAIntrinsicError(DAG, DL, VT);
6229 
6230     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6231                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6232   case Intrinsic::r600_read_local_size_y:
6233     if (Subtarget->isAmdHsaOS())
6234       return emitNonHSAIntrinsicError(DAG, DL, VT);
6235 
6236     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6237                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6238   case Intrinsic::r600_read_local_size_z:
6239     if (Subtarget->isAmdHsaOS())
6240       return emitNonHSAIntrinsicError(DAG, DL, VT);
6241 
6242     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6243                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6244   case Intrinsic::amdgcn_workgroup_id_x:
6245     return getPreloadedValue(DAG, *MFI, VT,
6246                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6247   case Intrinsic::amdgcn_workgroup_id_y:
6248     return getPreloadedValue(DAG, *MFI, VT,
6249                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6250   case Intrinsic::amdgcn_workgroup_id_z:
6251     return getPreloadedValue(DAG, *MFI, VT,
6252                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6253   case Intrinsic::amdgcn_workitem_id_x:
6254     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6255                           SDLoc(DAG.getEntryNode()),
6256                           MFI->getArgInfo().WorkItemIDX);
6257   case Intrinsic::amdgcn_workitem_id_y:
6258     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6259                           SDLoc(DAG.getEntryNode()),
6260                           MFI->getArgInfo().WorkItemIDY);
6261   case Intrinsic::amdgcn_workitem_id_z:
6262     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6263                           SDLoc(DAG.getEntryNode()),
6264                           MFI->getArgInfo().WorkItemIDZ);
6265   case Intrinsic::amdgcn_wavefrontsize:
6266     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6267                            SDLoc(Op), MVT::i32);
6268   case Intrinsic::amdgcn_s_buffer_load: {
6269     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6270     SDValue GLC;
6271     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6272     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6273                           IsGFX10 ? &DLC : nullptr))
6274       return Op;
6275     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6276                         DAG);
6277   }
6278   case Intrinsic::amdgcn_fdiv_fast:
6279     return lowerFDIV_FAST(Op, DAG);
6280   case Intrinsic::amdgcn_sin:
6281     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6282 
6283   case Intrinsic::amdgcn_cos:
6284     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6285 
6286   case Intrinsic::amdgcn_mul_u24:
6287     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6288   case Intrinsic::amdgcn_mul_i24:
6289     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6290 
6291   case Intrinsic::amdgcn_log_clamp: {
6292     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6293       return SDValue();
6294 
6295     DiagnosticInfoUnsupported BadIntrin(
6296       MF.getFunction(), "intrinsic not supported on subtarget",
6297       DL.getDebugLoc());
6298       DAG.getContext()->diagnose(BadIntrin);
6299       return DAG.getUNDEF(VT);
6300   }
6301   case Intrinsic::amdgcn_ldexp:
6302     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6303                        Op.getOperand(1), Op.getOperand(2));
6304 
6305   case Intrinsic::amdgcn_fract:
6306     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6307 
6308   case Intrinsic::amdgcn_class:
6309     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6310                        Op.getOperand(1), Op.getOperand(2));
6311   case Intrinsic::amdgcn_div_fmas:
6312     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6313                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6314                        Op.getOperand(4));
6315 
6316   case Intrinsic::amdgcn_div_fixup:
6317     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6318                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6319 
6320   case Intrinsic::amdgcn_trig_preop:
6321     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
6322                        Op.getOperand(1), Op.getOperand(2));
6323   case Intrinsic::amdgcn_div_scale: {
6324     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6325 
6326     // Translate to the operands expected by the machine instruction. The
6327     // first parameter must be the same as the first instruction.
6328     SDValue Numerator = Op.getOperand(1);
6329     SDValue Denominator = Op.getOperand(2);
6330 
6331     // Note this order is opposite of the machine instruction's operations,
6332     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6333     // intrinsic has the numerator as the first operand to match a normal
6334     // division operation.
6335 
6336     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6337 
6338     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6339                        Denominator, Numerator);
6340   }
6341   case Intrinsic::amdgcn_icmp: {
6342     // There is a Pat that handles this variant, so return it as-is.
6343     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6344         Op.getConstantOperandVal(2) == 0 &&
6345         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6346       return Op;
6347     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6348   }
6349   case Intrinsic::amdgcn_fcmp: {
6350     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6351   }
6352   case Intrinsic::amdgcn_ballot:
6353     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6354   case Intrinsic::amdgcn_fmed3:
6355     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6356                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6357   case Intrinsic::amdgcn_fdot2:
6358     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6359                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6360                        Op.getOperand(4));
6361   case Intrinsic::amdgcn_fmul_legacy:
6362     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6363                        Op.getOperand(1), Op.getOperand(2));
6364   case Intrinsic::amdgcn_sffbh:
6365     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6366   case Intrinsic::amdgcn_sbfe:
6367     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6368                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6369   case Intrinsic::amdgcn_ubfe:
6370     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6371                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6372   case Intrinsic::amdgcn_cvt_pkrtz:
6373   case Intrinsic::amdgcn_cvt_pknorm_i16:
6374   case Intrinsic::amdgcn_cvt_pknorm_u16:
6375   case Intrinsic::amdgcn_cvt_pk_i16:
6376   case Intrinsic::amdgcn_cvt_pk_u16: {
6377     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6378     EVT VT = Op.getValueType();
6379     unsigned Opcode;
6380 
6381     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6382       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6383     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6384       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6385     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6386       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6387     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6388       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6389     else
6390       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6391 
6392     if (isTypeLegal(VT))
6393       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6394 
6395     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6396                                Op.getOperand(1), Op.getOperand(2));
6397     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6398   }
6399   case Intrinsic::amdgcn_fmad_ftz:
6400     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6401                        Op.getOperand(2), Op.getOperand(3));
6402 
6403   case Intrinsic::amdgcn_if_break:
6404     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6405                                       Op->getOperand(1), Op->getOperand(2)), 0);
6406 
6407   case Intrinsic::amdgcn_groupstaticsize: {
6408     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6409     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6410       return Op;
6411 
6412     const Module *M = MF.getFunction().getParent();
6413     const GlobalValue *GV =
6414         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6415     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6416                                             SIInstrInfo::MO_ABS32_LO);
6417     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6418   }
6419   case Intrinsic::amdgcn_is_shared:
6420   case Intrinsic::amdgcn_is_private: {
6421     SDLoc SL(Op);
6422     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6423       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6424     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6425     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6426                                  Op.getOperand(1));
6427 
6428     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6429                                 DAG.getConstant(1, SL, MVT::i32));
6430     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6431   }
6432   case Intrinsic::amdgcn_alignbit:
6433     return DAG.getNode(ISD::FSHR, DL, VT,
6434                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6435   case Intrinsic::amdgcn_reloc_constant: {
6436     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6437     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6438     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6439     auto RelocSymbol = cast<GlobalVariable>(
6440         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6441     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6442                                             SIInstrInfo::MO_ABS32_LO);
6443     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6444   }
6445   default:
6446     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6447             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6448       return lowerImage(Op, ImageDimIntr, DAG);
6449 
6450     return Op;
6451   }
6452 }
6453 
6454 // This function computes an appropriate offset to pass to
6455 // MachineMemOperand::setOffset() based on the offset inputs to
6456 // an intrinsic.  If any of the offsets are non-contstant or
6457 // if VIndex is non-zero then this function returns 0.  Otherwise,
6458 // it returns the sum of VOffset, SOffset, and Offset.
6459 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6460                                       SDValue SOffset,
6461                                       SDValue Offset,
6462                                       SDValue VIndex = SDValue()) {
6463 
6464   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6465       !isa<ConstantSDNode>(Offset))
6466     return 0;
6467 
6468   if (VIndex) {
6469     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6470       return 0;
6471   }
6472 
6473   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6474          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6475          cast<ConstantSDNode>(Offset)->getSExtValue();
6476 }
6477 
6478 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6479   switch (MF.getFunction().getCallingConv()) {
6480   case CallingConv::AMDGPU_PS:
6481     return 1;
6482   case CallingConv::AMDGPU_VS:
6483     return 2;
6484   case CallingConv::AMDGPU_GS:
6485     return 3;
6486   case CallingConv::AMDGPU_HS:
6487   case CallingConv::AMDGPU_LS:
6488   case CallingConv::AMDGPU_ES:
6489     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6490   case CallingConv::AMDGPU_CS:
6491   case CallingConv::AMDGPU_KERNEL:
6492   case CallingConv::C:
6493   case CallingConv::Fast:
6494   default:
6495     // Assume other calling conventions are various compute callable functions
6496     return 0;
6497   }
6498 }
6499 
6500 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6501                                                  SelectionDAG &DAG) const {
6502   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6503   SDLoc DL(Op);
6504 
6505   switch (IntrID) {
6506   case Intrinsic::amdgcn_ds_ordered_add:
6507   case Intrinsic::amdgcn_ds_ordered_swap: {
6508     MemSDNode *M = cast<MemSDNode>(Op);
6509     SDValue Chain = M->getOperand(0);
6510     SDValue M0 = M->getOperand(2);
6511     SDValue Value = M->getOperand(3);
6512     unsigned IndexOperand = M->getConstantOperandVal(7);
6513     unsigned WaveRelease = M->getConstantOperandVal(8);
6514     unsigned WaveDone = M->getConstantOperandVal(9);
6515 
6516     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6517     IndexOperand &= ~0x3f;
6518     unsigned CountDw = 0;
6519 
6520     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6521       CountDw = (IndexOperand >> 24) & 0xf;
6522       IndexOperand &= ~(0xf << 24);
6523 
6524       if (CountDw < 1 || CountDw > 4) {
6525         report_fatal_error(
6526             "ds_ordered_count: dword count must be between 1 and 4");
6527       }
6528     }
6529 
6530     if (IndexOperand)
6531       report_fatal_error("ds_ordered_count: bad index operand");
6532 
6533     if (WaveDone && !WaveRelease)
6534       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6535 
6536     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6537     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6538     unsigned Offset0 = OrderedCountIndex << 2;
6539     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6540                        (Instruction << 4);
6541 
6542     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6543       Offset1 |= (CountDw - 1) << 6;
6544 
6545     unsigned Offset = Offset0 | (Offset1 << 8);
6546 
6547     SDValue Ops[] = {
6548       Chain,
6549       Value,
6550       DAG.getTargetConstant(Offset, DL, MVT::i16),
6551       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6552     };
6553     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6554                                    M->getVTList(), Ops, M->getMemoryVT(),
6555                                    M->getMemOperand());
6556   }
6557   case Intrinsic::amdgcn_ds_fadd: {
6558     MemSDNode *M = cast<MemSDNode>(Op);
6559     unsigned Opc;
6560     switch (IntrID) {
6561     case Intrinsic::amdgcn_ds_fadd:
6562       Opc = ISD::ATOMIC_LOAD_FADD;
6563       break;
6564     }
6565 
6566     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6567                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6568                          M->getMemOperand());
6569   }
6570   case Intrinsic::amdgcn_atomic_inc:
6571   case Intrinsic::amdgcn_atomic_dec:
6572   case Intrinsic::amdgcn_ds_fmin:
6573   case Intrinsic::amdgcn_ds_fmax: {
6574     MemSDNode *M = cast<MemSDNode>(Op);
6575     unsigned Opc;
6576     switch (IntrID) {
6577     case Intrinsic::amdgcn_atomic_inc:
6578       Opc = AMDGPUISD::ATOMIC_INC;
6579       break;
6580     case Intrinsic::amdgcn_atomic_dec:
6581       Opc = AMDGPUISD::ATOMIC_DEC;
6582       break;
6583     case Intrinsic::amdgcn_ds_fmin:
6584       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6585       break;
6586     case Intrinsic::amdgcn_ds_fmax:
6587       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6588       break;
6589     default:
6590       llvm_unreachable("Unknown intrinsic!");
6591     }
6592     SDValue Ops[] = {
6593       M->getOperand(0), // Chain
6594       M->getOperand(2), // Ptr
6595       M->getOperand(3)  // Value
6596     };
6597 
6598     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6599                                    M->getMemoryVT(), M->getMemOperand());
6600   }
6601   case Intrinsic::amdgcn_buffer_load:
6602   case Intrinsic::amdgcn_buffer_load_format: {
6603     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6604     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6605     unsigned IdxEn = 1;
6606     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6607       IdxEn = Idx->getZExtValue() != 0;
6608     SDValue Ops[] = {
6609       Op.getOperand(0), // Chain
6610       Op.getOperand(2), // rsrc
6611       Op.getOperand(3), // vindex
6612       SDValue(),        // voffset -- will be set by setBufferOffsets
6613       SDValue(),        // soffset -- will be set by setBufferOffsets
6614       SDValue(),        // offset -- will be set by setBufferOffsets
6615       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6616       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6617     };
6618 
6619     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6620     // We don't know the offset if vindex is non-zero, so clear it.
6621     if (IdxEn)
6622       Offset = 0;
6623 
6624     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6625         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6626 
6627     EVT VT = Op.getValueType();
6628     EVT IntVT = VT.changeTypeToInteger();
6629     auto *M = cast<MemSDNode>(Op);
6630     M->getMemOperand()->setOffset(Offset);
6631     EVT LoadVT = Op.getValueType();
6632 
6633     if (LoadVT.getScalarType() == MVT::f16)
6634       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6635                                  M, DAG, Ops);
6636 
6637     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6638     if (LoadVT.getScalarType() == MVT::i8 ||
6639         LoadVT.getScalarType() == MVT::i16)
6640       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6641 
6642     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6643                                M->getMemOperand(), DAG);
6644   }
6645   case Intrinsic::amdgcn_raw_buffer_load:
6646   case Intrinsic::amdgcn_raw_buffer_load_format: {
6647     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6648 
6649     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6650     SDValue Ops[] = {
6651       Op.getOperand(0), // Chain
6652       Op.getOperand(2), // rsrc
6653       DAG.getConstant(0, DL, MVT::i32), // vindex
6654       Offsets.first,    // voffset
6655       Op.getOperand(4), // soffset
6656       Offsets.second,   // offset
6657       Op.getOperand(5), // cachepolicy, swizzled buffer
6658       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6659     };
6660 
6661     auto *M = cast<MemSDNode>(Op);
6662     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6663     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6664   }
6665   case Intrinsic::amdgcn_struct_buffer_load:
6666   case Intrinsic::amdgcn_struct_buffer_load_format: {
6667     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6668 
6669     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6670     SDValue Ops[] = {
6671       Op.getOperand(0), // Chain
6672       Op.getOperand(2), // rsrc
6673       Op.getOperand(3), // vindex
6674       Offsets.first,    // voffset
6675       Op.getOperand(5), // soffset
6676       Offsets.second,   // offset
6677       Op.getOperand(6), // cachepolicy, swizzled buffer
6678       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6679     };
6680 
6681     auto *M = cast<MemSDNode>(Op);
6682     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6683                                                         Ops[2]));
6684     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6685   }
6686   case Intrinsic::amdgcn_tbuffer_load: {
6687     MemSDNode *M = cast<MemSDNode>(Op);
6688     EVT LoadVT = Op.getValueType();
6689 
6690     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6691     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6692     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6693     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6694     unsigned IdxEn = 1;
6695     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6696       IdxEn = Idx->getZExtValue() != 0;
6697     SDValue Ops[] = {
6698       Op.getOperand(0),  // Chain
6699       Op.getOperand(2),  // rsrc
6700       Op.getOperand(3),  // vindex
6701       Op.getOperand(4),  // voffset
6702       Op.getOperand(5),  // soffset
6703       Op.getOperand(6),  // offset
6704       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6705       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6706       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6707     };
6708 
6709     if (LoadVT.getScalarType() == MVT::f16)
6710       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6711                                  M, DAG, Ops);
6712     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6713                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6714                                DAG);
6715   }
6716   case Intrinsic::amdgcn_raw_tbuffer_load: {
6717     MemSDNode *M = cast<MemSDNode>(Op);
6718     EVT LoadVT = Op.getValueType();
6719     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6720 
6721     SDValue Ops[] = {
6722       Op.getOperand(0),  // Chain
6723       Op.getOperand(2),  // rsrc
6724       DAG.getConstant(0, DL, MVT::i32), // vindex
6725       Offsets.first,     // voffset
6726       Op.getOperand(4),  // soffset
6727       Offsets.second,    // offset
6728       Op.getOperand(5),  // format
6729       Op.getOperand(6),  // cachepolicy, swizzled buffer
6730       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6731     };
6732 
6733     if (LoadVT.getScalarType() == MVT::f16)
6734       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6735                                  M, DAG, Ops);
6736     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6737                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6738                                DAG);
6739   }
6740   case Intrinsic::amdgcn_struct_tbuffer_load: {
6741     MemSDNode *M = cast<MemSDNode>(Op);
6742     EVT LoadVT = Op.getValueType();
6743     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6744 
6745     SDValue Ops[] = {
6746       Op.getOperand(0),  // Chain
6747       Op.getOperand(2),  // rsrc
6748       Op.getOperand(3),  // vindex
6749       Offsets.first,     // voffset
6750       Op.getOperand(5),  // soffset
6751       Offsets.second,    // offset
6752       Op.getOperand(6),  // format
6753       Op.getOperand(7),  // cachepolicy, swizzled buffer
6754       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6755     };
6756 
6757     if (LoadVT.getScalarType() == MVT::f16)
6758       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6759                                  M, DAG, Ops);
6760     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6761                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6762                                DAG);
6763   }
6764   case Intrinsic::amdgcn_buffer_atomic_swap:
6765   case Intrinsic::amdgcn_buffer_atomic_add:
6766   case Intrinsic::amdgcn_buffer_atomic_sub:
6767   case Intrinsic::amdgcn_buffer_atomic_smin:
6768   case Intrinsic::amdgcn_buffer_atomic_umin:
6769   case Intrinsic::amdgcn_buffer_atomic_smax:
6770   case Intrinsic::amdgcn_buffer_atomic_umax:
6771   case Intrinsic::amdgcn_buffer_atomic_and:
6772   case Intrinsic::amdgcn_buffer_atomic_or:
6773   case Intrinsic::amdgcn_buffer_atomic_xor: {
6774     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6775     unsigned IdxEn = 1;
6776     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6777       IdxEn = Idx->getZExtValue() != 0;
6778     SDValue Ops[] = {
6779       Op.getOperand(0), // Chain
6780       Op.getOperand(2), // vdata
6781       Op.getOperand(3), // rsrc
6782       Op.getOperand(4), // vindex
6783       SDValue(),        // voffset -- will be set by setBufferOffsets
6784       SDValue(),        // soffset -- will be set by setBufferOffsets
6785       SDValue(),        // offset -- will be set by setBufferOffsets
6786       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6787       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6788     };
6789     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6790     // We don't know the offset if vindex is non-zero, so clear it.
6791     if (IdxEn)
6792       Offset = 0;
6793     EVT VT = Op.getValueType();
6794 
6795     auto *M = cast<MemSDNode>(Op);
6796     M->getMemOperand()->setOffset(Offset);
6797     unsigned Opcode = 0;
6798 
6799     switch (IntrID) {
6800     case Intrinsic::amdgcn_buffer_atomic_swap:
6801       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6802       break;
6803     case Intrinsic::amdgcn_buffer_atomic_add:
6804       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6805       break;
6806     case Intrinsic::amdgcn_buffer_atomic_sub:
6807       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6808       break;
6809     case Intrinsic::amdgcn_buffer_atomic_smin:
6810       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6811       break;
6812     case Intrinsic::amdgcn_buffer_atomic_umin:
6813       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6814       break;
6815     case Intrinsic::amdgcn_buffer_atomic_smax:
6816       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6817       break;
6818     case Intrinsic::amdgcn_buffer_atomic_umax:
6819       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6820       break;
6821     case Intrinsic::amdgcn_buffer_atomic_and:
6822       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6823       break;
6824     case Intrinsic::amdgcn_buffer_atomic_or:
6825       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6826       break;
6827     case Intrinsic::amdgcn_buffer_atomic_xor:
6828       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6829       break;
6830     default:
6831       llvm_unreachable("unhandled atomic opcode");
6832     }
6833 
6834     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6835                                    M->getMemOperand());
6836   }
6837   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6838   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6839   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6840   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6841   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6842   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6843   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6844   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6845   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6846   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6847   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6848   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6849     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6850     SDValue Ops[] = {
6851       Op.getOperand(0), // Chain
6852       Op.getOperand(2), // vdata
6853       Op.getOperand(3), // rsrc
6854       DAG.getConstant(0, DL, MVT::i32), // vindex
6855       Offsets.first,    // voffset
6856       Op.getOperand(5), // soffset
6857       Offsets.second,   // offset
6858       Op.getOperand(6), // cachepolicy
6859       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6860     };
6861     EVT VT = Op.getValueType();
6862 
6863     auto *M = cast<MemSDNode>(Op);
6864     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6865     unsigned Opcode = 0;
6866 
6867     switch (IntrID) {
6868     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6869       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6870       break;
6871     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6872       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6873       break;
6874     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6875       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6876       break;
6877     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6878       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6879       break;
6880     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6881       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6882       break;
6883     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6884       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6885       break;
6886     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6887       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6888       break;
6889     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6890       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6891       break;
6892     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6893       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6894       break;
6895     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6896       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6897       break;
6898     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6899       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6900       break;
6901     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6902       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6903       break;
6904     default:
6905       llvm_unreachable("unhandled atomic opcode");
6906     }
6907 
6908     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6909                                    M->getMemOperand());
6910   }
6911   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6912   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6913   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6914   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6915   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6916   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6917   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6918   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6919   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6920   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6921   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6922   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6923     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6924     SDValue Ops[] = {
6925       Op.getOperand(0), // Chain
6926       Op.getOperand(2), // vdata
6927       Op.getOperand(3), // rsrc
6928       Op.getOperand(4), // vindex
6929       Offsets.first,    // voffset
6930       Op.getOperand(6), // soffset
6931       Offsets.second,   // offset
6932       Op.getOperand(7), // cachepolicy
6933       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6934     };
6935     EVT VT = Op.getValueType();
6936 
6937     auto *M = cast<MemSDNode>(Op);
6938     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6939                                                         Ops[3]));
6940     unsigned Opcode = 0;
6941 
6942     switch (IntrID) {
6943     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6944       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6945       break;
6946     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6947       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6948       break;
6949     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6950       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6951       break;
6952     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6953       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6954       break;
6955     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6956       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6957       break;
6958     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6959       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6960       break;
6961     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6962       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6963       break;
6964     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6965       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6966       break;
6967     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6968       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6969       break;
6970     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6971       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6972       break;
6973     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6974       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6975       break;
6976     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6977       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6978       break;
6979     default:
6980       llvm_unreachable("unhandled atomic opcode");
6981     }
6982 
6983     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6984                                    M->getMemOperand());
6985   }
6986   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6987     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6988     unsigned IdxEn = 1;
6989     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6990       IdxEn = Idx->getZExtValue() != 0;
6991     SDValue Ops[] = {
6992       Op.getOperand(0), // Chain
6993       Op.getOperand(2), // src
6994       Op.getOperand(3), // cmp
6995       Op.getOperand(4), // rsrc
6996       Op.getOperand(5), // vindex
6997       SDValue(),        // voffset -- will be set by setBufferOffsets
6998       SDValue(),        // soffset -- will be set by setBufferOffsets
6999       SDValue(),        // offset -- will be set by setBufferOffsets
7000       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7001       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7002     };
7003     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7004     // We don't know the offset if vindex is non-zero, so clear it.
7005     if (IdxEn)
7006       Offset = 0;
7007     EVT VT = Op.getValueType();
7008     auto *M = cast<MemSDNode>(Op);
7009     M->getMemOperand()->setOffset(Offset);
7010 
7011     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7012                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7013   }
7014   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7015     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7016     SDValue Ops[] = {
7017       Op.getOperand(0), // Chain
7018       Op.getOperand(2), // src
7019       Op.getOperand(3), // cmp
7020       Op.getOperand(4), // rsrc
7021       DAG.getConstant(0, DL, MVT::i32), // vindex
7022       Offsets.first,    // voffset
7023       Op.getOperand(6), // soffset
7024       Offsets.second,   // offset
7025       Op.getOperand(7), // cachepolicy
7026       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7027     };
7028     EVT VT = Op.getValueType();
7029     auto *M = cast<MemSDNode>(Op);
7030     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7031 
7032     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7033                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7034   }
7035   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7036     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7037     SDValue Ops[] = {
7038       Op.getOperand(0), // Chain
7039       Op.getOperand(2), // src
7040       Op.getOperand(3), // cmp
7041       Op.getOperand(4), // rsrc
7042       Op.getOperand(5), // vindex
7043       Offsets.first,    // voffset
7044       Op.getOperand(7), // soffset
7045       Offsets.second,   // offset
7046       Op.getOperand(8), // cachepolicy
7047       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7048     };
7049     EVT VT = Op.getValueType();
7050     auto *M = cast<MemSDNode>(Op);
7051     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7052                                                         Ops[4]));
7053 
7054     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7055                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7056   }
7057 
7058   default:
7059     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7060             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7061       return lowerImage(Op, ImageDimIntr, DAG);
7062 
7063     return SDValue();
7064   }
7065 }
7066 
7067 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7068 // dwordx4 if on SI.
7069 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7070                                               SDVTList VTList,
7071                                               ArrayRef<SDValue> Ops, EVT MemVT,
7072                                               MachineMemOperand *MMO,
7073                                               SelectionDAG &DAG) const {
7074   EVT VT = VTList.VTs[0];
7075   EVT WidenedVT = VT;
7076   EVT WidenedMemVT = MemVT;
7077   if (!Subtarget->hasDwordx3LoadStores() &&
7078       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7079     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7080                                  WidenedVT.getVectorElementType(), 4);
7081     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7082                                     WidenedMemVT.getVectorElementType(), 4);
7083     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7084   }
7085 
7086   assert(VTList.NumVTs == 2);
7087   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7088 
7089   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7090                                        WidenedMemVT, MMO);
7091   if (WidenedVT != VT) {
7092     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7093                                DAG.getVectorIdxConstant(0, DL));
7094     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7095   }
7096   return NewOp;
7097 }
7098 
7099 SDValue SITargetLowering::handleD16VData(SDValue VData,
7100                                          SelectionDAG &DAG) const {
7101   EVT StoreVT = VData.getValueType();
7102 
7103   // No change for f16 and legal vector D16 types.
7104   if (!StoreVT.isVector())
7105     return VData;
7106 
7107   SDLoc DL(VData);
7108   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
7109 
7110   if (Subtarget->hasUnpackedD16VMem()) {
7111     // We need to unpack the packed data to store.
7112     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7113     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7114 
7115     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
7116                                         StoreVT.getVectorNumElements());
7117     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7118     return DAG.UnrollVectorOp(ZExt.getNode());
7119   }
7120 
7121   assert(isTypeLegal(StoreVT));
7122   return VData;
7123 }
7124 
7125 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7126                                               SelectionDAG &DAG) const {
7127   SDLoc DL(Op);
7128   SDValue Chain = Op.getOperand(0);
7129   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7130   MachineFunction &MF = DAG.getMachineFunction();
7131 
7132   switch (IntrinsicID) {
7133   case Intrinsic::amdgcn_exp_compr: {
7134     SDValue Src0 = Op.getOperand(4);
7135     SDValue Src1 = Op.getOperand(5);
7136     // Hack around illegal type on SI by directly selecting it.
7137     if (isTypeLegal(Src0.getValueType()))
7138       return SDValue();
7139 
7140     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7141     SDValue Undef = DAG.getUNDEF(MVT::f32);
7142     const SDValue Ops[] = {
7143       Op.getOperand(2), // tgt
7144       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7145       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7146       Undef, // src2
7147       Undef, // src3
7148       Op.getOperand(7), // vm
7149       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7150       Op.getOperand(3), // en
7151       Op.getOperand(0) // Chain
7152     };
7153 
7154     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7155     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7156   }
7157   case Intrinsic::amdgcn_s_barrier: {
7158     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7159       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7160       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7161       if (WGSize <= ST.getWavefrontSize())
7162         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7163                                           Op.getOperand(0)), 0);
7164     }
7165     return SDValue();
7166   };
7167   case Intrinsic::amdgcn_tbuffer_store: {
7168     SDValue VData = Op.getOperand(2);
7169     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7170     if (IsD16)
7171       VData = handleD16VData(VData, DAG);
7172     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7173     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7174     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7175     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7176     unsigned IdxEn = 1;
7177     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7178       IdxEn = Idx->getZExtValue() != 0;
7179     SDValue Ops[] = {
7180       Chain,
7181       VData,             // vdata
7182       Op.getOperand(3),  // rsrc
7183       Op.getOperand(4),  // vindex
7184       Op.getOperand(5),  // voffset
7185       Op.getOperand(6),  // soffset
7186       Op.getOperand(7),  // offset
7187       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7188       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7189       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7190     };
7191     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7192                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7193     MemSDNode *M = cast<MemSDNode>(Op);
7194     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7195                                    M->getMemoryVT(), M->getMemOperand());
7196   }
7197 
7198   case Intrinsic::amdgcn_struct_tbuffer_store: {
7199     SDValue VData = Op.getOperand(2);
7200     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7201     if (IsD16)
7202       VData = handleD16VData(VData, DAG);
7203     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7204     SDValue Ops[] = {
7205       Chain,
7206       VData,             // vdata
7207       Op.getOperand(3),  // rsrc
7208       Op.getOperand(4),  // vindex
7209       Offsets.first,     // voffset
7210       Op.getOperand(6),  // soffset
7211       Offsets.second,    // offset
7212       Op.getOperand(7),  // format
7213       Op.getOperand(8),  // cachepolicy, swizzled buffer
7214       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7215     };
7216     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7217                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7218     MemSDNode *M = cast<MemSDNode>(Op);
7219     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7220                                    M->getMemoryVT(), M->getMemOperand());
7221   }
7222 
7223   case Intrinsic::amdgcn_raw_tbuffer_store: {
7224     SDValue VData = Op.getOperand(2);
7225     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7226     if (IsD16)
7227       VData = handleD16VData(VData, DAG);
7228     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7229     SDValue Ops[] = {
7230       Chain,
7231       VData,             // vdata
7232       Op.getOperand(3),  // rsrc
7233       DAG.getConstant(0, DL, MVT::i32), // vindex
7234       Offsets.first,     // voffset
7235       Op.getOperand(5),  // soffset
7236       Offsets.second,    // offset
7237       Op.getOperand(6),  // format
7238       Op.getOperand(7),  // cachepolicy, swizzled buffer
7239       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7240     };
7241     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7242                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7243     MemSDNode *M = cast<MemSDNode>(Op);
7244     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7245                                    M->getMemoryVT(), M->getMemOperand());
7246   }
7247 
7248   case Intrinsic::amdgcn_buffer_store:
7249   case Intrinsic::amdgcn_buffer_store_format: {
7250     SDValue VData = Op.getOperand(2);
7251     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7252     if (IsD16)
7253       VData = handleD16VData(VData, DAG);
7254     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7255     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7256     unsigned IdxEn = 1;
7257     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7258       IdxEn = Idx->getZExtValue() != 0;
7259     SDValue Ops[] = {
7260       Chain,
7261       VData,
7262       Op.getOperand(3), // rsrc
7263       Op.getOperand(4), // vindex
7264       SDValue(), // voffset -- will be set by setBufferOffsets
7265       SDValue(), // soffset -- will be set by setBufferOffsets
7266       SDValue(), // offset -- will be set by setBufferOffsets
7267       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7268       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7269     };
7270     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7271     // We don't know the offset if vindex is non-zero, so clear it.
7272     if (IdxEn)
7273       Offset = 0;
7274     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7275                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7276     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7277     MemSDNode *M = cast<MemSDNode>(Op);
7278     M->getMemOperand()->setOffset(Offset);
7279 
7280     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7281     EVT VDataType = VData.getValueType().getScalarType();
7282     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7283       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7284 
7285     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7286                                    M->getMemoryVT(), M->getMemOperand());
7287   }
7288 
7289   case Intrinsic::amdgcn_raw_buffer_store:
7290   case Intrinsic::amdgcn_raw_buffer_store_format: {
7291     const bool IsFormat =
7292         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7293 
7294     SDValue VData = Op.getOperand(2);
7295     EVT VDataVT = VData.getValueType();
7296     EVT EltType = VDataVT.getScalarType();
7297     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7298     if (IsD16)
7299       VData = handleD16VData(VData, DAG);
7300 
7301     if (!isTypeLegal(VDataVT)) {
7302       VData =
7303           DAG.getNode(ISD::BITCAST, DL,
7304                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7305     }
7306 
7307     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7308     SDValue Ops[] = {
7309       Chain,
7310       VData,
7311       Op.getOperand(3), // rsrc
7312       DAG.getConstant(0, DL, MVT::i32), // vindex
7313       Offsets.first,    // voffset
7314       Op.getOperand(5), // soffset
7315       Offsets.second,   // offset
7316       Op.getOperand(6), // cachepolicy, swizzled buffer
7317       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7318     };
7319     unsigned Opc =
7320         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7321     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7322     MemSDNode *M = cast<MemSDNode>(Op);
7323     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7324 
7325     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7326     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7327       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7328 
7329     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7330                                    M->getMemoryVT(), M->getMemOperand());
7331   }
7332 
7333   case Intrinsic::amdgcn_struct_buffer_store:
7334   case Intrinsic::amdgcn_struct_buffer_store_format: {
7335     const bool IsFormat =
7336         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7337 
7338     SDValue VData = Op.getOperand(2);
7339     EVT VDataVT = VData.getValueType();
7340     EVT EltType = VDataVT.getScalarType();
7341     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7342 
7343     if (IsD16)
7344       VData = handleD16VData(VData, DAG);
7345 
7346     if (!isTypeLegal(VDataVT)) {
7347       VData =
7348           DAG.getNode(ISD::BITCAST, DL,
7349                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7350     }
7351 
7352     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7353     SDValue Ops[] = {
7354       Chain,
7355       VData,
7356       Op.getOperand(3), // rsrc
7357       Op.getOperand(4), // vindex
7358       Offsets.first,    // voffset
7359       Op.getOperand(6), // soffset
7360       Offsets.second,   // offset
7361       Op.getOperand(7), // cachepolicy, swizzled buffer
7362       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7363     };
7364     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7365                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7366     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7367     MemSDNode *M = cast<MemSDNode>(Op);
7368     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7369                                                         Ops[3]));
7370 
7371     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7372     EVT VDataType = VData.getValueType().getScalarType();
7373     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7374       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7375 
7376     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7377                                    M->getMemoryVT(), M->getMemOperand());
7378   }
7379 
7380   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7381     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7382     unsigned IdxEn = 1;
7383     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7384       IdxEn = Idx->getZExtValue() != 0;
7385     SDValue Ops[] = {
7386       Chain,
7387       Op.getOperand(2), // vdata
7388       Op.getOperand(3), // rsrc
7389       Op.getOperand(4), // vindex
7390       SDValue(),        // voffset -- will be set by setBufferOffsets
7391       SDValue(),        // soffset -- will be set by setBufferOffsets
7392       SDValue(),        // offset -- will be set by setBufferOffsets
7393       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7394       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7395     };
7396     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7397     // We don't know the offset if vindex is non-zero, so clear it.
7398     if (IdxEn)
7399       Offset = 0;
7400     EVT VT = Op.getOperand(2).getValueType();
7401 
7402     auto *M = cast<MemSDNode>(Op);
7403     M->getMemOperand()->setOffset(Offset);
7404     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7405                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7406 
7407     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7408                                    M->getMemOperand());
7409   }
7410 
7411   case Intrinsic::amdgcn_global_atomic_fadd: {
7412     SDValue Ops[] = {
7413       Chain,
7414       Op.getOperand(2), // ptr
7415       Op.getOperand(3)  // vdata
7416     };
7417     EVT VT = Op.getOperand(3).getValueType();
7418 
7419     auto *M = cast<MemSDNode>(Op);
7420     if (VT.isVector()) {
7421       return DAG.getMemIntrinsicNode(
7422         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7423         M->getMemOperand());
7424     }
7425 
7426     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7427                          DAG.getVTList(VT, MVT::Other), Ops,
7428                          M->getMemOperand()).getValue(1);
7429   }
7430   case Intrinsic::amdgcn_end_cf:
7431     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7432                                       Op->getOperand(2), Chain), 0);
7433 
7434   default: {
7435     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7436             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7437       return lowerImage(Op, ImageDimIntr, DAG);
7438 
7439     return Op;
7440   }
7441   }
7442 }
7443 
7444 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7445 // offset (the offset that is included in bounds checking and swizzling, to be
7446 // split between the instruction's voffset and immoffset fields) and soffset
7447 // (the offset that is excluded from bounds checking and swizzling, to go in
7448 // the instruction's soffset field).  This function takes the first kind of
7449 // offset and figures out how to split it between voffset and immoffset.
7450 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7451     SDValue Offset, SelectionDAG &DAG) const {
7452   SDLoc DL(Offset);
7453   const unsigned MaxImm = 4095;
7454   SDValue N0 = Offset;
7455   ConstantSDNode *C1 = nullptr;
7456 
7457   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7458     N0 = SDValue();
7459   else if (DAG.isBaseWithConstantOffset(N0)) {
7460     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7461     N0 = N0.getOperand(0);
7462   }
7463 
7464   if (C1) {
7465     unsigned ImmOffset = C1->getZExtValue();
7466     // If the immediate value is too big for the immoffset field, put the value
7467     // and -4096 into the immoffset field so that the value that is copied/added
7468     // for the voffset field is a multiple of 4096, and it stands more chance
7469     // of being CSEd with the copy/add for another similar load/store.
7470     // However, do not do that rounding down to a multiple of 4096 if that is a
7471     // negative number, as it appears to be illegal to have a negative offset
7472     // in the vgpr, even if adding the immediate offset makes it positive.
7473     unsigned Overflow = ImmOffset & ~MaxImm;
7474     ImmOffset -= Overflow;
7475     if ((int32_t)Overflow < 0) {
7476       Overflow += ImmOffset;
7477       ImmOffset = 0;
7478     }
7479     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7480     if (Overflow) {
7481       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7482       if (!N0)
7483         N0 = OverflowVal;
7484       else {
7485         SDValue Ops[] = { N0, OverflowVal };
7486         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7487       }
7488     }
7489   }
7490   if (!N0)
7491     N0 = DAG.getConstant(0, DL, MVT::i32);
7492   if (!C1)
7493     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7494   return {N0, SDValue(C1, 0)};
7495 }
7496 
7497 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7498 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7499 // pointed to by Offsets.
7500 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7501                                         SelectionDAG &DAG, SDValue *Offsets,
7502                                         unsigned Align) const {
7503   SDLoc DL(CombinedOffset);
7504   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7505     uint32_t Imm = C->getZExtValue();
7506     uint32_t SOffset, ImmOffset;
7507     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7508       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7509       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7510       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7511       return SOffset + ImmOffset;
7512     }
7513   }
7514   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7515     SDValue N0 = CombinedOffset.getOperand(0);
7516     SDValue N1 = CombinedOffset.getOperand(1);
7517     uint32_t SOffset, ImmOffset;
7518     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7519     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7520                                                 Subtarget, Align)) {
7521       Offsets[0] = N0;
7522       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7523       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7524       return 0;
7525     }
7526   }
7527   Offsets[0] = CombinedOffset;
7528   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7529   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7530   return 0;
7531 }
7532 
7533 // Handle 8 bit and 16 bit buffer loads
7534 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7535                                                      EVT LoadVT, SDLoc DL,
7536                                                      ArrayRef<SDValue> Ops,
7537                                                      MemSDNode *M) const {
7538   EVT IntVT = LoadVT.changeTypeToInteger();
7539   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7540          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7541 
7542   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7543   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7544                                                Ops, IntVT,
7545                                                M->getMemOperand());
7546   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7547   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7548 
7549   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7550 }
7551 
7552 // Handle 8 bit and 16 bit buffer stores
7553 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7554                                                       EVT VDataType, SDLoc DL,
7555                                                       SDValue Ops[],
7556                                                       MemSDNode *M) const {
7557   if (VDataType == MVT::f16)
7558     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7559 
7560   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7561   Ops[1] = BufferStoreExt;
7562   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7563                                  AMDGPUISD::BUFFER_STORE_SHORT;
7564   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7565   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7566                                      M->getMemOperand());
7567 }
7568 
7569 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7570                                  ISD::LoadExtType ExtType, SDValue Op,
7571                                  const SDLoc &SL, EVT VT) {
7572   if (VT.bitsLT(Op.getValueType()))
7573     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7574 
7575   switch (ExtType) {
7576   case ISD::SEXTLOAD:
7577     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7578   case ISD::ZEXTLOAD:
7579     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7580   case ISD::EXTLOAD:
7581     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7582   case ISD::NON_EXTLOAD:
7583     return Op;
7584   }
7585 
7586   llvm_unreachable("invalid ext type");
7587 }
7588 
7589 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7590   SelectionDAG &DAG = DCI.DAG;
7591   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7592     return SDValue();
7593 
7594   // FIXME: Constant loads should all be marked invariant.
7595   unsigned AS = Ld->getAddressSpace();
7596   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7597       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7598       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7599     return SDValue();
7600 
7601   // Don't do this early, since it may interfere with adjacent load merging for
7602   // illegal types. We can avoid losing alignment information for exotic types
7603   // pre-legalize.
7604   EVT MemVT = Ld->getMemoryVT();
7605   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7606       MemVT.getSizeInBits() >= 32)
7607     return SDValue();
7608 
7609   SDLoc SL(Ld);
7610 
7611   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7612          "unexpected vector extload");
7613 
7614   // TODO: Drop only high part of range.
7615   SDValue Ptr = Ld->getBasePtr();
7616   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7617                                 MVT::i32, SL, Ld->getChain(), Ptr,
7618                                 Ld->getOffset(),
7619                                 Ld->getPointerInfo(), MVT::i32,
7620                                 Ld->getAlignment(),
7621                                 Ld->getMemOperand()->getFlags(),
7622                                 Ld->getAAInfo(),
7623                                 nullptr); // Drop ranges
7624 
7625   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7626   if (MemVT.isFloatingPoint()) {
7627     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7628            "unexpected fp extload");
7629     TruncVT = MemVT.changeTypeToInteger();
7630   }
7631 
7632   SDValue Cvt = NewLoad;
7633   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7634     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7635                       DAG.getValueType(TruncVT));
7636   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7637              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7638     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7639   } else {
7640     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7641   }
7642 
7643   EVT VT = Ld->getValueType(0);
7644   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7645 
7646   DCI.AddToWorklist(Cvt.getNode());
7647 
7648   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7649   // the appropriate extension from the 32-bit load.
7650   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7651   DCI.AddToWorklist(Cvt.getNode());
7652 
7653   // Handle conversion back to floating point if necessary.
7654   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7655 
7656   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7657 }
7658 
7659 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7660   SDLoc DL(Op);
7661   LoadSDNode *Load = cast<LoadSDNode>(Op);
7662   ISD::LoadExtType ExtType = Load->getExtensionType();
7663   EVT MemVT = Load->getMemoryVT();
7664 
7665   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7666     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7667       return SDValue();
7668 
7669     // FIXME: Copied from PPC
7670     // First, load into 32 bits, then truncate to 1 bit.
7671 
7672     SDValue Chain = Load->getChain();
7673     SDValue BasePtr = Load->getBasePtr();
7674     MachineMemOperand *MMO = Load->getMemOperand();
7675 
7676     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7677 
7678     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7679                                    BasePtr, RealMemVT, MMO);
7680 
7681     if (!MemVT.isVector()) {
7682       SDValue Ops[] = {
7683         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7684         NewLD.getValue(1)
7685       };
7686 
7687       return DAG.getMergeValues(Ops, DL);
7688     }
7689 
7690     SmallVector<SDValue, 3> Elts;
7691     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7692       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7693                                 DAG.getConstant(I, DL, MVT::i32));
7694 
7695       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7696     }
7697 
7698     SDValue Ops[] = {
7699       DAG.getBuildVector(MemVT, DL, Elts),
7700       NewLD.getValue(1)
7701     };
7702 
7703     return DAG.getMergeValues(Ops, DL);
7704   }
7705 
7706   if (!MemVT.isVector())
7707     return SDValue();
7708 
7709   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7710          "Custom lowering for non-i32 vectors hasn't been implemented.");
7711 
7712   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7713                                       MemVT, *Load->getMemOperand())) {
7714     SDValue Ops[2];
7715     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7716     return DAG.getMergeValues(Ops, DL);
7717   }
7718 
7719   unsigned Alignment = Load->getAlignment();
7720   unsigned AS = Load->getAddressSpace();
7721   if (Subtarget->hasLDSMisalignedBug() &&
7722       AS == AMDGPUAS::FLAT_ADDRESS &&
7723       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7724     return SplitVectorLoad(Op, DAG);
7725   }
7726 
7727   MachineFunction &MF = DAG.getMachineFunction();
7728   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7729   // If there is a possibilty that flat instruction access scratch memory
7730   // then we need to use the same legalization rules we use for private.
7731   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7732       !Subtarget->hasMultiDwordFlatScratchAddressing())
7733     AS = MFI->hasFlatScratchInit() ?
7734          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7735 
7736   unsigned NumElements = MemVT.getVectorNumElements();
7737 
7738   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7739       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7740     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7741       if (MemVT.isPow2VectorType())
7742         return SDValue();
7743       if (NumElements == 3)
7744         return WidenVectorLoad(Op, DAG);
7745       return SplitVectorLoad(Op, DAG);
7746     }
7747     // Non-uniform loads will be selected to MUBUF instructions, so they
7748     // have the same legalization requirements as global and private
7749     // loads.
7750     //
7751   }
7752 
7753   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7754       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7755       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7756     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7757         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7758         Alignment >= 4 && NumElements < 32) {
7759       if (MemVT.isPow2VectorType())
7760         return SDValue();
7761       if (NumElements == 3)
7762         return WidenVectorLoad(Op, DAG);
7763       return SplitVectorLoad(Op, DAG);
7764     }
7765     // Non-uniform loads will be selected to MUBUF instructions, so they
7766     // have the same legalization requirements as global and private
7767     // loads.
7768     //
7769   }
7770   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7771       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7772       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7773       AS == AMDGPUAS::FLAT_ADDRESS) {
7774     if (NumElements > 4)
7775       return SplitVectorLoad(Op, DAG);
7776     // v3 loads not supported on SI.
7777     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7778       return WidenVectorLoad(Op, DAG);
7779     // v3 and v4 loads are supported for private and global memory.
7780     return SDValue();
7781   }
7782   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7783     // Depending on the setting of the private_element_size field in the
7784     // resource descriptor, we can only make private accesses up to a certain
7785     // size.
7786     switch (Subtarget->getMaxPrivateElementSize()) {
7787     case 4: {
7788       SDValue Ops[2];
7789       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7790       return DAG.getMergeValues(Ops, DL);
7791     }
7792     case 8:
7793       if (NumElements > 2)
7794         return SplitVectorLoad(Op, DAG);
7795       return SDValue();
7796     case 16:
7797       // Same as global/flat
7798       if (NumElements > 4)
7799         return SplitVectorLoad(Op, DAG);
7800       // v3 loads not supported on SI.
7801       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7802         return WidenVectorLoad(Op, DAG);
7803       return SDValue();
7804     default:
7805       llvm_unreachable("unsupported private_element_size");
7806     }
7807   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7808     // Use ds_read_b128 if possible.
7809     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7810         MemVT.getStoreSize() == 16)
7811       return SDValue();
7812 
7813     if (NumElements > 2)
7814       return SplitVectorLoad(Op, DAG);
7815 
7816     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7817     // address is negative, then the instruction is incorrectly treated as
7818     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7819     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7820     // load later in the SILoadStoreOptimizer.
7821     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7822         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7823         Load->getAlignment() < 8) {
7824       return SplitVectorLoad(Op, DAG);
7825     }
7826   }
7827   return SDValue();
7828 }
7829 
7830 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7831   EVT VT = Op.getValueType();
7832   assert(VT.getSizeInBits() == 64);
7833 
7834   SDLoc DL(Op);
7835   SDValue Cond = Op.getOperand(0);
7836 
7837   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7838   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7839 
7840   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7841   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7842 
7843   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7844   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7845 
7846   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7847 
7848   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7849   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7850 
7851   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7852 
7853   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7854   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7855 }
7856 
7857 // Catch division cases where we can use shortcuts with rcp and rsq
7858 // instructions.
7859 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7860                                               SelectionDAG &DAG) const {
7861   SDLoc SL(Op);
7862   SDValue LHS = Op.getOperand(0);
7863   SDValue RHS = Op.getOperand(1);
7864   EVT VT = Op.getValueType();
7865   const SDNodeFlags Flags = Op->getFlags();
7866 
7867   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7868                             Flags.hasApproximateFuncs();
7869 
7870   // Without !fpmath accuracy information, we can't do more because we don't
7871   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7872   if (!AllowInaccurateRcp)
7873     return SDValue();
7874 
7875   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7876     if (CLHS->isExactlyValue(1.0)) {
7877       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7878       // the CI documentation has a worst case error of 1 ulp.
7879       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7880       // use it as long as we aren't trying to use denormals.
7881       //
7882       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7883 
7884       // 1.0 / sqrt(x) -> rsq(x)
7885 
7886       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7887       // error seems really high at 2^29 ULP.
7888       if (RHS.getOpcode() == ISD::FSQRT)
7889         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7890 
7891       // 1.0 / x -> rcp(x)
7892       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7893     }
7894 
7895     // Same as for 1.0, but expand the sign out of the constant.
7896     if (CLHS->isExactlyValue(-1.0)) {
7897       // -1.0 / x -> rcp (fneg x)
7898       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7899       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7900     }
7901   }
7902 
7903   // Turn into multiply by the reciprocal.
7904   // x / y -> x * (1.0 / y)
7905   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7906   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7907 }
7908 
7909 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7910                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
7911                           SDNodeFlags Flags) {
7912   if (GlueChain->getNumValues() <= 1) {
7913     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
7914   }
7915 
7916   assert(GlueChain->getNumValues() == 3);
7917 
7918   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7919   switch (Opcode) {
7920   default: llvm_unreachable("no chain equivalent for opcode");
7921   case ISD::FMUL:
7922     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7923     break;
7924   }
7925 
7926   return DAG.getNode(Opcode, SL, VTList,
7927                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
7928                      Flags);
7929 }
7930 
7931 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7932                            EVT VT, SDValue A, SDValue B, SDValue C,
7933                            SDValue GlueChain, SDNodeFlags Flags) {
7934   if (GlueChain->getNumValues() <= 1) {
7935     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
7936   }
7937 
7938   assert(GlueChain->getNumValues() == 3);
7939 
7940   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7941   switch (Opcode) {
7942   default: llvm_unreachable("no chain equivalent for opcode");
7943   case ISD::FMA:
7944     Opcode = AMDGPUISD::FMA_W_CHAIN;
7945     break;
7946   }
7947 
7948   return DAG.getNode(Opcode, SL, VTList,
7949                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
7950                      Flags);
7951 }
7952 
7953 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7954   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7955     return FastLowered;
7956 
7957   SDLoc SL(Op);
7958   SDValue Src0 = Op.getOperand(0);
7959   SDValue Src1 = Op.getOperand(1);
7960 
7961   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7962   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7963 
7964   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7965   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7966 
7967   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7968   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7969 
7970   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7971 }
7972 
7973 // Faster 2.5 ULP division that does not support denormals.
7974 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7975   SDLoc SL(Op);
7976   SDValue LHS = Op.getOperand(1);
7977   SDValue RHS = Op.getOperand(2);
7978 
7979   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7980 
7981   const APFloat K0Val(BitsToFloat(0x6f800000));
7982   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7983 
7984   const APFloat K1Val(BitsToFloat(0x2f800000));
7985   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7986 
7987   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7988 
7989   EVT SetCCVT =
7990     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7991 
7992   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7993 
7994   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7995 
7996   // TODO: Should this propagate fast-math-flags?
7997   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7998 
7999   // rcp does not support denormals.
8000   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8001 
8002   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8003 
8004   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8005 }
8006 
8007 // Returns immediate value for setting the F32 denorm mode when using the
8008 // S_DENORM_MODE instruction.
8009 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8010                                           const SDLoc &SL, const GCNSubtarget *ST) {
8011   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8012   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8013                                 ? FP_DENORM_FLUSH_NONE
8014                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8015 
8016   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8017   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8018 }
8019 
8020 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8021   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8022     return FastLowered;
8023 
8024   // The selection matcher assumes anything with a chain selecting to a
8025   // mayRaiseFPException machine instruction. Since we're introducing a chain
8026   // here, we need to explicitly report nofpexcept for the regular fdiv
8027   // lowering.
8028   SDNodeFlags Flags = Op->getFlags();
8029   Flags.setNoFPExcept(true);
8030 
8031   SDLoc SL(Op);
8032   SDValue LHS = Op.getOperand(0);
8033   SDValue RHS = Op.getOperand(1);
8034 
8035   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8036 
8037   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8038 
8039   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8040                                           {RHS, RHS, LHS}, Flags);
8041   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8042                                         {LHS, RHS, LHS}, Flags);
8043 
8044   // Denominator is scaled to not be denormal, so using rcp is ok.
8045   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8046                                   DenominatorScaled, Flags);
8047   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8048                                      DenominatorScaled, Flags);
8049 
8050   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8051                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8052                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8053   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8054 
8055   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8056 
8057   if (!HasFP32Denormals) {
8058     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8059     // lowering. The chain dependence is insufficient, and we need glue. We do
8060     // not need the glue variants in a strictfp function.
8061 
8062     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8063 
8064     SDNode *EnableDenorm;
8065     if (Subtarget->hasDenormModeInst()) {
8066       const SDValue EnableDenormValue =
8067           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8068 
8069       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8070                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8071     } else {
8072       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8073                                                         SL, MVT::i32);
8074       EnableDenorm =
8075           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8076                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8077     }
8078 
8079     SDValue Ops[3] = {
8080       NegDivScale0,
8081       SDValue(EnableDenorm, 0),
8082       SDValue(EnableDenorm, 1)
8083     };
8084 
8085     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8086   }
8087 
8088   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8089                              ApproxRcp, One, NegDivScale0, Flags);
8090 
8091   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8092                              ApproxRcp, Fma0, Flags);
8093 
8094   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8095                            Fma1, Fma1, Flags);
8096 
8097   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8098                              NumeratorScaled, Mul, Flags);
8099 
8100   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8101                              Fma2, Fma1, Mul, Fma2, Flags);
8102 
8103   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8104                              NumeratorScaled, Fma3, Flags);
8105 
8106   if (!HasFP32Denormals) {
8107     SDNode *DisableDenorm;
8108     if (Subtarget->hasDenormModeInst()) {
8109       const SDValue DisableDenormValue =
8110           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8111 
8112       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8113                                   Fma4.getValue(1), DisableDenormValue,
8114                                   Fma4.getValue(2)).getNode();
8115     } else {
8116       const SDValue DisableDenormValue =
8117           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8118 
8119       DisableDenorm = DAG.getMachineNode(
8120           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8121           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8122     }
8123 
8124     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8125                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8126     DAG.setRoot(OutputChain);
8127   }
8128 
8129   SDValue Scale = NumeratorScaled.getValue(1);
8130   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8131                              {Fma4, Fma1, Fma3, Scale}, Flags);
8132 
8133   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8134 }
8135 
8136 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8137   if (DAG.getTarget().Options.UnsafeFPMath)
8138     return lowerFastUnsafeFDIV(Op, DAG);
8139 
8140   SDLoc SL(Op);
8141   SDValue X = Op.getOperand(0);
8142   SDValue Y = Op.getOperand(1);
8143 
8144   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8145 
8146   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8147 
8148   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8149 
8150   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8151 
8152   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8153 
8154   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8155 
8156   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8157 
8158   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8159 
8160   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8161 
8162   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8163   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8164 
8165   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8166                              NegDivScale0, Mul, DivScale1);
8167 
8168   SDValue Scale;
8169 
8170   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8171     // Workaround a hardware bug on SI where the condition output from div_scale
8172     // is not usable.
8173 
8174     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8175 
8176     // Figure out if the scale to use for div_fmas.
8177     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8178     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8179     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8180     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8181 
8182     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8183     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8184 
8185     SDValue Scale0Hi
8186       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8187     SDValue Scale1Hi
8188       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8189 
8190     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8191     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8192     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8193   } else {
8194     Scale = DivScale1.getValue(1);
8195   }
8196 
8197   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8198                              Fma4, Fma3, Mul, Scale);
8199 
8200   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8201 }
8202 
8203 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8204   EVT VT = Op.getValueType();
8205 
8206   if (VT == MVT::f32)
8207     return LowerFDIV32(Op, DAG);
8208 
8209   if (VT == MVT::f64)
8210     return LowerFDIV64(Op, DAG);
8211 
8212   if (VT == MVT::f16)
8213     return LowerFDIV16(Op, DAG);
8214 
8215   llvm_unreachable("Unexpected type for fdiv");
8216 }
8217 
8218 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8219   SDLoc DL(Op);
8220   StoreSDNode *Store = cast<StoreSDNode>(Op);
8221   EVT VT = Store->getMemoryVT();
8222 
8223   if (VT == MVT::i1) {
8224     return DAG.getTruncStore(Store->getChain(), DL,
8225        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8226        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8227   }
8228 
8229   assert(VT.isVector() &&
8230          Store->getValue().getValueType().getScalarType() == MVT::i32);
8231 
8232   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8233                                       VT, *Store->getMemOperand())) {
8234     return expandUnalignedStore(Store, DAG);
8235   }
8236 
8237   unsigned AS = Store->getAddressSpace();
8238   if (Subtarget->hasLDSMisalignedBug() &&
8239       AS == AMDGPUAS::FLAT_ADDRESS &&
8240       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8241     return SplitVectorStore(Op, DAG);
8242   }
8243 
8244   MachineFunction &MF = DAG.getMachineFunction();
8245   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8246   // If there is a possibilty that flat instruction access scratch memory
8247   // then we need to use the same legalization rules we use for private.
8248   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8249       !Subtarget->hasMultiDwordFlatScratchAddressing())
8250     AS = MFI->hasFlatScratchInit() ?
8251          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8252 
8253   unsigned NumElements = VT.getVectorNumElements();
8254   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8255       AS == AMDGPUAS::FLAT_ADDRESS) {
8256     if (NumElements > 4)
8257       return SplitVectorStore(Op, DAG);
8258     // v3 stores not supported on SI.
8259     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8260       return SplitVectorStore(Op, DAG);
8261     return SDValue();
8262   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8263     switch (Subtarget->getMaxPrivateElementSize()) {
8264     case 4:
8265       return scalarizeVectorStore(Store, DAG);
8266     case 8:
8267       if (NumElements > 2)
8268         return SplitVectorStore(Op, DAG);
8269       return SDValue();
8270     case 16:
8271       if (NumElements > 4 || NumElements == 3)
8272         return SplitVectorStore(Op, DAG);
8273       return SDValue();
8274     default:
8275       llvm_unreachable("unsupported private_element_size");
8276     }
8277   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8278     // Use ds_write_b128 if possible.
8279     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8280         VT.getStoreSize() == 16 && NumElements != 3)
8281       return SDValue();
8282 
8283     if (NumElements > 2)
8284       return SplitVectorStore(Op, DAG);
8285 
8286     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8287     // address is negative, then the instruction is incorrectly treated as
8288     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8289     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8290     // store later in the SILoadStoreOptimizer.
8291     if (!Subtarget->hasUsableDSOffset() &&
8292         NumElements == 2 && VT.getStoreSize() == 8 &&
8293         Store->getAlignment() < 8) {
8294       return SplitVectorStore(Op, DAG);
8295     }
8296 
8297     return SDValue();
8298   } else {
8299     llvm_unreachable("unhandled address space");
8300   }
8301 }
8302 
8303 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8304   SDLoc DL(Op);
8305   EVT VT = Op.getValueType();
8306   SDValue Arg = Op.getOperand(0);
8307   SDValue TrigVal;
8308 
8309   // Propagate fast-math flags so that the multiply we introduce can be folded
8310   // if Arg is already the result of a multiply by constant.
8311   auto Flags = Op->getFlags();
8312 
8313   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8314 
8315   if (Subtarget->hasTrigReducedRange()) {
8316     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8317     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8318   } else {
8319     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8320   }
8321 
8322   switch (Op.getOpcode()) {
8323   case ISD::FCOS:
8324     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8325   case ISD::FSIN:
8326     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8327   default:
8328     llvm_unreachable("Wrong trig opcode");
8329   }
8330 }
8331 
8332 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8333   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8334   assert(AtomicNode->isCompareAndSwap());
8335   unsigned AS = AtomicNode->getAddressSpace();
8336 
8337   // No custom lowering required for local address space
8338   if (!isFlatGlobalAddrSpace(AS))
8339     return Op;
8340 
8341   // Non-local address space requires custom lowering for atomic compare
8342   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8343   SDLoc DL(Op);
8344   SDValue ChainIn = Op.getOperand(0);
8345   SDValue Addr = Op.getOperand(1);
8346   SDValue Old = Op.getOperand(2);
8347   SDValue New = Op.getOperand(3);
8348   EVT VT = Op.getValueType();
8349   MVT SimpleVT = VT.getSimpleVT();
8350   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8351 
8352   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8353   SDValue Ops[] = { ChainIn, Addr, NewOld };
8354 
8355   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8356                                  Ops, VT, AtomicNode->getMemOperand());
8357 }
8358 
8359 //===----------------------------------------------------------------------===//
8360 // Custom DAG optimizations
8361 //===----------------------------------------------------------------------===//
8362 
8363 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8364                                                      DAGCombinerInfo &DCI) const {
8365   EVT VT = N->getValueType(0);
8366   EVT ScalarVT = VT.getScalarType();
8367   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8368     return SDValue();
8369 
8370   SelectionDAG &DAG = DCI.DAG;
8371   SDLoc DL(N);
8372 
8373   SDValue Src = N->getOperand(0);
8374   EVT SrcVT = Src.getValueType();
8375 
8376   // TODO: We could try to match extracting the higher bytes, which would be
8377   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8378   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8379   // about in practice.
8380   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8381     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8382       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8383       DCI.AddToWorklist(Cvt.getNode());
8384 
8385       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8386       if (ScalarVT != MVT::f32) {
8387         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8388                           DAG.getTargetConstant(0, DL, MVT::i32));
8389       }
8390       return Cvt;
8391     }
8392   }
8393 
8394   return SDValue();
8395 }
8396 
8397 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8398 
8399 // This is a variant of
8400 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8401 //
8402 // The normal DAG combiner will do this, but only if the add has one use since
8403 // that would increase the number of instructions.
8404 //
8405 // This prevents us from seeing a constant offset that can be folded into a
8406 // memory instruction's addressing mode. If we know the resulting add offset of
8407 // a pointer can be folded into an addressing offset, we can replace the pointer
8408 // operand with the add of new constant offset. This eliminates one of the uses,
8409 // and may allow the remaining use to also be simplified.
8410 //
8411 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8412                                                unsigned AddrSpace,
8413                                                EVT MemVT,
8414                                                DAGCombinerInfo &DCI) const {
8415   SDValue N0 = N->getOperand(0);
8416   SDValue N1 = N->getOperand(1);
8417 
8418   // We only do this to handle cases where it's profitable when there are
8419   // multiple uses of the add, so defer to the standard combine.
8420   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8421       N0->hasOneUse())
8422     return SDValue();
8423 
8424   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8425   if (!CN1)
8426     return SDValue();
8427 
8428   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8429   if (!CAdd)
8430     return SDValue();
8431 
8432   // If the resulting offset is too large, we can't fold it into the addressing
8433   // mode offset.
8434   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8435   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8436 
8437   AddrMode AM;
8438   AM.HasBaseReg = true;
8439   AM.BaseOffs = Offset.getSExtValue();
8440   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8441     return SDValue();
8442 
8443   SelectionDAG &DAG = DCI.DAG;
8444   SDLoc SL(N);
8445   EVT VT = N->getValueType(0);
8446 
8447   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8448   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8449 
8450   SDNodeFlags Flags;
8451   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8452                           (N0.getOpcode() == ISD::OR ||
8453                            N0->getFlags().hasNoUnsignedWrap()));
8454 
8455   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8456 }
8457 
8458 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8459                                                   DAGCombinerInfo &DCI) const {
8460   SDValue Ptr = N->getBasePtr();
8461   SelectionDAG &DAG = DCI.DAG;
8462   SDLoc SL(N);
8463 
8464   // TODO: We could also do this for multiplies.
8465   if (Ptr.getOpcode() == ISD::SHL) {
8466     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8467                                           N->getMemoryVT(), DCI);
8468     if (NewPtr) {
8469       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8470 
8471       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8472       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8473     }
8474   }
8475 
8476   return SDValue();
8477 }
8478 
8479 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8480   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8481          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8482          (Opc == ISD::XOR && Val == 0);
8483 }
8484 
8485 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8486 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8487 // integer combine opportunities since most 64-bit operations are decomposed
8488 // this way.  TODO: We won't want this for SALU especially if it is an inline
8489 // immediate.
8490 SDValue SITargetLowering::splitBinaryBitConstantOp(
8491   DAGCombinerInfo &DCI,
8492   const SDLoc &SL,
8493   unsigned Opc, SDValue LHS,
8494   const ConstantSDNode *CRHS) const {
8495   uint64_t Val = CRHS->getZExtValue();
8496   uint32_t ValLo = Lo_32(Val);
8497   uint32_t ValHi = Hi_32(Val);
8498   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8499 
8500     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8501          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8502         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8503     // If we need to materialize a 64-bit immediate, it will be split up later
8504     // anyway. Avoid creating the harder to understand 64-bit immediate
8505     // materialization.
8506     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8507   }
8508 
8509   return SDValue();
8510 }
8511 
8512 // Returns true if argument is a boolean value which is not serialized into
8513 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8514 static bool isBoolSGPR(SDValue V) {
8515   if (V.getValueType() != MVT::i1)
8516     return false;
8517   switch (V.getOpcode()) {
8518   default: break;
8519   case ISD::SETCC:
8520   case ISD::AND:
8521   case ISD::OR:
8522   case ISD::XOR:
8523   case AMDGPUISD::FP_CLASS:
8524     return true;
8525   }
8526   return false;
8527 }
8528 
8529 // If a constant has all zeroes or all ones within each byte return it.
8530 // Otherwise return 0.
8531 static uint32_t getConstantPermuteMask(uint32_t C) {
8532   // 0xff for any zero byte in the mask
8533   uint32_t ZeroByteMask = 0;
8534   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8535   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8536   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8537   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8538   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8539   if ((NonZeroByteMask & C) != NonZeroByteMask)
8540     return 0; // Partial bytes selected.
8541   return C;
8542 }
8543 
8544 // Check if a node selects whole bytes from its operand 0 starting at a byte
8545 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8546 // or -1 if not succeeded.
8547 // Note byte select encoding:
8548 // value 0-3 selects corresponding source byte;
8549 // value 0xc selects zero;
8550 // value 0xff selects 0xff.
8551 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8552   assert(V.getValueSizeInBits() == 32);
8553 
8554   if (V.getNumOperands() != 2)
8555     return ~0;
8556 
8557   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8558   if (!N1)
8559     return ~0;
8560 
8561   uint32_t C = N1->getZExtValue();
8562 
8563   switch (V.getOpcode()) {
8564   default:
8565     break;
8566   case ISD::AND:
8567     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8568       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8569     }
8570     break;
8571 
8572   case ISD::OR:
8573     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8574       return (0x03020100 & ~ConstMask) | ConstMask;
8575     }
8576     break;
8577 
8578   case ISD::SHL:
8579     if (C % 8)
8580       return ~0;
8581 
8582     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8583 
8584   case ISD::SRL:
8585     if (C % 8)
8586       return ~0;
8587 
8588     return uint32_t(0x0c0c0c0c03020100ull >> C);
8589   }
8590 
8591   return ~0;
8592 }
8593 
8594 SDValue SITargetLowering::performAndCombine(SDNode *N,
8595                                             DAGCombinerInfo &DCI) const {
8596   if (DCI.isBeforeLegalize())
8597     return SDValue();
8598 
8599   SelectionDAG &DAG = DCI.DAG;
8600   EVT VT = N->getValueType(0);
8601   SDValue LHS = N->getOperand(0);
8602   SDValue RHS = N->getOperand(1);
8603 
8604 
8605   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8606   if (VT == MVT::i64 && CRHS) {
8607     if (SDValue Split
8608         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8609       return Split;
8610   }
8611 
8612   if (CRHS && VT == MVT::i32) {
8613     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8614     // nb = number of trailing zeroes in mask
8615     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8616     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8617     uint64_t Mask = CRHS->getZExtValue();
8618     unsigned Bits = countPopulation(Mask);
8619     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8620         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8621       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8622         unsigned Shift = CShift->getZExtValue();
8623         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8624         unsigned Offset = NB + Shift;
8625         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8626           SDLoc SL(N);
8627           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8628                                     LHS->getOperand(0),
8629                                     DAG.getConstant(Offset, SL, MVT::i32),
8630                                     DAG.getConstant(Bits, SL, MVT::i32));
8631           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8632           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8633                                     DAG.getValueType(NarrowVT));
8634           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8635                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8636           return Shl;
8637         }
8638       }
8639     }
8640 
8641     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8642     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8643         isa<ConstantSDNode>(LHS.getOperand(2))) {
8644       uint32_t Sel = getConstantPermuteMask(Mask);
8645       if (!Sel)
8646         return SDValue();
8647 
8648       // Select 0xc for all zero bytes
8649       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8650       SDLoc DL(N);
8651       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8652                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8653     }
8654   }
8655 
8656   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8657   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8658   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8659     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8660     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8661 
8662     SDValue X = LHS.getOperand(0);
8663     SDValue Y = RHS.getOperand(0);
8664     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8665       return SDValue();
8666 
8667     if (LCC == ISD::SETO) {
8668       if (X != LHS.getOperand(1))
8669         return SDValue();
8670 
8671       if (RCC == ISD::SETUNE) {
8672         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8673         if (!C1 || !C1->isInfinity() || C1->isNegative())
8674           return SDValue();
8675 
8676         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8677                               SIInstrFlags::N_SUBNORMAL |
8678                               SIInstrFlags::N_ZERO |
8679                               SIInstrFlags::P_ZERO |
8680                               SIInstrFlags::P_SUBNORMAL |
8681                               SIInstrFlags::P_NORMAL;
8682 
8683         static_assert(((~(SIInstrFlags::S_NAN |
8684                           SIInstrFlags::Q_NAN |
8685                           SIInstrFlags::N_INFINITY |
8686                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8687                       "mask not equal");
8688 
8689         SDLoc DL(N);
8690         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8691                            X, DAG.getConstant(Mask, DL, MVT::i32));
8692       }
8693     }
8694   }
8695 
8696   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8697     std::swap(LHS, RHS);
8698 
8699   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8700       RHS.hasOneUse()) {
8701     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8702     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8703     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8704     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8705     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8706         (RHS.getOperand(0) == LHS.getOperand(0) &&
8707          LHS.getOperand(0) == LHS.getOperand(1))) {
8708       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8709       unsigned NewMask = LCC == ISD::SETO ?
8710         Mask->getZExtValue() & ~OrdMask :
8711         Mask->getZExtValue() & OrdMask;
8712 
8713       SDLoc DL(N);
8714       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8715                          DAG.getConstant(NewMask, DL, MVT::i32));
8716     }
8717   }
8718 
8719   if (VT == MVT::i32 &&
8720       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8721     // and x, (sext cc from i1) => select cc, x, 0
8722     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8723       std::swap(LHS, RHS);
8724     if (isBoolSGPR(RHS.getOperand(0)))
8725       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8726                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8727   }
8728 
8729   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8730   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8731   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8732       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8733     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8734     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8735     if (LHSMask != ~0u && RHSMask != ~0u) {
8736       // Canonicalize the expression in an attempt to have fewer unique masks
8737       // and therefore fewer registers used to hold the masks.
8738       if (LHSMask > RHSMask) {
8739         std::swap(LHSMask, RHSMask);
8740         std::swap(LHS, RHS);
8741       }
8742 
8743       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8744       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8745       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8746       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8747 
8748       // Check of we need to combine values from two sources within a byte.
8749       if (!(LHSUsedLanes & RHSUsedLanes) &&
8750           // If we select high and lower word keep it for SDWA.
8751           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8752           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8753         // Each byte in each mask is either selector mask 0-3, or has higher
8754         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8755         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8756         // mask which is not 0xff wins. By anding both masks we have a correct
8757         // result except that 0x0c shall be corrected to give 0x0c only.
8758         uint32_t Mask = LHSMask & RHSMask;
8759         for (unsigned I = 0; I < 32; I += 8) {
8760           uint32_t ByteSel = 0xff << I;
8761           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8762             Mask &= (0x0c << I) & 0xffffffff;
8763         }
8764 
8765         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8766         // or 0x0c.
8767         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8768         SDLoc DL(N);
8769 
8770         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8771                            LHS.getOperand(0), RHS.getOperand(0),
8772                            DAG.getConstant(Sel, DL, MVT::i32));
8773       }
8774     }
8775   }
8776 
8777   return SDValue();
8778 }
8779 
8780 SDValue SITargetLowering::performOrCombine(SDNode *N,
8781                                            DAGCombinerInfo &DCI) const {
8782   SelectionDAG &DAG = DCI.DAG;
8783   SDValue LHS = N->getOperand(0);
8784   SDValue RHS = N->getOperand(1);
8785 
8786   EVT VT = N->getValueType(0);
8787   if (VT == MVT::i1) {
8788     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8789     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8790         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8791       SDValue Src = LHS.getOperand(0);
8792       if (Src != RHS.getOperand(0))
8793         return SDValue();
8794 
8795       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8796       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8797       if (!CLHS || !CRHS)
8798         return SDValue();
8799 
8800       // Only 10 bits are used.
8801       static const uint32_t MaxMask = 0x3ff;
8802 
8803       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8804       SDLoc DL(N);
8805       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8806                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8807     }
8808 
8809     return SDValue();
8810   }
8811 
8812   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8813   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8814       LHS.getOpcode() == AMDGPUISD::PERM &&
8815       isa<ConstantSDNode>(LHS.getOperand(2))) {
8816     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8817     if (!Sel)
8818       return SDValue();
8819 
8820     Sel |= LHS.getConstantOperandVal(2);
8821     SDLoc DL(N);
8822     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8823                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8824   }
8825 
8826   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8827   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8828   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8829       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8830     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8831     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8832     if (LHSMask != ~0u && RHSMask != ~0u) {
8833       // Canonicalize the expression in an attempt to have fewer unique masks
8834       // and therefore fewer registers used to hold the masks.
8835       if (LHSMask > RHSMask) {
8836         std::swap(LHSMask, RHSMask);
8837         std::swap(LHS, RHS);
8838       }
8839 
8840       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8841       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8842       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8843       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8844 
8845       // Check of we need to combine values from two sources within a byte.
8846       if (!(LHSUsedLanes & RHSUsedLanes) &&
8847           // If we select high and lower word keep it for SDWA.
8848           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8849           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8850         // Kill zero bytes selected by other mask. Zero value is 0xc.
8851         LHSMask &= ~RHSUsedLanes;
8852         RHSMask &= ~LHSUsedLanes;
8853         // Add 4 to each active LHS lane
8854         LHSMask |= LHSUsedLanes & 0x04040404;
8855         // Combine masks
8856         uint32_t Sel = LHSMask | RHSMask;
8857         SDLoc DL(N);
8858 
8859         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8860                            LHS.getOperand(0), RHS.getOperand(0),
8861                            DAG.getConstant(Sel, DL, MVT::i32));
8862       }
8863     }
8864   }
8865 
8866   if (VT != MVT::i64)
8867     return SDValue();
8868 
8869   // TODO: This could be a generic combine with a predicate for extracting the
8870   // high half of an integer being free.
8871 
8872   // (or i64:x, (zero_extend i32:y)) ->
8873   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8874   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8875       RHS.getOpcode() != ISD::ZERO_EXTEND)
8876     std::swap(LHS, RHS);
8877 
8878   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8879     SDValue ExtSrc = RHS.getOperand(0);
8880     EVT SrcVT = ExtSrc.getValueType();
8881     if (SrcVT == MVT::i32) {
8882       SDLoc SL(N);
8883       SDValue LowLHS, HiBits;
8884       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8885       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8886 
8887       DCI.AddToWorklist(LowOr.getNode());
8888       DCI.AddToWorklist(HiBits.getNode());
8889 
8890       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8891                                 LowOr, HiBits);
8892       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8893     }
8894   }
8895 
8896   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8897   if (CRHS) {
8898     if (SDValue Split
8899           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8900       return Split;
8901   }
8902 
8903   return SDValue();
8904 }
8905 
8906 SDValue SITargetLowering::performXorCombine(SDNode *N,
8907                                             DAGCombinerInfo &DCI) const {
8908   EVT VT = N->getValueType(0);
8909   if (VT != MVT::i64)
8910     return SDValue();
8911 
8912   SDValue LHS = N->getOperand(0);
8913   SDValue RHS = N->getOperand(1);
8914 
8915   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8916   if (CRHS) {
8917     if (SDValue Split
8918           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8919       return Split;
8920   }
8921 
8922   return SDValue();
8923 }
8924 
8925 // Instructions that will be lowered with a final instruction that zeros the
8926 // high result bits.
8927 // XXX - probably only need to list legal operations.
8928 static bool fp16SrcZerosHighBits(unsigned Opc) {
8929   switch (Opc) {
8930   case ISD::FADD:
8931   case ISD::FSUB:
8932   case ISD::FMUL:
8933   case ISD::FDIV:
8934   case ISD::FREM:
8935   case ISD::FMA:
8936   case ISD::FMAD:
8937   case ISD::FCANONICALIZE:
8938   case ISD::FP_ROUND:
8939   case ISD::UINT_TO_FP:
8940   case ISD::SINT_TO_FP:
8941   case ISD::FABS:
8942     // Fabs is lowered to a bit operation, but it's an and which will clear the
8943     // high bits anyway.
8944   case ISD::FSQRT:
8945   case ISD::FSIN:
8946   case ISD::FCOS:
8947   case ISD::FPOWI:
8948   case ISD::FPOW:
8949   case ISD::FLOG:
8950   case ISD::FLOG2:
8951   case ISD::FLOG10:
8952   case ISD::FEXP:
8953   case ISD::FEXP2:
8954   case ISD::FCEIL:
8955   case ISD::FTRUNC:
8956   case ISD::FRINT:
8957   case ISD::FNEARBYINT:
8958   case ISD::FROUND:
8959   case ISD::FFLOOR:
8960   case ISD::FMINNUM:
8961   case ISD::FMAXNUM:
8962   case AMDGPUISD::FRACT:
8963   case AMDGPUISD::CLAMP:
8964   case AMDGPUISD::COS_HW:
8965   case AMDGPUISD::SIN_HW:
8966   case AMDGPUISD::FMIN3:
8967   case AMDGPUISD::FMAX3:
8968   case AMDGPUISD::FMED3:
8969   case AMDGPUISD::FMAD_FTZ:
8970   case AMDGPUISD::RCP:
8971   case AMDGPUISD::RSQ:
8972   case AMDGPUISD::RCP_IFLAG:
8973   case AMDGPUISD::LDEXP:
8974     return true;
8975   default:
8976     // fcopysign, select and others may be lowered to 32-bit bit operations
8977     // which don't zero the high bits.
8978     return false;
8979   }
8980 }
8981 
8982 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8983                                                    DAGCombinerInfo &DCI) const {
8984   if (!Subtarget->has16BitInsts() ||
8985       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8986     return SDValue();
8987 
8988   EVT VT = N->getValueType(0);
8989   if (VT != MVT::i32)
8990     return SDValue();
8991 
8992   SDValue Src = N->getOperand(0);
8993   if (Src.getValueType() != MVT::i16)
8994     return SDValue();
8995 
8996   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8997   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8998   if (Src.getOpcode() == ISD::BITCAST) {
8999     SDValue BCSrc = Src.getOperand(0);
9000     if (BCSrc.getValueType() == MVT::f16 &&
9001         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9002       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9003   }
9004 
9005   return SDValue();
9006 }
9007 
9008 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9009                                                         DAGCombinerInfo &DCI)
9010                                                         const {
9011   SDValue Src = N->getOperand(0);
9012   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9013 
9014   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9015       VTSign->getVT() == MVT::i8) ||
9016       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9017       VTSign->getVT() == MVT::i16)) &&
9018       Src.hasOneUse()) {
9019     auto *M = cast<MemSDNode>(Src);
9020     SDValue Ops[] = {
9021       Src.getOperand(0), // Chain
9022       Src.getOperand(1), // rsrc
9023       Src.getOperand(2), // vindex
9024       Src.getOperand(3), // voffset
9025       Src.getOperand(4), // soffset
9026       Src.getOperand(5), // offset
9027       Src.getOperand(6),
9028       Src.getOperand(7)
9029     };
9030     // replace with BUFFER_LOAD_BYTE/SHORT
9031     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9032                                          Src.getOperand(0).getValueType());
9033     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9034                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9035     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9036                                                           ResList,
9037                                                           Ops, M->getMemoryVT(),
9038                                                           M->getMemOperand());
9039     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9040                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9041   }
9042   return SDValue();
9043 }
9044 
9045 SDValue SITargetLowering::performClassCombine(SDNode *N,
9046                                               DAGCombinerInfo &DCI) const {
9047   SelectionDAG &DAG = DCI.DAG;
9048   SDValue Mask = N->getOperand(1);
9049 
9050   // fp_class x, 0 -> false
9051   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9052     if (CMask->isNullValue())
9053       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9054   }
9055 
9056   if (N->getOperand(0).isUndef())
9057     return DAG.getUNDEF(MVT::i1);
9058 
9059   return SDValue();
9060 }
9061 
9062 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9063                                             DAGCombinerInfo &DCI) const {
9064   EVT VT = N->getValueType(0);
9065   SDValue N0 = N->getOperand(0);
9066 
9067   if (N0.isUndef())
9068     return N0;
9069 
9070   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9071                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9072     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9073                            N->getFlags());
9074   }
9075 
9076   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9077     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9078                            N0.getOperand(0), N->getFlags());
9079   }
9080 
9081   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9082 }
9083 
9084 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9085                                        unsigned MaxDepth) const {
9086   unsigned Opcode = Op.getOpcode();
9087   if (Opcode == ISD::FCANONICALIZE)
9088     return true;
9089 
9090   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9091     auto F = CFP->getValueAPF();
9092     if (F.isNaN() && F.isSignaling())
9093       return false;
9094     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9095   }
9096 
9097   // If source is a result of another standard FP operation it is already in
9098   // canonical form.
9099   if (MaxDepth == 0)
9100     return false;
9101 
9102   switch (Opcode) {
9103   // These will flush denorms if required.
9104   case ISD::FADD:
9105   case ISD::FSUB:
9106   case ISD::FMUL:
9107   case ISD::FCEIL:
9108   case ISD::FFLOOR:
9109   case ISD::FMA:
9110   case ISD::FMAD:
9111   case ISD::FSQRT:
9112   case ISD::FDIV:
9113   case ISD::FREM:
9114   case ISD::FP_ROUND:
9115   case ISD::FP_EXTEND:
9116   case AMDGPUISD::FMUL_LEGACY:
9117   case AMDGPUISD::FMAD_FTZ:
9118   case AMDGPUISD::RCP:
9119   case AMDGPUISD::RSQ:
9120   case AMDGPUISD::RSQ_CLAMP:
9121   case AMDGPUISD::RCP_LEGACY:
9122   case AMDGPUISD::RCP_IFLAG:
9123   case AMDGPUISD::TRIG_PREOP:
9124   case AMDGPUISD::DIV_SCALE:
9125   case AMDGPUISD::DIV_FMAS:
9126   case AMDGPUISD::DIV_FIXUP:
9127   case AMDGPUISD::FRACT:
9128   case AMDGPUISD::LDEXP:
9129   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9130   case AMDGPUISD::CVT_F32_UBYTE0:
9131   case AMDGPUISD::CVT_F32_UBYTE1:
9132   case AMDGPUISD::CVT_F32_UBYTE2:
9133   case AMDGPUISD::CVT_F32_UBYTE3:
9134     return true;
9135 
9136   // It can/will be lowered or combined as a bit operation.
9137   // Need to check their input recursively to handle.
9138   case ISD::FNEG:
9139   case ISD::FABS:
9140   case ISD::FCOPYSIGN:
9141     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9142 
9143   case ISD::FSIN:
9144   case ISD::FCOS:
9145   case ISD::FSINCOS:
9146     return Op.getValueType().getScalarType() != MVT::f16;
9147 
9148   case ISD::FMINNUM:
9149   case ISD::FMAXNUM:
9150   case ISD::FMINNUM_IEEE:
9151   case ISD::FMAXNUM_IEEE:
9152   case AMDGPUISD::CLAMP:
9153   case AMDGPUISD::FMED3:
9154   case AMDGPUISD::FMAX3:
9155   case AMDGPUISD::FMIN3: {
9156     // FIXME: Shouldn't treat the generic operations different based these.
9157     // However, we aren't really required to flush the result from
9158     // minnum/maxnum..
9159 
9160     // snans will be quieted, so we only need to worry about denormals.
9161     if (Subtarget->supportsMinMaxDenormModes() ||
9162         denormalsEnabledForType(DAG, Op.getValueType()))
9163       return true;
9164 
9165     // Flushing may be required.
9166     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9167     // targets need to check their input recursively.
9168 
9169     // FIXME: Does this apply with clamp? It's implemented with max.
9170     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9171       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9172         return false;
9173     }
9174 
9175     return true;
9176   }
9177   case ISD::SELECT: {
9178     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9179            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9180   }
9181   case ISD::BUILD_VECTOR: {
9182     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9183       SDValue SrcOp = Op.getOperand(i);
9184       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9185         return false;
9186     }
9187 
9188     return true;
9189   }
9190   case ISD::EXTRACT_VECTOR_ELT:
9191   case ISD::EXTRACT_SUBVECTOR: {
9192     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9193   }
9194   case ISD::INSERT_VECTOR_ELT: {
9195     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9196            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9197   }
9198   case ISD::UNDEF:
9199     // Could be anything.
9200     return false;
9201 
9202   case ISD::BITCAST: {
9203     // Hack round the mess we make when legalizing extract_vector_elt
9204     SDValue Src = Op.getOperand(0);
9205     if (Src.getValueType() == MVT::i16 &&
9206         Src.getOpcode() == ISD::TRUNCATE) {
9207       SDValue TruncSrc = Src.getOperand(0);
9208       if (TruncSrc.getValueType() == MVT::i32 &&
9209           TruncSrc.getOpcode() == ISD::BITCAST &&
9210           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9211         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9212       }
9213     }
9214 
9215     return false;
9216   }
9217   case ISD::INTRINSIC_WO_CHAIN: {
9218     unsigned IntrinsicID
9219       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9220     // TODO: Handle more intrinsics
9221     switch (IntrinsicID) {
9222     case Intrinsic::amdgcn_cvt_pkrtz:
9223     case Intrinsic::amdgcn_cubeid:
9224     case Intrinsic::amdgcn_frexp_mant:
9225     case Intrinsic::amdgcn_fdot2:
9226     case Intrinsic::amdgcn_rcp:
9227     case Intrinsic::amdgcn_rsq:
9228     case Intrinsic::amdgcn_rsq_clamp:
9229     case Intrinsic::amdgcn_rcp_legacy:
9230     case Intrinsic::amdgcn_rsq_legacy:
9231       return true;
9232     default:
9233       break;
9234     }
9235 
9236     LLVM_FALLTHROUGH;
9237   }
9238   default:
9239     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9240            DAG.isKnownNeverSNaN(Op);
9241   }
9242 
9243   llvm_unreachable("invalid operation");
9244 }
9245 
9246 // Constant fold canonicalize.
9247 SDValue SITargetLowering::getCanonicalConstantFP(
9248   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9249   // Flush denormals to 0 if not enabled.
9250   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9251     return DAG.getConstantFP(0.0, SL, VT);
9252 
9253   if (C.isNaN()) {
9254     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9255     if (C.isSignaling()) {
9256       // Quiet a signaling NaN.
9257       // FIXME: Is this supposed to preserve payload bits?
9258       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9259     }
9260 
9261     // Make sure it is the canonical NaN bitpattern.
9262     //
9263     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9264     // immediate?
9265     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9266       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9267   }
9268 
9269   // Already canonical.
9270   return DAG.getConstantFP(C, SL, VT);
9271 }
9272 
9273 static bool vectorEltWillFoldAway(SDValue Op) {
9274   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9275 }
9276 
9277 SDValue SITargetLowering::performFCanonicalizeCombine(
9278   SDNode *N,
9279   DAGCombinerInfo &DCI) const {
9280   SelectionDAG &DAG = DCI.DAG;
9281   SDValue N0 = N->getOperand(0);
9282   EVT VT = N->getValueType(0);
9283 
9284   // fcanonicalize undef -> qnan
9285   if (N0.isUndef()) {
9286     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9287     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9288   }
9289 
9290   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9291     EVT VT = N->getValueType(0);
9292     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9293   }
9294 
9295   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9296   //                                                   (fcanonicalize k)
9297   //
9298   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9299 
9300   // TODO: This could be better with wider vectors that will be split to v2f16,
9301   // and to consider uses since there aren't that many packed operations.
9302   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9303       isTypeLegal(MVT::v2f16)) {
9304     SDLoc SL(N);
9305     SDValue NewElts[2];
9306     SDValue Lo = N0.getOperand(0);
9307     SDValue Hi = N0.getOperand(1);
9308     EVT EltVT = Lo.getValueType();
9309 
9310     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9311       for (unsigned I = 0; I != 2; ++I) {
9312         SDValue Op = N0.getOperand(I);
9313         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9314           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9315                                               CFP->getValueAPF());
9316         } else if (Op.isUndef()) {
9317           // Handled below based on what the other operand is.
9318           NewElts[I] = Op;
9319         } else {
9320           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9321         }
9322       }
9323 
9324       // If one half is undef, and one is constant, perfer a splat vector rather
9325       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9326       // cheaper to use and may be free with a packed operation.
9327       if (NewElts[0].isUndef()) {
9328         if (isa<ConstantFPSDNode>(NewElts[1]))
9329           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9330             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9331       }
9332 
9333       if (NewElts[1].isUndef()) {
9334         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9335           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9336       }
9337 
9338       return DAG.getBuildVector(VT, SL, NewElts);
9339     }
9340   }
9341 
9342   unsigned SrcOpc = N0.getOpcode();
9343 
9344   // If it's free to do so, push canonicalizes further up the source, which may
9345   // find a canonical source.
9346   //
9347   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9348   // sNaNs.
9349   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9350     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9351     if (CRHS && N0.hasOneUse()) {
9352       SDLoc SL(N);
9353       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9354                                    N0.getOperand(0));
9355       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9356       DCI.AddToWorklist(Canon0.getNode());
9357 
9358       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9359     }
9360   }
9361 
9362   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9363 }
9364 
9365 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9366   switch (Opc) {
9367   case ISD::FMAXNUM:
9368   case ISD::FMAXNUM_IEEE:
9369     return AMDGPUISD::FMAX3;
9370   case ISD::SMAX:
9371     return AMDGPUISD::SMAX3;
9372   case ISD::UMAX:
9373     return AMDGPUISD::UMAX3;
9374   case ISD::FMINNUM:
9375   case ISD::FMINNUM_IEEE:
9376     return AMDGPUISD::FMIN3;
9377   case ISD::SMIN:
9378     return AMDGPUISD::SMIN3;
9379   case ISD::UMIN:
9380     return AMDGPUISD::UMIN3;
9381   default:
9382     llvm_unreachable("Not a min/max opcode");
9383   }
9384 }
9385 
9386 SDValue SITargetLowering::performIntMed3ImmCombine(
9387   SelectionDAG &DAG, const SDLoc &SL,
9388   SDValue Op0, SDValue Op1, bool Signed) const {
9389   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9390   if (!K1)
9391     return SDValue();
9392 
9393   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9394   if (!K0)
9395     return SDValue();
9396 
9397   if (Signed) {
9398     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9399       return SDValue();
9400   } else {
9401     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9402       return SDValue();
9403   }
9404 
9405   EVT VT = K0->getValueType(0);
9406   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9407   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9408     return DAG.getNode(Med3Opc, SL, VT,
9409                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9410   }
9411 
9412   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9413   MVT NVT = MVT::i32;
9414   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9415 
9416   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9417   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9418   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9419 
9420   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9421   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9422 }
9423 
9424 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9425   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9426     return C;
9427 
9428   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9429     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9430       return C;
9431   }
9432 
9433   return nullptr;
9434 }
9435 
9436 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9437                                                   const SDLoc &SL,
9438                                                   SDValue Op0,
9439                                                   SDValue Op1) const {
9440   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9441   if (!K1)
9442     return SDValue();
9443 
9444   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9445   if (!K0)
9446     return SDValue();
9447 
9448   // Ordered >= (although NaN inputs should have folded away by now).
9449   if (K0->getValueAPF() > K1->getValueAPF())
9450     return SDValue();
9451 
9452   const MachineFunction &MF = DAG.getMachineFunction();
9453   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9454 
9455   // TODO: Check IEEE bit enabled?
9456   EVT VT = Op0.getValueType();
9457   if (Info->getMode().DX10Clamp) {
9458     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9459     // hardware fmed3 behavior converting to a min.
9460     // FIXME: Should this be allowing -0.0?
9461     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9462       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9463   }
9464 
9465   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9466   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9467     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9468     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9469     // then give the other result, which is different from med3 with a NaN
9470     // input.
9471     SDValue Var = Op0.getOperand(0);
9472     if (!DAG.isKnownNeverSNaN(Var))
9473       return SDValue();
9474 
9475     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9476 
9477     if ((!K0->hasOneUse() ||
9478          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9479         (!K1->hasOneUse() ||
9480          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9481       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9482                          Var, SDValue(K0, 0), SDValue(K1, 0));
9483     }
9484   }
9485 
9486   return SDValue();
9487 }
9488 
9489 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9490                                                DAGCombinerInfo &DCI) const {
9491   SelectionDAG &DAG = DCI.DAG;
9492 
9493   EVT VT = N->getValueType(0);
9494   unsigned Opc = N->getOpcode();
9495   SDValue Op0 = N->getOperand(0);
9496   SDValue Op1 = N->getOperand(1);
9497 
9498   // Only do this if the inner op has one use since this will just increases
9499   // register pressure for no benefit.
9500 
9501   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9502       !VT.isVector() &&
9503       (VT == MVT::i32 || VT == MVT::f32 ||
9504        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9505     // max(max(a, b), c) -> max3(a, b, c)
9506     // min(min(a, b), c) -> min3(a, b, c)
9507     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9508       SDLoc DL(N);
9509       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9510                          DL,
9511                          N->getValueType(0),
9512                          Op0.getOperand(0),
9513                          Op0.getOperand(1),
9514                          Op1);
9515     }
9516 
9517     // Try commuted.
9518     // max(a, max(b, c)) -> max3(a, b, c)
9519     // min(a, min(b, c)) -> min3(a, b, c)
9520     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9521       SDLoc DL(N);
9522       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9523                          DL,
9524                          N->getValueType(0),
9525                          Op0,
9526                          Op1.getOperand(0),
9527                          Op1.getOperand(1));
9528     }
9529   }
9530 
9531   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9532   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9533     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9534       return Med3;
9535   }
9536 
9537   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9538     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9539       return Med3;
9540   }
9541 
9542   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9543   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9544        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9545        (Opc == AMDGPUISD::FMIN_LEGACY &&
9546         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9547       (VT == MVT::f32 || VT == MVT::f64 ||
9548        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9549        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9550       Op0.hasOneUse()) {
9551     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9552       return Res;
9553   }
9554 
9555   return SDValue();
9556 }
9557 
9558 static bool isClampZeroToOne(SDValue A, SDValue B) {
9559   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9560     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9561       // FIXME: Should this be allowing -0.0?
9562       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9563              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9564     }
9565   }
9566 
9567   return false;
9568 }
9569 
9570 // FIXME: Should only worry about snans for version with chain.
9571 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9572                                               DAGCombinerInfo &DCI) const {
9573   EVT VT = N->getValueType(0);
9574   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9575   // NaNs. With a NaN input, the order of the operands may change the result.
9576 
9577   SelectionDAG &DAG = DCI.DAG;
9578   SDLoc SL(N);
9579 
9580   SDValue Src0 = N->getOperand(0);
9581   SDValue Src1 = N->getOperand(1);
9582   SDValue Src2 = N->getOperand(2);
9583 
9584   if (isClampZeroToOne(Src0, Src1)) {
9585     // const_a, const_b, x -> clamp is safe in all cases including signaling
9586     // nans.
9587     // FIXME: Should this be allowing -0.0?
9588     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9589   }
9590 
9591   const MachineFunction &MF = DAG.getMachineFunction();
9592   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9593 
9594   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9595   // handling no dx10-clamp?
9596   if (Info->getMode().DX10Clamp) {
9597     // If NaNs is clamped to 0, we are free to reorder the inputs.
9598 
9599     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9600       std::swap(Src0, Src1);
9601 
9602     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9603       std::swap(Src1, Src2);
9604 
9605     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9606       std::swap(Src0, Src1);
9607 
9608     if (isClampZeroToOne(Src1, Src2))
9609       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9610   }
9611 
9612   return SDValue();
9613 }
9614 
9615 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9616                                                  DAGCombinerInfo &DCI) const {
9617   SDValue Src0 = N->getOperand(0);
9618   SDValue Src1 = N->getOperand(1);
9619   if (Src0.isUndef() && Src1.isUndef())
9620     return DCI.DAG.getUNDEF(N->getValueType(0));
9621   return SDValue();
9622 }
9623 
9624 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9625 // expanded into a set of cmp/select instructions.
9626 static bool shouldExpandVectorDynExt(SDNode *N) {
9627   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9628   if (UseDivergentRegisterIndexing || isa<ConstantSDNode>(Idx))
9629     return false;
9630 
9631   SDValue Vec = N->getOperand(0);
9632   EVT VecVT = Vec.getValueType();
9633   EVT EltVT = VecVT.getVectorElementType();
9634   unsigned VecSize = VecVT.getSizeInBits();
9635   unsigned EltSize = EltVT.getSizeInBits();
9636   unsigned NumElem = VecVT.getVectorNumElements();
9637 
9638   // Sub-dword vectors of size 2 dword or less have better implementation.
9639   if (VecSize <= 64 && EltSize < 32)
9640     return false;
9641 
9642   // Always expand the rest of sub-dword instructions, otherwise it will be
9643   // lowered via memory.
9644   if (EltSize < 32)
9645     return true;
9646 
9647   // Always do this if var-idx is divergent, otherwise it will become a loop.
9648   if (Idx->isDivergent())
9649     return true;
9650 
9651   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9652   unsigned NumInsts = NumElem /* Number of compares */ +
9653                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9654   return NumInsts <= 16;
9655 }
9656 
9657 SDValue SITargetLowering::performExtractVectorEltCombine(
9658   SDNode *N, DAGCombinerInfo &DCI) const {
9659   SDValue Vec = N->getOperand(0);
9660   SelectionDAG &DAG = DCI.DAG;
9661 
9662   EVT VecVT = Vec.getValueType();
9663   EVT EltVT = VecVT.getVectorElementType();
9664 
9665   if ((Vec.getOpcode() == ISD::FNEG ||
9666        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9667     SDLoc SL(N);
9668     EVT EltVT = N->getValueType(0);
9669     SDValue Idx = N->getOperand(1);
9670     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9671                               Vec.getOperand(0), Idx);
9672     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9673   }
9674 
9675   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9676   //    =>
9677   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9678   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9679   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9680   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9681     SDLoc SL(N);
9682     EVT EltVT = N->getValueType(0);
9683     SDValue Idx = N->getOperand(1);
9684     unsigned Opc = Vec.getOpcode();
9685 
9686     switch(Opc) {
9687     default:
9688       break;
9689       // TODO: Support other binary operations.
9690     case ISD::FADD:
9691     case ISD::FSUB:
9692     case ISD::FMUL:
9693     case ISD::ADD:
9694     case ISD::UMIN:
9695     case ISD::UMAX:
9696     case ISD::SMIN:
9697     case ISD::SMAX:
9698     case ISD::FMAXNUM:
9699     case ISD::FMINNUM:
9700     case ISD::FMAXNUM_IEEE:
9701     case ISD::FMINNUM_IEEE: {
9702       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9703                                  Vec.getOperand(0), Idx);
9704       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9705                                  Vec.getOperand(1), Idx);
9706 
9707       DCI.AddToWorklist(Elt0.getNode());
9708       DCI.AddToWorklist(Elt1.getNode());
9709       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9710     }
9711     }
9712   }
9713 
9714   unsigned VecSize = VecVT.getSizeInBits();
9715   unsigned EltSize = EltVT.getSizeInBits();
9716 
9717   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9718   if (shouldExpandVectorDynExt(N)) {
9719     SDLoc SL(N);
9720     SDValue Idx = N->getOperand(1);
9721     SDValue V;
9722     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9723       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9724       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9725       if (I == 0)
9726         V = Elt;
9727       else
9728         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9729     }
9730     return V;
9731   }
9732 
9733   if (!DCI.isBeforeLegalize())
9734     return SDValue();
9735 
9736   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9737   // elements. This exposes more load reduction opportunities by replacing
9738   // multiple small extract_vector_elements with a single 32-bit extract.
9739   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9740   if (isa<MemSDNode>(Vec) &&
9741       EltSize <= 16 &&
9742       EltVT.isByteSized() &&
9743       VecSize > 32 &&
9744       VecSize % 32 == 0 &&
9745       Idx) {
9746     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9747 
9748     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9749     unsigned EltIdx = BitIndex / 32;
9750     unsigned LeftoverBitIdx = BitIndex % 32;
9751     SDLoc SL(N);
9752 
9753     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9754     DCI.AddToWorklist(Cast.getNode());
9755 
9756     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9757                               DAG.getConstant(EltIdx, SL, MVT::i32));
9758     DCI.AddToWorklist(Elt.getNode());
9759     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9760                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9761     DCI.AddToWorklist(Srl.getNode());
9762 
9763     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9764     DCI.AddToWorklist(Trunc.getNode());
9765     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9766   }
9767 
9768   return SDValue();
9769 }
9770 
9771 SDValue
9772 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9773                                                 DAGCombinerInfo &DCI) const {
9774   SDValue Vec = N->getOperand(0);
9775   SDValue Idx = N->getOperand(2);
9776   EVT VecVT = Vec.getValueType();
9777   EVT EltVT = VecVT.getVectorElementType();
9778 
9779   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9780   // => BUILD_VECTOR n x select (e, const-idx)
9781   if (!shouldExpandVectorDynExt(N))
9782     return SDValue();
9783 
9784   SelectionDAG &DAG = DCI.DAG;
9785   SDLoc SL(N);
9786   SDValue Ins = N->getOperand(1);
9787   EVT IdxVT = Idx.getValueType();
9788 
9789   SmallVector<SDValue, 16> Ops;
9790   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9791     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9792     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9793     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9794     Ops.push_back(V);
9795   }
9796 
9797   return DAG.getBuildVector(VecVT, SL, Ops);
9798 }
9799 
9800 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9801                                           const SDNode *N0,
9802                                           const SDNode *N1) const {
9803   EVT VT = N0->getValueType(0);
9804 
9805   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9806   // support denormals ever.
9807   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9808        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9809         getSubtarget()->hasMadF16())) &&
9810        isOperationLegal(ISD::FMAD, VT))
9811     return ISD::FMAD;
9812 
9813   const TargetOptions &Options = DAG.getTarget().Options;
9814   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9815        (N0->getFlags().hasAllowContract() &&
9816         N1->getFlags().hasAllowContract())) &&
9817       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9818     return ISD::FMA;
9819   }
9820 
9821   return 0;
9822 }
9823 
9824 // For a reassociatable opcode perform:
9825 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9826 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9827                                                SelectionDAG &DAG) const {
9828   EVT VT = N->getValueType(0);
9829   if (VT != MVT::i32 && VT != MVT::i64)
9830     return SDValue();
9831 
9832   unsigned Opc = N->getOpcode();
9833   SDValue Op0 = N->getOperand(0);
9834   SDValue Op1 = N->getOperand(1);
9835 
9836   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9837     return SDValue();
9838 
9839   if (Op0->isDivergent())
9840     std::swap(Op0, Op1);
9841 
9842   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9843     return SDValue();
9844 
9845   SDValue Op2 = Op1.getOperand(1);
9846   Op1 = Op1.getOperand(0);
9847   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9848     return SDValue();
9849 
9850   if (Op1->isDivergent())
9851     std::swap(Op1, Op2);
9852 
9853   // If either operand is constant this will conflict with
9854   // DAGCombiner::ReassociateOps().
9855   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9856       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9857     return SDValue();
9858 
9859   SDLoc SL(N);
9860   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9861   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9862 }
9863 
9864 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9865                            EVT VT,
9866                            SDValue N0, SDValue N1, SDValue N2,
9867                            bool Signed) {
9868   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9869   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9870   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9871   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9872 }
9873 
9874 SDValue SITargetLowering::performAddCombine(SDNode *N,
9875                                             DAGCombinerInfo &DCI) const {
9876   SelectionDAG &DAG = DCI.DAG;
9877   EVT VT = N->getValueType(0);
9878   SDLoc SL(N);
9879   SDValue LHS = N->getOperand(0);
9880   SDValue RHS = N->getOperand(1);
9881 
9882   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9883       && Subtarget->hasMad64_32() &&
9884       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9885       VT.getScalarSizeInBits() <= 64) {
9886     if (LHS.getOpcode() != ISD::MUL)
9887       std::swap(LHS, RHS);
9888 
9889     SDValue MulLHS = LHS.getOperand(0);
9890     SDValue MulRHS = LHS.getOperand(1);
9891     SDValue AddRHS = RHS;
9892 
9893     // TODO: Maybe restrict if SGPR inputs.
9894     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9895         numBitsUnsigned(MulRHS, DAG) <= 32) {
9896       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9897       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9898       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9899       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9900     }
9901 
9902     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9903       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9904       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9905       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9906       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9907     }
9908 
9909     return SDValue();
9910   }
9911 
9912   if (SDValue V = reassociateScalarOps(N, DAG)) {
9913     return V;
9914   }
9915 
9916   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9917     return SDValue();
9918 
9919   // add x, zext (setcc) => addcarry x, 0, setcc
9920   // add x, sext (setcc) => subcarry x, 0, setcc
9921   unsigned Opc = LHS.getOpcode();
9922   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9923       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9924     std::swap(RHS, LHS);
9925 
9926   Opc = RHS.getOpcode();
9927   switch (Opc) {
9928   default: break;
9929   case ISD::ZERO_EXTEND:
9930   case ISD::SIGN_EXTEND:
9931   case ISD::ANY_EXTEND: {
9932     auto Cond = RHS.getOperand(0);
9933     // If this won't be a real VOPC output, we would still need to insert an
9934     // extra instruction anyway.
9935     if (!isBoolSGPR(Cond))
9936       break;
9937     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9938     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9939     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9940     return DAG.getNode(Opc, SL, VTList, Args);
9941   }
9942   case ISD::ADDCARRY: {
9943     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9944     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9945     if (!C || C->getZExtValue() != 0) break;
9946     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9947     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9948   }
9949   }
9950   return SDValue();
9951 }
9952 
9953 SDValue SITargetLowering::performSubCombine(SDNode *N,
9954                                             DAGCombinerInfo &DCI) const {
9955   SelectionDAG &DAG = DCI.DAG;
9956   EVT VT = N->getValueType(0);
9957 
9958   if (VT != MVT::i32)
9959     return SDValue();
9960 
9961   SDLoc SL(N);
9962   SDValue LHS = N->getOperand(0);
9963   SDValue RHS = N->getOperand(1);
9964 
9965   // sub x, zext (setcc) => subcarry x, 0, setcc
9966   // sub x, sext (setcc) => addcarry x, 0, setcc
9967   unsigned Opc = RHS.getOpcode();
9968   switch (Opc) {
9969   default: break;
9970   case ISD::ZERO_EXTEND:
9971   case ISD::SIGN_EXTEND:
9972   case ISD::ANY_EXTEND: {
9973     auto Cond = RHS.getOperand(0);
9974     // If this won't be a real VOPC output, we would still need to insert an
9975     // extra instruction anyway.
9976     if (!isBoolSGPR(Cond))
9977       break;
9978     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9979     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9980     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9981     return DAG.getNode(Opc, SL, VTList, Args);
9982   }
9983   }
9984 
9985   if (LHS.getOpcode() == ISD::SUBCARRY) {
9986     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9987     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9988     if (!C || !C->isNullValue())
9989       return SDValue();
9990     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9991     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9992   }
9993   return SDValue();
9994 }
9995 
9996 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9997   DAGCombinerInfo &DCI) const {
9998 
9999   if (N->getValueType(0) != MVT::i32)
10000     return SDValue();
10001 
10002   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10003   if (!C || C->getZExtValue() != 0)
10004     return SDValue();
10005 
10006   SelectionDAG &DAG = DCI.DAG;
10007   SDValue LHS = N->getOperand(0);
10008 
10009   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10010   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10011   unsigned LHSOpc = LHS.getOpcode();
10012   unsigned Opc = N->getOpcode();
10013   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10014       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10015     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10016     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10017   }
10018   return SDValue();
10019 }
10020 
10021 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10022                                              DAGCombinerInfo &DCI) const {
10023   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10024     return SDValue();
10025 
10026   SelectionDAG &DAG = DCI.DAG;
10027   EVT VT = N->getValueType(0);
10028 
10029   SDLoc SL(N);
10030   SDValue LHS = N->getOperand(0);
10031   SDValue RHS = N->getOperand(1);
10032 
10033   // These should really be instruction patterns, but writing patterns with
10034   // source modiifiers is a pain.
10035 
10036   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10037   if (LHS.getOpcode() == ISD::FADD) {
10038     SDValue A = LHS.getOperand(0);
10039     if (A == LHS.getOperand(1)) {
10040       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10041       if (FusedOp != 0) {
10042         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10043         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10044       }
10045     }
10046   }
10047 
10048   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10049   if (RHS.getOpcode() == ISD::FADD) {
10050     SDValue A = RHS.getOperand(0);
10051     if (A == RHS.getOperand(1)) {
10052       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10053       if (FusedOp != 0) {
10054         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10055         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10056       }
10057     }
10058   }
10059 
10060   return SDValue();
10061 }
10062 
10063 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10064                                              DAGCombinerInfo &DCI) const {
10065   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10066     return SDValue();
10067 
10068   SelectionDAG &DAG = DCI.DAG;
10069   SDLoc SL(N);
10070   EVT VT = N->getValueType(0);
10071   assert(!VT.isVector());
10072 
10073   // Try to get the fneg to fold into the source modifier. This undoes generic
10074   // DAG combines and folds them into the mad.
10075   //
10076   // Only do this if we are not trying to support denormals. v_mad_f32 does
10077   // not support denormals ever.
10078   SDValue LHS = N->getOperand(0);
10079   SDValue RHS = N->getOperand(1);
10080   if (LHS.getOpcode() == ISD::FADD) {
10081     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10082     SDValue A = LHS.getOperand(0);
10083     if (A == LHS.getOperand(1)) {
10084       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10085       if (FusedOp != 0){
10086         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10087         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10088 
10089         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10090       }
10091     }
10092   }
10093 
10094   if (RHS.getOpcode() == ISD::FADD) {
10095     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10096 
10097     SDValue A = RHS.getOperand(0);
10098     if (A == RHS.getOperand(1)) {
10099       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10100       if (FusedOp != 0){
10101         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10102         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10103       }
10104     }
10105   }
10106 
10107   return SDValue();
10108 }
10109 
10110 SDValue SITargetLowering::performFMACombine(SDNode *N,
10111                                             DAGCombinerInfo &DCI) const {
10112   SelectionDAG &DAG = DCI.DAG;
10113   EVT VT = N->getValueType(0);
10114   SDLoc SL(N);
10115 
10116   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10117     return SDValue();
10118 
10119   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10120   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10121   SDValue Op1 = N->getOperand(0);
10122   SDValue Op2 = N->getOperand(1);
10123   SDValue FMA = N->getOperand(2);
10124 
10125   if (FMA.getOpcode() != ISD::FMA ||
10126       Op1.getOpcode() != ISD::FP_EXTEND ||
10127       Op2.getOpcode() != ISD::FP_EXTEND)
10128     return SDValue();
10129 
10130   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10131   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10132   // is sufficient to allow generaing fdot2.
10133   const TargetOptions &Options = DAG.getTarget().Options;
10134   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10135       (N->getFlags().hasAllowContract() &&
10136        FMA->getFlags().hasAllowContract())) {
10137     Op1 = Op1.getOperand(0);
10138     Op2 = Op2.getOperand(0);
10139     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10140         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10141       return SDValue();
10142 
10143     SDValue Vec1 = Op1.getOperand(0);
10144     SDValue Idx1 = Op1.getOperand(1);
10145     SDValue Vec2 = Op2.getOperand(0);
10146 
10147     SDValue FMAOp1 = FMA.getOperand(0);
10148     SDValue FMAOp2 = FMA.getOperand(1);
10149     SDValue FMAAcc = FMA.getOperand(2);
10150 
10151     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10152         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10153       return SDValue();
10154 
10155     FMAOp1 = FMAOp1.getOperand(0);
10156     FMAOp2 = FMAOp2.getOperand(0);
10157     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10158         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10159       return SDValue();
10160 
10161     SDValue Vec3 = FMAOp1.getOperand(0);
10162     SDValue Vec4 = FMAOp2.getOperand(0);
10163     SDValue Idx2 = FMAOp1.getOperand(1);
10164 
10165     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10166         // Idx1 and Idx2 cannot be the same.
10167         Idx1 == Idx2)
10168       return SDValue();
10169 
10170     if (Vec1 == Vec2 || Vec3 == Vec4)
10171       return SDValue();
10172 
10173     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10174       return SDValue();
10175 
10176     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10177         (Vec1 == Vec4 && Vec2 == Vec3)) {
10178       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10179                          DAG.getTargetConstant(0, SL, MVT::i1));
10180     }
10181   }
10182   return SDValue();
10183 }
10184 
10185 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10186                                               DAGCombinerInfo &DCI) const {
10187   SelectionDAG &DAG = DCI.DAG;
10188   SDLoc SL(N);
10189 
10190   SDValue LHS = N->getOperand(0);
10191   SDValue RHS = N->getOperand(1);
10192   EVT VT = LHS.getValueType();
10193   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10194 
10195   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10196   if (!CRHS) {
10197     CRHS = dyn_cast<ConstantSDNode>(LHS);
10198     if (CRHS) {
10199       std::swap(LHS, RHS);
10200       CC = getSetCCSwappedOperands(CC);
10201     }
10202   }
10203 
10204   if (CRHS) {
10205     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10206         isBoolSGPR(LHS.getOperand(0))) {
10207       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10208       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10209       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10210       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10211       if ((CRHS->isAllOnesValue() &&
10212            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10213           (CRHS->isNullValue() &&
10214            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10215         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10216                            DAG.getConstant(-1, SL, MVT::i1));
10217       if ((CRHS->isAllOnesValue() &&
10218            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10219           (CRHS->isNullValue() &&
10220            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10221         return LHS.getOperand(0);
10222     }
10223 
10224     uint64_t CRHSVal = CRHS->getZExtValue();
10225     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10226         LHS.getOpcode() == ISD::SELECT &&
10227         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10228         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10229         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10230         isBoolSGPR(LHS.getOperand(0))) {
10231       // Given CT != FT:
10232       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10233       // setcc (select cc, CT, CF), CF, ne => cc
10234       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10235       // setcc (select cc, CT, CF), CT, eq => cc
10236       uint64_t CT = LHS.getConstantOperandVal(1);
10237       uint64_t CF = LHS.getConstantOperandVal(2);
10238 
10239       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10240           (CT == CRHSVal && CC == ISD::SETNE))
10241         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10242                            DAG.getConstant(-1, SL, MVT::i1));
10243       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10244           (CT == CRHSVal && CC == ISD::SETEQ))
10245         return LHS.getOperand(0);
10246     }
10247   }
10248 
10249   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10250                                            VT != MVT::f16))
10251     return SDValue();
10252 
10253   // Match isinf/isfinite pattern
10254   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10255   // (fcmp one (fabs x), inf) -> (fp_class x,
10256   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10257   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10258     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10259     if (!CRHS)
10260       return SDValue();
10261 
10262     const APFloat &APF = CRHS->getValueAPF();
10263     if (APF.isInfinity() && !APF.isNegative()) {
10264       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10265                                  SIInstrFlags::N_INFINITY;
10266       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10267                                     SIInstrFlags::P_ZERO |
10268                                     SIInstrFlags::N_NORMAL |
10269                                     SIInstrFlags::P_NORMAL |
10270                                     SIInstrFlags::N_SUBNORMAL |
10271                                     SIInstrFlags::P_SUBNORMAL;
10272       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10273       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10274                          DAG.getConstant(Mask, SL, MVT::i32));
10275     }
10276   }
10277 
10278   return SDValue();
10279 }
10280 
10281 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10282                                                      DAGCombinerInfo &DCI) const {
10283   SelectionDAG &DAG = DCI.DAG;
10284   SDLoc SL(N);
10285   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10286 
10287   SDValue Src = N->getOperand(0);
10288   SDValue Shift = N->getOperand(0);
10289 
10290   // TODO: Extend type shouldn't matter (assuming legal types).
10291   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10292     Shift = Shift.getOperand(0);
10293 
10294   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10295     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10296     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10297     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10298     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10299     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10300     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10301       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10302                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10303 
10304       unsigned ShiftOffset = 8 * Offset;
10305       if (Shift.getOpcode() == ISD::SHL)
10306         ShiftOffset -= C->getZExtValue();
10307       else
10308         ShiftOffset += C->getZExtValue();
10309 
10310       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10311         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10312                            MVT::f32, Shift);
10313       }
10314     }
10315   }
10316 
10317   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10318   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10319   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10320     // We simplified Src. If this node is not dead, visit it again so it is
10321     // folded properly.
10322     if (N->getOpcode() != ISD::DELETED_NODE)
10323       DCI.AddToWorklist(N);
10324     return SDValue(N, 0);
10325   }
10326 
10327   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10328   if (SDValue DemandedSrc =
10329           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10330     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10331 
10332   return SDValue();
10333 }
10334 
10335 SDValue SITargetLowering::performClampCombine(SDNode *N,
10336                                               DAGCombinerInfo &DCI) const {
10337   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10338   if (!CSrc)
10339     return SDValue();
10340 
10341   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10342   const APFloat &F = CSrc->getValueAPF();
10343   APFloat Zero = APFloat::getZero(F.getSemantics());
10344   if (F < Zero ||
10345       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10346     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10347   }
10348 
10349   APFloat One(F.getSemantics(), "1.0");
10350   if (F > One)
10351     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10352 
10353   return SDValue(CSrc, 0);
10354 }
10355 
10356 
10357 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10358                                             DAGCombinerInfo &DCI) const {
10359   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10360     return SDValue();
10361   switch (N->getOpcode()) {
10362   default:
10363     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10364   case ISD::ADD:
10365     return performAddCombine(N, DCI);
10366   case ISD::SUB:
10367     return performSubCombine(N, DCI);
10368   case ISD::ADDCARRY:
10369   case ISD::SUBCARRY:
10370     return performAddCarrySubCarryCombine(N, DCI);
10371   case ISD::FADD:
10372     return performFAddCombine(N, DCI);
10373   case ISD::FSUB:
10374     return performFSubCombine(N, DCI);
10375   case ISD::SETCC:
10376     return performSetCCCombine(N, DCI);
10377   case ISD::FMAXNUM:
10378   case ISD::FMINNUM:
10379   case ISD::FMAXNUM_IEEE:
10380   case ISD::FMINNUM_IEEE:
10381   case ISD::SMAX:
10382   case ISD::SMIN:
10383   case ISD::UMAX:
10384   case ISD::UMIN:
10385   case AMDGPUISD::FMIN_LEGACY:
10386   case AMDGPUISD::FMAX_LEGACY:
10387     return performMinMaxCombine(N, DCI);
10388   case ISD::FMA:
10389     return performFMACombine(N, DCI);
10390   case ISD::LOAD: {
10391     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10392       return Widended;
10393     LLVM_FALLTHROUGH;
10394   }
10395   case ISD::STORE:
10396   case ISD::ATOMIC_LOAD:
10397   case ISD::ATOMIC_STORE:
10398   case ISD::ATOMIC_CMP_SWAP:
10399   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10400   case ISD::ATOMIC_SWAP:
10401   case ISD::ATOMIC_LOAD_ADD:
10402   case ISD::ATOMIC_LOAD_SUB:
10403   case ISD::ATOMIC_LOAD_AND:
10404   case ISD::ATOMIC_LOAD_OR:
10405   case ISD::ATOMIC_LOAD_XOR:
10406   case ISD::ATOMIC_LOAD_NAND:
10407   case ISD::ATOMIC_LOAD_MIN:
10408   case ISD::ATOMIC_LOAD_MAX:
10409   case ISD::ATOMIC_LOAD_UMIN:
10410   case ISD::ATOMIC_LOAD_UMAX:
10411   case ISD::ATOMIC_LOAD_FADD:
10412   case AMDGPUISD::ATOMIC_INC:
10413   case AMDGPUISD::ATOMIC_DEC:
10414   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10415   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10416     if (DCI.isBeforeLegalize())
10417       break;
10418     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10419   case ISD::AND:
10420     return performAndCombine(N, DCI);
10421   case ISD::OR:
10422     return performOrCombine(N, DCI);
10423   case ISD::XOR:
10424     return performXorCombine(N, DCI);
10425   case ISD::ZERO_EXTEND:
10426     return performZeroExtendCombine(N, DCI);
10427   case ISD::SIGN_EXTEND_INREG:
10428     return performSignExtendInRegCombine(N , DCI);
10429   case AMDGPUISD::FP_CLASS:
10430     return performClassCombine(N, DCI);
10431   case ISD::FCANONICALIZE:
10432     return performFCanonicalizeCombine(N, DCI);
10433   case AMDGPUISD::RCP:
10434     return performRcpCombine(N, DCI);
10435   case AMDGPUISD::FRACT:
10436   case AMDGPUISD::RSQ:
10437   case AMDGPUISD::RCP_LEGACY:
10438   case AMDGPUISD::RCP_IFLAG:
10439   case AMDGPUISD::RSQ_CLAMP:
10440   case AMDGPUISD::LDEXP: {
10441     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10442     SDValue Src = N->getOperand(0);
10443     if (Src.isUndef())
10444       return Src;
10445     break;
10446   }
10447   case ISD::SINT_TO_FP:
10448   case ISD::UINT_TO_FP:
10449     return performUCharToFloatCombine(N, DCI);
10450   case AMDGPUISD::CVT_F32_UBYTE0:
10451   case AMDGPUISD::CVT_F32_UBYTE1:
10452   case AMDGPUISD::CVT_F32_UBYTE2:
10453   case AMDGPUISD::CVT_F32_UBYTE3:
10454     return performCvtF32UByteNCombine(N, DCI);
10455   case AMDGPUISD::FMED3:
10456     return performFMed3Combine(N, DCI);
10457   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10458     return performCvtPkRTZCombine(N, DCI);
10459   case AMDGPUISD::CLAMP:
10460     return performClampCombine(N, DCI);
10461   case ISD::SCALAR_TO_VECTOR: {
10462     SelectionDAG &DAG = DCI.DAG;
10463     EVT VT = N->getValueType(0);
10464 
10465     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10466     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10467       SDLoc SL(N);
10468       SDValue Src = N->getOperand(0);
10469       EVT EltVT = Src.getValueType();
10470       if (EltVT == MVT::f16)
10471         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10472 
10473       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10474       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10475     }
10476 
10477     break;
10478   }
10479   case ISD::EXTRACT_VECTOR_ELT:
10480     return performExtractVectorEltCombine(N, DCI);
10481   case ISD::INSERT_VECTOR_ELT:
10482     return performInsertVectorEltCombine(N, DCI);
10483   }
10484   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10485 }
10486 
10487 /// Helper function for adjustWritemask
10488 static unsigned SubIdx2Lane(unsigned Idx) {
10489   switch (Idx) {
10490   default: return 0;
10491   case AMDGPU::sub0: return 0;
10492   case AMDGPU::sub1: return 1;
10493   case AMDGPU::sub2: return 2;
10494   case AMDGPU::sub3: return 3;
10495   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10496   }
10497 }
10498 
10499 /// Adjust the writemask of MIMG instructions
10500 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10501                                           SelectionDAG &DAG) const {
10502   unsigned Opcode = Node->getMachineOpcode();
10503 
10504   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10505   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10506   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10507     return Node; // not implemented for D16
10508 
10509   SDNode *Users[5] = { nullptr };
10510   unsigned Lane = 0;
10511   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10512   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10513   unsigned NewDmask = 0;
10514   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10515   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10516   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10517                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10518   unsigned TFCLane = 0;
10519   bool HasChain = Node->getNumValues() > 1;
10520 
10521   if (OldDmask == 0) {
10522     // These are folded out, but on the chance it happens don't assert.
10523     return Node;
10524   }
10525 
10526   unsigned OldBitsSet = countPopulation(OldDmask);
10527   // Work out which is the TFE/LWE lane if that is enabled.
10528   if (UsesTFC) {
10529     TFCLane = OldBitsSet;
10530   }
10531 
10532   // Try to figure out the used register components
10533   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10534        I != E; ++I) {
10535 
10536     // Don't look at users of the chain.
10537     if (I.getUse().getResNo() != 0)
10538       continue;
10539 
10540     // Abort if we can't understand the usage
10541     if (!I->isMachineOpcode() ||
10542         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10543       return Node;
10544 
10545     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10546     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10547     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10548     // set, etc.
10549     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10550 
10551     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10552     if (UsesTFC && Lane == TFCLane) {
10553       Users[Lane] = *I;
10554     } else {
10555       // Set which texture component corresponds to the lane.
10556       unsigned Comp;
10557       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10558         Comp = countTrailingZeros(Dmask);
10559         Dmask &= ~(1 << Comp);
10560       }
10561 
10562       // Abort if we have more than one user per component.
10563       if (Users[Lane])
10564         return Node;
10565 
10566       Users[Lane] = *I;
10567       NewDmask |= 1 << Comp;
10568     }
10569   }
10570 
10571   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10572   bool NoChannels = !NewDmask;
10573   if (NoChannels) {
10574     if (!UsesTFC) {
10575       // No uses of the result and not using TFC. Then do nothing.
10576       return Node;
10577     }
10578     // If the original dmask has one channel - then nothing to do
10579     if (OldBitsSet == 1)
10580       return Node;
10581     // Use an arbitrary dmask - required for the instruction to work
10582     NewDmask = 1;
10583   }
10584   // Abort if there's no change
10585   if (NewDmask == OldDmask)
10586     return Node;
10587 
10588   unsigned BitsSet = countPopulation(NewDmask);
10589 
10590   // Check for TFE or LWE - increase the number of channels by one to account
10591   // for the extra return value
10592   // This will need adjustment for D16 if this is also included in
10593   // adjustWriteMask (this function) but at present D16 are excluded.
10594   unsigned NewChannels = BitsSet + UsesTFC;
10595 
10596   int NewOpcode =
10597       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10598   assert(NewOpcode != -1 &&
10599          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10600          "failed to find equivalent MIMG op");
10601 
10602   // Adjust the writemask in the node
10603   SmallVector<SDValue, 12> Ops;
10604   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10605   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10606   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10607 
10608   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10609 
10610   MVT ResultVT = NewChannels == 1 ?
10611     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10612                            NewChannels == 5 ? 8 : NewChannels);
10613   SDVTList NewVTList = HasChain ?
10614     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10615 
10616 
10617   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10618                                               NewVTList, Ops);
10619 
10620   if (HasChain) {
10621     // Update chain.
10622     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10623     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10624   }
10625 
10626   if (NewChannels == 1) {
10627     assert(Node->hasNUsesOfValue(1, 0));
10628     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10629                                       SDLoc(Node), Users[Lane]->getValueType(0),
10630                                       SDValue(NewNode, 0));
10631     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10632     return nullptr;
10633   }
10634 
10635   // Update the users of the node with the new indices
10636   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10637     SDNode *User = Users[i];
10638     if (!User) {
10639       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10640       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10641       if (i || !NoChannels)
10642         continue;
10643     } else {
10644       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10645       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10646     }
10647 
10648     switch (Idx) {
10649     default: break;
10650     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10651     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10652     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10653     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10654     }
10655   }
10656 
10657   DAG.RemoveDeadNode(Node);
10658   return nullptr;
10659 }
10660 
10661 static bool isFrameIndexOp(SDValue Op) {
10662   if (Op.getOpcode() == ISD::AssertZext)
10663     Op = Op.getOperand(0);
10664 
10665   return isa<FrameIndexSDNode>(Op);
10666 }
10667 
10668 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10669 /// with frame index operands.
10670 /// LLVM assumes that inputs are to these instructions are registers.
10671 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10672                                                         SelectionDAG &DAG) const {
10673   if (Node->getOpcode() == ISD::CopyToReg) {
10674     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10675     SDValue SrcVal = Node->getOperand(2);
10676 
10677     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10678     // to try understanding copies to physical registers.
10679     if (SrcVal.getValueType() == MVT::i1 &&
10680         Register::isPhysicalRegister(DestReg->getReg())) {
10681       SDLoc SL(Node);
10682       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10683       SDValue VReg = DAG.getRegister(
10684         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10685 
10686       SDNode *Glued = Node->getGluedNode();
10687       SDValue ToVReg
10688         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10689                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10690       SDValue ToResultReg
10691         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10692                            VReg, ToVReg.getValue(1));
10693       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10694       DAG.RemoveDeadNode(Node);
10695       return ToResultReg.getNode();
10696     }
10697   }
10698 
10699   SmallVector<SDValue, 8> Ops;
10700   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10701     if (!isFrameIndexOp(Node->getOperand(i))) {
10702       Ops.push_back(Node->getOperand(i));
10703       continue;
10704     }
10705 
10706     SDLoc DL(Node);
10707     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10708                                      Node->getOperand(i).getValueType(),
10709                                      Node->getOperand(i)), 0));
10710   }
10711 
10712   return DAG.UpdateNodeOperands(Node, Ops);
10713 }
10714 
10715 /// Fold the instructions after selecting them.
10716 /// Returns null if users were already updated.
10717 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10718                                           SelectionDAG &DAG) const {
10719   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10720   unsigned Opcode = Node->getMachineOpcode();
10721 
10722   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10723       !TII->isGather4(Opcode)) {
10724     return adjustWritemask(Node, DAG);
10725   }
10726 
10727   if (Opcode == AMDGPU::INSERT_SUBREG ||
10728       Opcode == AMDGPU::REG_SEQUENCE) {
10729     legalizeTargetIndependentNode(Node, DAG);
10730     return Node;
10731   }
10732 
10733   switch (Opcode) {
10734   case AMDGPU::V_DIV_SCALE_F32:
10735   case AMDGPU::V_DIV_SCALE_F64: {
10736     // Satisfy the operand register constraint when one of the inputs is
10737     // undefined. Ordinarily each undef value will have its own implicit_def of
10738     // a vreg, so force these to use a single register.
10739     SDValue Src0 = Node->getOperand(0);
10740     SDValue Src1 = Node->getOperand(1);
10741     SDValue Src2 = Node->getOperand(2);
10742 
10743     if ((Src0.isMachineOpcode() &&
10744          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10745         (Src0 == Src1 || Src0 == Src2))
10746       break;
10747 
10748     MVT VT = Src0.getValueType().getSimpleVT();
10749     const TargetRegisterClass *RC =
10750         getRegClassFor(VT, Src0.getNode()->isDivergent());
10751 
10752     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10753     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10754 
10755     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10756                                       UndefReg, Src0, SDValue());
10757 
10758     // src0 must be the same register as src1 or src2, even if the value is
10759     // undefined, so make sure we don't violate this constraint.
10760     if (Src0.isMachineOpcode() &&
10761         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10762       if (Src1.isMachineOpcode() &&
10763           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10764         Src0 = Src1;
10765       else if (Src2.isMachineOpcode() &&
10766                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10767         Src0 = Src2;
10768       else {
10769         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10770         Src0 = UndefReg;
10771         Src1 = UndefReg;
10772       }
10773     } else
10774       break;
10775 
10776     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10777     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10778       Ops.push_back(Node->getOperand(I));
10779 
10780     Ops.push_back(ImpDef.getValue(1));
10781     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10782   }
10783   default:
10784     break;
10785   }
10786 
10787   return Node;
10788 }
10789 
10790 /// Assign the register class depending on the number of
10791 /// bits set in the writemask
10792 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10793                                                      SDNode *Node) const {
10794   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10795 
10796   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10797 
10798   if (TII->isVOP3(MI.getOpcode())) {
10799     // Make sure constant bus requirements are respected.
10800     TII->legalizeOperandsVOP3(MRI, MI);
10801 
10802     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10803     // This saves a chain-copy of registers and better ballance register
10804     // use between vgpr and agpr as agpr tuples tend to be big.
10805     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10806       unsigned Opc = MI.getOpcode();
10807       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10808       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10809                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10810         if (I == -1)
10811           break;
10812         MachineOperand &Op = MI.getOperand(I);
10813         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10814              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10815             !Register::isVirtualRegister(Op.getReg()) ||
10816             !TRI->isAGPR(MRI, Op.getReg()))
10817           continue;
10818         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10819         if (!Src || !Src->isCopy() ||
10820             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10821           continue;
10822         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10823         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10824         // All uses of agpr64 and agpr32 can also accept vgpr except for
10825         // v_accvgpr_read, but we do not produce agpr reads during selection,
10826         // so no use checks are needed.
10827         MRI.setRegClass(Op.getReg(), NewRC);
10828       }
10829     }
10830 
10831     return;
10832   }
10833 
10834   // Replace unused atomics with the no return version.
10835   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10836   if (NoRetAtomicOp != -1) {
10837     if (!Node->hasAnyUseOfValue(0)) {
10838       MI.setDesc(TII->get(NoRetAtomicOp));
10839       MI.RemoveOperand(0);
10840       return;
10841     }
10842 
10843     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10844     // instruction, because the return type of these instructions is a vec2 of
10845     // the memory type, so it can be tied to the input operand.
10846     // This means these instructions always have a use, so we need to add a
10847     // special case to check if the atomic has only one extract_subreg use,
10848     // which itself has no uses.
10849     if ((Node->hasNUsesOfValue(1, 0) &&
10850          Node->use_begin()->isMachineOpcode() &&
10851          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10852          !Node->use_begin()->hasAnyUseOfValue(0))) {
10853       Register Def = MI.getOperand(0).getReg();
10854 
10855       // Change this into a noret atomic.
10856       MI.setDesc(TII->get(NoRetAtomicOp));
10857       MI.RemoveOperand(0);
10858 
10859       // If we only remove the def operand from the atomic instruction, the
10860       // extract_subreg will be left with a use of a vreg without a def.
10861       // So we need to insert an implicit_def to avoid machine verifier
10862       // errors.
10863       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10864               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10865     }
10866     return;
10867   }
10868 }
10869 
10870 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10871                               uint64_t Val) {
10872   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10873   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10874 }
10875 
10876 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10877                                                 const SDLoc &DL,
10878                                                 SDValue Ptr) const {
10879   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10880 
10881   // Build the half of the subregister with the constants before building the
10882   // full 128-bit register. If we are building multiple resource descriptors,
10883   // this will allow CSEing of the 2-component register.
10884   const SDValue Ops0[] = {
10885     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10886     buildSMovImm32(DAG, DL, 0),
10887     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10888     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10889     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10890   };
10891 
10892   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10893                                                 MVT::v2i32, Ops0), 0);
10894 
10895   // Combine the constants and the pointer.
10896   const SDValue Ops1[] = {
10897     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10898     Ptr,
10899     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10900     SubRegHi,
10901     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10902   };
10903 
10904   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10905 }
10906 
10907 /// Return a resource descriptor with the 'Add TID' bit enabled
10908 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10909 ///        of the resource descriptor) to create an offset, which is added to
10910 ///        the resource pointer.
10911 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10912                                            SDValue Ptr, uint32_t RsrcDword1,
10913                                            uint64_t RsrcDword2And3) const {
10914   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10915   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10916   if (RsrcDword1) {
10917     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10918                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10919                     0);
10920   }
10921 
10922   SDValue DataLo = buildSMovImm32(DAG, DL,
10923                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10924   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10925 
10926   const SDValue Ops[] = {
10927     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10928     PtrLo,
10929     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10930     PtrHi,
10931     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10932     DataLo,
10933     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10934     DataHi,
10935     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10936   };
10937 
10938   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10939 }
10940 
10941 //===----------------------------------------------------------------------===//
10942 //                         SI Inline Assembly Support
10943 //===----------------------------------------------------------------------===//
10944 
10945 std::pair<unsigned, const TargetRegisterClass *>
10946 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10947                                                StringRef Constraint,
10948                                                MVT VT) const {
10949   const TargetRegisterClass *RC = nullptr;
10950   if (Constraint.size() == 1) {
10951     const unsigned BitWidth = VT.getSizeInBits();
10952     switch (Constraint[0]) {
10953     default:
10954       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10955     case 's':
10956     case 'r':
10957       switch (BitWidth) {
10958       case 16:
10959         RC = &AMDGPU::SReg_32RegClass;
10960         break;
10961       case 64:
10962         RC = &AMDGPU::SGPR_64RegClass;
10963         break;
10964       default:
10965         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
10966         if (!RC)
10967           return std::make_pair(0U, nullptr);
10968         break;
10969       }
10970       break;
10971     case 'v':
10972       switch (BitWidth) {
10973       case 16:
10974         RC = &AMDGPU::VGPR_32RegClass;
10975         break;
10976       default:
10977         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
10978         if (!RC)
10979           return std::make_pair(0U, nullptr);
10980         break;
10981       }
10982       break;
10983     case 'a':
10984       if (!Subtarget->hasMAIInsts())
10985         break;
10986       switch (BitWidth) {
10987       case 16:
10988         RC = &AMDGPU::AGPR_32RegClass;
10989         break;
10990       default:
10991         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
10992         if (!RC)
10993           return std::make_pair(0U, nullptr);
10994         break;
10995       }
10996       break;
10997     }
10998     // We actually support i128, i16 and f16 as inline parameters
10999     // even if they are not reported as legal
11000     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11001                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11002       return std::make_pair(0U, RC);
11003   }
11004 
11005   if (Constraint.size() > 1) {
11006     if (Constraint[1] == 'v') {
11007       RC = &AMDGPU::VGPR_32RegClass;
11008     } else if (Constraint[1] == 's') {
11009       RC = &AMDGPU::SGPR_32RegClass;
11010     } else if (Constraint[1] == 'a') {
11011       RC = &AMDGPU::AGPR_32RegClass;
11012     }
11013 
11014     if (RC) {
11015       uint32_t Idx;
11016       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11017       if (!Failed && Idx < RC->getNumRegs())
11018         return std::make_pair(RC->getRegister(Idx), RC);
11019     }
11020   }
11021 
11022   // FIXME: Returns VS_32 for physical SGPR constraints
11023   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11024 }
11025 
11026 SITargetLowering::ConstraintType
11027 SITargetLowering::getConstraintType(StringRef Constraint) const {
11028   if (Constraint.size() == 1) {
11029     switch (Constraint[0]) {
11030     default: break;
11031     case 's':
11032     case 'v':
11033     case 'a':
11034       return C_RegisterClass;
11035     case 'A':
11036       return C_Other;
11037     }
11038   }
11039   return TargetLowering::getConstraintType(Constraint);
11040 }
11041 
11042 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11043                                                     std::string &Constraint,
11044                                                     std::vector<SDValue> &Ops,
11045                                                     SelectionDAG &DAG) const {
11046   if (Constraint.length() == 1 && Constraint[0] == 'A') {
11047     LowerAsmOperandForConstraintA(Op, Ops, DAG);
11048   } else {
11049     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11050   }
11051 }
11052 
11053 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op,
11054                                                      std::vector<SDValue> &Ops,
11055                                                      SelectionDAG &DAG) const {
11056   unsigned Size = Op.getScalarValueSizeInBits();
11057   if (Size > 64)
11058     return;
11059 
11060   uint64_t Val;
11061   bool IsConst = false;
11062   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11063     Val = C->getSExtValue();
11064     IsConst = true;
11065   } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11066     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11067     IsConst = true;
11068   } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11069     if (Size != 16 || Op.getNumOperands() != 2)
11070       return;
11071     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11072       return;
11073     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11074       Val = C->getSExtValue();
11075       IsConst = true;
11076     } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11077       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11078       IsConst = true;
11079     }
11080   }
11081 
11082   if (IsConst) {
11083     bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11084     if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11085         (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11086         (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11087       // Clear unused bits of fp constants
11088       if (!AMDGPU::isInlinableIntLiteral(Val)) {
11089         unsigned UnusedBits = 64 - Size;
11090         Val = (Val << UnusedBits) >> UnusedBits;
11091       }
11092       auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64);
11093       Ops.push_back(Res);
11094     }
11095   }
11096 }
11097 
11098 // Figure out which registers should be reserved for stack access. Only after
11099 // the function is legalized do we know all of the non-spill stack objects or if
11100 // calls are present.
11101 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11102   MachineRegisterInfo &MRI = MF.getRegInfo();
11103   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11104   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11105   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11106 
11107   if (Info->isEntryFunction()) {
11108     // Callable functions have fixed registers used for stack access.
11109     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11110   }
11111 
11112   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11113                              Info->getStackPtrOffsetReg()));
11114   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11115     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11116 
11117   // We need to worry about replacing the default register with itself in case
11118   // of MIR testcases missing the MFI.
11119   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11120     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11121 
11122   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11123     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11124 
11125   Info->limitOccupancy(MF);
11126 
11127   if (ST.isWave32() && !MF.empty()) {
11128     // Add VCC_HI def because many instructions marked as imp-use VCC where
11129     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11130     // having a use of undef.
11131 
11132     const SIInstrInfo *TII = ST.getInstrInfo();
11133     DebugLoc DL;
11134 
11135     MachineBasicBlock &MBB = MF.front();
11136     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11137     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11138 
11139     for (auto &MBB : MF) {
11140       for (auto &MI : MBB) {
11141         TII->fixImplicitOperands(MI);
11142       }
11143     }
11144   }
11145 
11146   TargetLoweringBase::finalizeLowering(MF);
11147 
11148   // Allocate a VGPR for future SGPR Spill if
11149   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11150   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11151   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11152       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11153     Info->reserveVGPRforSGPRSpills(MF);
11154 }
11155 
11156 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
11157                                                      KnownBits &Known,
11158                                                      const APInt &DemandedElts,
11159                                                      const SelectionDAG &DAG,
11160                                                      unsigned Depth) const {
11161   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
11162                                                 DAG, Depth);
11163 
11164   // Set the high bits to zero based on the maximum allowed scratch size per
11165   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11166   // calculation won't overflow, so assume the sign bit is never set.
11167   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11168 }
11169 
11170 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11171   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11172   const Align CacheLineAlign = Align(64);
11173 
11174   // Pre-GFX10 target did not benefit from loop alignment
11175   if (!ML || DisableLoopAlignment ||
11176       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11177       getSubtarget()->hasInstFwdPrefetchBug())
11178     return PrefAlign;
11179 
11180   // On GFX10 I$ is 4 x 64 bytes cache lines.
11181   // By default prefetcher keeps one cache line behind and reads two ahead.
11182   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11183   // behind and one ahead.
11184   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11185   // If loop fits 64 bytes it always spans no more than two cache lines and
11186   // does not need an alignment.
11187   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11188   // Else if loop is less or equal 192 bytes we need two lines behind.
11189 
11190   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11191   const MachineBasicBlock *Header = ML->getHeader();
11192   if (Header->getAlignment() != PrefAlign)
11193     return Header->getAlignment(); // Already processed.
11194 
11195   unsigned LoopSize = 0;
11196   for (const MachineBasicBlock *MBB : ML->blocks()) {
11197     // If inner loop block is aligned assume in average half of the alignment
11198     // size to be added as nops.
11199     if (MBB != Header)
11200       LoopSize += MBB->getAlignment().value() / 2;
11201 
11202     for (const MachineInstr &MI : *MBB) {
11203       LoopSize += TII->getInstSizeInBytes(MI);
11204       if (LoopSize > 192)
11205         return PrefAlign;
11206     }
11207   }
11208 
11209   if (LoopSize <= 64)
11210     return PrefAlign;
11211 
11212   if (LoopSize <= 128)
11213     return CacheLineAlign;
11214 
11215   // If any of parent loops is surrounded by prefetch instructions do not
11216   // insert new for inner loop, which would reset parent's settings.
11217   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11218     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11219       auto I = Exit->getFirstNonDebugInstr();
11220       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11221         return CacheLineAlign;
11222     }
11223   }
11224 
11225   MachineBasicBlock *Pre = ML->getLoopPreheader();
11226   MachineBasicBlock *Exit = ML->getExitBlock();
11227 
11228   if (Pre && Exit) {
11229     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11230             TII->get(AMDGPU::S_INST_PREFETCH))
11231       .addImm(1); // prefetch 2 lines behind PC
11232 
11233     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11234             TII->get(AMDGPU::S_INST_PREFETCH))
11235       .addImm(2); // prefetch 1 line behind PC
11236   }
11237 
11238   return CacheLineAlign;
11239 }
11240 
11241 LLVM_ATTRIBUTE_UNUSED
11242 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11243   assert(N->getOpcode() == ISD::CopyFromReg);
11244   do {
11245     // Follow the chain until we find an INLINEASM node.
11246     N = N->getOperand(0).getNode();
11247     if (N->getOpcode() == ISD::INLINEASM ||
11248         N->getOpcode() == ISD::INLINEASM_BR)
11249       return true;
11250   } while (N->getOpcode() == ISD::CopyFromReg);
11251   return false;
11252 }
11253 
11254 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11255   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11256 {
11257   switch (N->getOpcode()) {
11258     case ISD::CopyFromReg:
11259     {
11260       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11261       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11262       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11263       Register Reg = R->getReg();
11264 
11265       // FIXME: Why does this need to consider isLiveIn?
11266       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11267         return !TRI->isSGPRReg(MRI, Reg);
11268 
11269       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11270         return KDA->isDivergent(V);
11271 
11272       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11273       return !TRI->isSGPRReg(MRI, Reg);
11274     }
11275     break;
11276     case ISD::LOAD: {
11277       const LoadSDNode *L = cast<LoadSDNode>(N);
11278       unsigned AS = L->getAddressSpace();
11279       // A flat load may access private memory.
11280       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11281     } break;
11282     case ISD::CALLSEQ_END:
11283     return true;
11284     break;
11285     case ISD::INTRINSIC_WO_CHAIN:
11286     {
11287 
11288     }
11289       return AMDGPU::isIntrinsicSourceOfDivergence(
11290       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11291     case ISD::INTRINSIC_W_CHAIN:
11292       return AMDGPU::isIntrinsicSourceOfDivergence(
11293       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11294   }
11295   return false;
11296 }
11297 
11298 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11299                                                EVT VT) const {
11300   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11301   case MVT::f32:
11302     return hasFP32Denormals(DAG.getMachineFunction());
11303   case MVT::f64:
11304   case MVT::f16:
11305     return hasFP64FP16Denormals(DAG.getMachineFunction());
11306   default:
11307     return false;
11308   }
11309 }
11310 
11311 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11312                                                     const SelectionDAG &DAG,
11313                                                     bool SNaN,
11314                                                     unsigned Depth) const {
11315   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11316     const MachineFunction &MF = DAG.getMachineFunction();
11317     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11318 
11319     if (Info->getMode().DX10Clamp)
11320       return true; // Clamped to 0.
11321     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11322   }
11323 
11324   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11325                                                             SNaN, Depth);
11326 }
11327 
11328 TargetLowering::AtomicExpansionKind
11329 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11330   switch (RMW->getOperation()) {
11331   case AtomicRMWInst::FAdd: {
11332     Type *Ty = RMW->getType();
11333 
11334     // We don't have a way to support 16-bit atomics now, so just leave them
11335     // as-is.
11336     if (Ty->isHalfTy())
11337       return AtomicExpansionKind::None;
11338 
11339     if (!Ty->isFloatTy())
11340       return AtomicExpansionKind::CmpXChg;
11341 
11342     // TODO: Do have these for flat. Older targets also had them for buffers.
11343     unsigned AS = RMW->getPointerAddressSpace();
11344 
11345     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11346       return RMW->use_empty() ? AtomicExpansionKind::None :
11347                                 AtomicExpansionKind::CmpXChg;
11348     }
11349 
11350     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11351       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11352   }
11353   default:
11354     break;
11355   }
11356 
11357   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11358 }
11359 
11360 const TargetRegisterClass *
11361 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11362   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11363   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11364   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11365     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11366                                                : &AMDGPU::SReg_32RegClass;
11367   if (!TRI->isSGPRClass(RC) && !isDivergent)
11368     return TRI->getEquivalentSGPRClass(RC);
11369   else if (TRI->isSGPRClass(RC) && isDivergent)
11370     return TRI->getEquivalentVGPRClass(RC);
11371 
11372   return RC;
11373 }
11374 
11375 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11376 // uniform values (as produced by the mask results of control flow intrinsics)
11377 // used outside of divergent blocks. The phi users need to also be treated as
11378 // always uniform.
11379 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11380                       unsigned WaveSize) {
11381   // FIXME: We asssume we never cast the mask results of a control flow
11382   // intrinsic.
11383   // Early exit if the type won't be consistent as a compile time hack.
11384   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11385   if (!IT || IT->getBitWidth() != WaveSize)
11386     return false;
11387 
11388   if (!isa<Instruction>(V))
11389     return false;
11390   if (!Visited.insert(V).second)
11391     return false;
11392   bool Result = false;
11393   for (auto U : V->users()) {
11394     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11395       if (V == U->getOperand(1)) {
11396         switch (Intrinsic->getIntrinsicID()) {
11397         default:
11398           Result = false;
11399           break;
11400         case Intrinsic::amdgcn_if_break:
11401         case Intrinsic::amdgcn_if:
11402         case Intrinsic::amdgcn_else:
11403           Result = true;
11404           break;
11405         }
11406       }
11407       if (V == U->getOperand(0)) {
11408         switch (Intrinsic->getIntrinsicID()) {
11409         default:
11410           Result = false;
11411           break;
11412         case Intrinsic::amdgcn_end_cf:
11413         case Intrinsic::amdgcn_loop:
11414           Result = true;
11415           break;
11416         }
11417       }
11418     } else {
11419       Result = hasCFUser(U, Visited, WaveSize);
11420     }
11421     if (Result)
11422       break;
11423   }
11424   return Result;
11425 }
11426 
11427 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11428                                                const Value *V) const {
11429   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11430     if (CI->isInlineAsm()) {
11431       // FIXME: This cannot give a correct answer. This should only trigger in
11432       // the case where inline asm returns mixed SGPR and VGPR results, used
11433       // outside the defining block. We don't have a specific result to
11434       // consider, so this assumes if any value is SGPR, the overall register
11435       // also needs to be SGPR.
11436       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11437       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11438           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11439       for (auto &TC : TargetConstraints) {
11440         if (TC.Type == InlineAsm::isOutput) {
11441           ComputeConstraintToUse(TC, SDValue());
11442           unsigned AssignedReg;
11443           const TargetRegisterClass *RC;
11444           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11445               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11446           if (RC) {
11447             MachineRegisterInfo &MRI = MF.getRegInfo();
11448             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11449               return true;
11450             else if (SIRI->isSGPRClass(RC))
11451               return true;
11452           }
11453         }
11454       }
11455     }
11456   }
11457   SmallPtrSet<const Value *, 16> Visited;
11458   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11459 }
11460