1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Custom DAG lowering for SI
13 //===----------------------------------------------------------------------===//
15 #if defined(_MSC_VER) || defined(__MINGW32__)
17 #define _USE_MATH_DEFINES
20 #include "SIISelLowering.h"
22 #include "AMDGPUIntrinsicInfo.h"
23 #include "AMDGPUSubtarget.h"
24 #include "AMDGPUTargetMachine.h"
25 #include "SIDefines.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
30 #include "Utils/AMDGPUBaseInfo.h"
31 #include "llvm/ADT/APFloat.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Twine.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/CallingConvLower.h"
42 #include "llvm/CodeGen/DAGCombine.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
89 #define DEBUG_TYPE "si-lower"
91 STATISTIC(NumTailCalls, "Number of tail calls");
93 static cl::opt<bool> EnableVGPRIndexMode(
94 "amdgpu-vgpr-index-mode",
95 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
98 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
99 "amdgpu-frame-index-zero-bits",
100 cl::desc("High bits of frame index assumed to be zero"),
104 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
105 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
106 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
107 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
108 return AMDGPU::SGPR0 + Reg;
111 llvm_unreachable("Cannot allocate sgpr");
114 SITargetLowering::SITargetLowering(const TargetMachine &TM,
115 const GCNSubtarget &STI)
116 : AMDGPUTargetLowering(TM, STI),
118 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
119 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
121 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
122 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
124 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
125 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
126 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
128 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
129 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
131 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
132 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
134 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
135 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
137 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
138 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
140 if (Subtarget->has16BitInsts()) {
141 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
142 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
144 // Unless there are also VOP3P operations, not operations are really legal.
145 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
146 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
147 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
148 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
151 computeRegisterProperties(Subtarget->getRegisterInfo());
153 // We need to custom lower vector stores from local memory
154 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
155 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
156 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
157 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
158 setOperationAction(ISD::LOAD, MVT::i1, Custom);
159 setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
161 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
162 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
163 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
164 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
165 setOperationAction(ISD::STORE, MVT::i1, Custom);
166 setOperationAction(ISD::STORE, MVT::v32i32, Custom);
168 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
169 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
170 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
171 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
172 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
173 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
174 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
175 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
176 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
177 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
179 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
180 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
182 setOperationAction(ISD::SELECT, MVT::i1, Promote);
183 setOperationAction(ISD::SELECT, MVT::i64, Custom);
184 setOperationAction(ISD::SELECT, MVT::f64, Promote);
185 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
187 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
188 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
189 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
190 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
191 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
193 setOperationAction(ISD::SETCC, MVT::i1, Promote);
194 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
195 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
196 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
198 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
199 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
201 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
206 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
207 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
209 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
210 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
211 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
212 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
213 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
214 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
215 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
217 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
218 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
219 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
220 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
222 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
223 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
224 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
225 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
227 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
228 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
229 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
230 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
231 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
232 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
234 setOperationAction(ISD::UADDO, MVT::i32, Legal);
235 setOperationAction(ISD::USUBO, MVT::i32, Legal);
237 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
238 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
240 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
241 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
242 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
245 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
246 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
249 // We only support LOAD/STORE and vector manipulation ops for vectors
250 // with > 4 elements.
251 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
252 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, MVT::v32i32 }) {
253 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
257 case ISD::BUILD_VECTOR:
259 case ISD::EXTRACT_VECTOR_ELT:
260 case ISD::INSERT_VECTOR_ELT:
261 case ISD::INSERT_SUBVECTOR:
262 case ISD::EXTRACT_SUBVECTOR:
263 case ISD::SCALAR_TO_VECTOR:
265 case ISD::CONCAT_VECTORS:
266 setOperationAction(Op, VT, Custom);
269 setOperationAction(Op, VT, Expand);
275 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
277 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
278 // is expanded to avoid having two separate loops in case the index is a VGPR.
280 // Most operations are naturally 32-bit vector operations. We only support
281 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
282 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
283 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
284 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
286 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
287 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
289 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
290 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
292 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
293 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
296 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
297 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
298 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
299 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
301 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
302 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
304 // Avoid stack access for these.
305 // TODO: Generalize to more vector types.
306 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
307 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
308 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
309 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
311 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
312 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
313 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
314 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
315 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
319 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
321 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
323 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
324 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
326 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
327 // and output demarshalling
328 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
329 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
331 // We can't return success/failure, only the old value,
332 // let LLVM add the comparison
333 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
334 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
336 if (Subtarget->hasFlatAddressSpace()) {
337 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
338 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
341 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
342 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
344 // On SI this is s_memtime and s_memrealtime on VI.
345 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
346 setOperationAction(ISD::TRAP, MVT::Other, Custom);
347 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
349 if (Subtarget->has16BitInsts()) {
350 setOperationAction(ISD::FLOG, MVT::f16, Custom);
351 setOperationAction(ISD::FEXP, MVT::f16, Custom);
352 setOperationAction(ISD::FLOG10, MVT::f16, Custom);
355 // v_mad_f32 does not support denormals according to some sources.
356 if (!Subtarget->hasFP32Denormals())
357 setOperationAction(ISD::FMAD, MVT::f32, Legal);
359 if (!Subtarget->hasBFI()) {
360 // fcopysign can be done in a single instruction with BFI.
361 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
362 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
365 if (!Subtarget->hasBCNT(32))
366 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
368 if (!Subtarget->hasBCNT(64))
369 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
371 if (Subtarget->hasFFBH())
372 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
374 if (Subtarget->hasFFBL())
375 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
377 // We only really have 32-bit BFE instructions (and 16-bit on VI).
379 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
380 // effort to match them now. We want this to be false for i64 cases when the
381 // extraction isn't restricted to the upper or lower half. Ideally we would
382 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
383 // span the midpoint are probably relatively rare, so don't worry about them
385 if (Subtarget->hasBFE())
386 setHasExtractBitsInsn(true);
388 setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
389 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
390 setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
391 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
394 // These are really only legal for ieee_mode functions. We should be avoiding
395 // them for functions that don't have ieee_mode enabled, so just say they are
397 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
398 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
399 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
400 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
403 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
404 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
405 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
406 setOperationAction(ISD::FRINT, MVT::f64, Legal);
408 setOperationAction(ISD::FCEIL, MVT::f64, Custom);
409 setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
410 setOperationAction(ISD::FRINT, MVT::f64, Custom);
411 setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
414 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
416 setOperationAction(ISD::FSIN, MVT::f32, Custom);
417 setOperationAction(ISD::FCOS, MVT::f32, Custom);
418 setOperationAction(ISD::FDIV, MVT::f32, Custom);
419 setOperationAction(ISD::FDIV, MVT::f64, Custom);
421 if (Subtarget->has16BitInsts()) {
422 setOperationAction(ISD::Constant, MVT::i16, Legal);
424 setOperationAction(ISD::SMIN, MVT::i16, Legal);
425 setOperationAction(ISD::SMAX, MVT::i16, Legal);
427 setOperationAction(ISD::UMIN, MVT::i16, Legal);
428 setOperationAction(ISD::UMAX, MVT::i16, Legal);
430 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
431 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
433 setOperationAction(ISD::ROTR, MVT::i16, Promote);
434 setOperationAction(ISD::ROTL, MVT::i16, Promote);
436 setOperationAction(ISD::SDIV, MVT::i16, Promote);
437 setOperationAction(ISD::UDIV, MVT::i16, Promote);
438 setOperationAction(ISD::SREM, MVT::i16, Promote);
439 setOperationAction(ISD::UREM, MVT::i16, Promote);
441 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
442 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
444 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
445 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
446 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
447 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
448 setOperationAction(ISD::CTPOP, MVT::i16, Promote);
450 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
452 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
454 setOperationAction(ISD::LOAD, MVT::i16, Custom);
456 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
458 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
459 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
460 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
461 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
463 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
464 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
465 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
466 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
468 // F16 - Constant Actions.
469 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
471 // F16 - Load/Store Actions.
472 setOperationAction(ISD::LOAD, MVT::f16, Promote);
473 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
474 setOperationAction(ISD::STORE, MVT::f16, Promote);
475 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
477 // F16 - VOP1 Actions.
478 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
479 setOperationAction(ISD::FCOS, MVT::f16, Promote);
480 setOperationAction(ISD::FSIN, MVT::f16, Promote);
481 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
482 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
483 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
484 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
485 setOperationAction(ISD::FROUND, MVT::f16, Custom);
487 // F16 - VOP2 Actions.
488 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
489 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
491 setOperationAction(ISD::FDIV, MVT::f16, Custom);
493 // F16 - VOP3 Actions.
494 setOperationAction(ISD::FMA, MVT::f16, Legal);
495 if (!Subtarget->hasFP16Denormals())
496 setOperationAction(ISD::FMAD, MVT::f16, Legal);
498 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
499 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
503 case ISD::BUILD_VECTOR:
505 case ISD::EXTRACT_VECTOR_ELT:
506 case ISD::INSERT_VECTOR_ELT:
507 case ISD::INSERT_SUBVECTOR:
508 case ISD::EXTRACT_SUBVECTOR:
509 case ISD::SCALAR_TO_VECTOR:
511 case ISD::CONCAT_VECTORS:
512 setOperationAction(Op, VT, Custom);
515 setOperationAction(Op, VT, Expand);
521 // XXX - Do these do anything? Vector constants turn into build_vector.
522 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
523 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
525 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
526 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
528 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
529 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
530 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
531 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
533 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
534 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
535 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
536 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
538 setOperationAction(ISD::AND, MVT::v2i16, Promote);
539 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
540 setOperationAction(ISD::OR, MVT::v2i16, Promote);
541 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
542 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
543 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
545 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
546 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
547 setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
548 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
550 setOperationAction(ISD::STORE, MVT::v4i16, Promote);
551 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
552 setOperationAction(ISD::STORE, MVT::v4f16, Promote);
553 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
555 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
556 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
557 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
558 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
560 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
561 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
562 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
564 if (!Subtarget->hasVOP3PInsts()) {
565 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
566 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
569 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
570 // This isn't really legal, but this avoids the legalizer unrolling it (and
571 // allows matching fneg (fabs x) patterns)
572 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
574 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
575 setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
576 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
577 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
579 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
580 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
582 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
583 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
586 if (Subtarget->hasVOP3PInsts()) {
587 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
588 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
589 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
590 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
591 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
592 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
593 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
594 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
595 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
596 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
598 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
599 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
600 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
602 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
603 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
605 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
607 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
608 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
610 setOperationAction(ISD::SHL, MVT::v4i16, Custom);
611 setOperationAction(ISD::SRA, MVT::v4i16, Custom);
612 setOperationAction(ISD::SRL, MVT::v4i16, Custom);
613 setOperationAction(ISD::ADD, MVT::v4i16, Custom);
614 setOperationAction(ISD::SUB, MVT::v4i16, Custom);
615 setOperationAction(ISD::MUL, MVT::v4i16, Custom);
617 setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
618 setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
619 setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
620 setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
622 setOperationAction(ISD::FADD, MVT::v4f16, Custom);
623 setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
625 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
626 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
628 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
629 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
630 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
632 setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
633 setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
634 setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
637 setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
638 setOperationAction(ISD::FABS, MVT::v4f16, Custom);
640 if (Subtarget->has16BitInsts()) {
641 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
642 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
643 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
644 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
646 // Legalization hack.
647 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
648 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
650 setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
651 setOperationAction(ISD::FABS, MVT::v2f16, Custom);
654 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
655 setOperationAction(ISD::SELECT, VT, Custom);
658 setTargetDAGCombine(ISD::ADD);
659 setTargetDAGCombine(ISD::ADDCARRY);
660 setTargetDAGCombine(ISD::SUB);
661 setTargetDAGCombine(ISD::SUBCARRY);
662 setTargetDAGCombine(ISD::FADD);
663 setTargetDAGCombine(ISD::FSUB);
664 setTargetDAGCombine(ISD::FMINNUM);
665 setTargetDAGCombine(ISD::FMAXNUM);
666 setTargetDAGCombine(ISD::FMINNUM_IEEE);
667 setTargetDAGCombine(ISD::FMAXNUM_IEEE);
668 setTargetDAGCombine(ISD::FMA);
669 setTargetDAGCombine(ISD::SMIN);
670 setTargetDAGCombine(ISD::SMAX);
671 setTargetDAGCombine(ISD::UMIN);
672 setTargetDAGCombine(ISD::UMAX);
673 setTargetDAGCombine(ISD::SETCC);
674 setTargetDAGCombine(ISD::AND);
675 setTargetDAGCombine(ISD::OR);
676 setTargetDAGCombine(ISD::XOR);
677 setTargetDAGCombine(ISD::SINT_TO_FP);
678 setTargetDAGCombine(ISD::UINT_TO_FP);
679 setTargetDAGCombine(ISD::FCANONICALIZE);
680 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
681 setTargetDAGCombine(ISD::ZERO_EXTEND);
682 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
683 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
685 // All memory operations. Some folding on the pointer operand is done to help
686 // matching the constant offsets in the addressing modes.
687 setTargetDAGCombine(ISD::LOAD);
688 setTargetDAGCombine(ISD::STORE);
689 setTargetDAGCombine(ISD::ATOMIC_LOAD);
690 setTargetDAGCombine(ISD::ATOMIC_STORE);
691 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
692 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
693 setTargetDAGCombine(ISD::ATOMIC_SWAP);
694 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
695 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
696 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
697 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
698 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
699 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
700 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
701 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
702 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
703 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
705 setSchedulingPreference(Sched::RegPressure);
707 // SI at least has hardware support for floating point exceptions, but no way
708 // of using or handling them is implemented. They are also optional in OpenCL
710 setHasFloatingPointExceptions(Subtarget->hasFPExceptions());
713 const GCNSubtarget *SITargetLowering::getSubtarget() const {
717 //===----------------------------------------------------------------------===//
718 // TargetLowering queries
719 //===----------------------------------------------------------------------===//
721 // v_mad_mix* support a conversion from f16 to f32.
723 // There is only one special case when denormals are enabled we don't currently,
724 // where this is OK to use.
725 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
726 EVT DestVT, EVT SrcVT) const {
727 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
728 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
729 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
730 SrcVT.getScalarType() == MVT::f16;
733 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
734 // SI has some legal vector types, but no legal vector operations. Say no
735 // shuffles are legal in order to prefer scalarizing some vector operations.
739 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
742 // TODO: Consider splitting all arguments into 32-bit pieces.
743 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
744 EVT ScalarVT = VT.getScalarType();
745 unsigned Size = ScalarVT.getSizeInBits();
747 return ScalarVT.getSimpleVT();
752 if (Size == 16 && Subtarget->has16BitInsts())
753 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
756 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
759 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
762 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
763 unsigned NumElts = VT.getVectorNumElements();
764 EVT ScalarVT = VT.getScalarType();
765 unsigned Size = ScalarVT.getSizeInBits();
773 if (Size == 16 && Subtarget->has16BitInsts())
774 return (VT.getVectorNumElements() + 1) / 2;
777 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
780 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
781 LLVMContext &Context, CallingConv::ID CC,
782 EVT VT, EVT &IntermediateVT,
783 unsigned &NumIntermediates, MVT &RegisterVT) const {
784 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
785 unsigned NumElts = VT.getVectorNumElements();
786 EVT ScalarVT = VT.getScalarType();
787 unsigned Size = ScalarVT.getSizeInBits();
789 RegisterVT = ScalarVT.getSimpleVT();
790 IntermediateVT = RegisterVT;
791 NumIntermediates = NumElts;
792 return NumIntermediates;
796 RegisterVT = MVT::i32;
797 IntermediateVT = RegisterVT;
798 NumIntermediates = 2 * NumElts;
799 return NumIntermediates;
802 // FIXME: We should fix the ABI to be the same on targets without 16-bit
803 // support, but unless we can properly handle 3-vectors, it will be still be
805 if (Size == 16 && Subtarget->has16BitInsts()) {
806 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
807 IntermediateVT = RegisterVT;
808 NumIntermediates = (NumElts + 1) / 2;
809 return NumIntermediates;
813 return TargetLowering::getVectorTypeBreakdownForCallingConv(
814 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
817 static MVT memVTFromAggregate(Type *Ty) {
818 // Only limited forms of aggregate type currently expected.
819 assert(Ty->isStructTy() && "Expected struct type");
822 Type *ElementType = nullptr;
824 if (Ty->getContainedType(0)->isVectorTy()) {
825 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
826 ElementType = VecComponent->getElementType();
827 NumElts = VecComponent->getNumElements();
829 ElementType = Ty->getContainedType(0);
833 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
835 // Calculate the size of the memVT type from the aggregate
836 unsigned Pow2Elts = 0;
837 unsigned ElementSize;
838 switch (ElementType->getTypeID()) {
840 llvm_unreachable("Unknown type!");
841 case Type::IntegerTyID:
842 ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
847 case Type::FloatTyID:
851 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
852 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
854 return MVT::getVectorVT(MVT::getVT(ElementType, false),
858 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
861 unsigned IntrID) const {
862 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
863 AMDGPU::lookupRsrcIntrinsic(IntrID)) {
864 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
865 (Intrinsic::ID)IntrID);
866 if (Attr.hasFnAttribute(Attribute::ReadNone))
869 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
871 if (RsrcIntr->IsImage) {
872 Info.ptrVal = MFI->getImagePSV(
873 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
874 CI.getArgOperand(RsrcIntr->RsrcArg));
877 Info.ptrVal = MFI->getBufferPSV(
878 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
879 CI.getArgOperand(RsrcIntr->RsrcArg));
882 Info.flags = MachineMemOperand::MODereferenceable;
883 if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
884 Info.opc = ISD::INTRINSIC_W_CHAIN;
885 Info.memVT = MVT::getVT(CI.getType(), true);
886 if (Info.memVT == MVT::Other) {
887 // Some intrinsics return an aggregate type - special case to work out
889 Info.memVT = memVTFromAggregate(CI.getType());
891 Info.flags |= MachineMemOperand::MOLoad;
892 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
893 Info.opc = ISD::INTRINSIC_VOID;
894 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
895 Info.flags |= MachineMemOperand::MOStore;
898 Info.opc = ISD::INTRINSIC_W_CHAIN;
899 Info.memVT = MVT::getVT(CI.getType());
900 Info.flags = MachineMemOperand::MOLoad |
901 MachineMemOperand::MOStore |
902 MachineMemOperand::MODereferenceable;
904 // XXX - Should this be volatile without known ordering?
905 Info.flags |= MachineMemOperand::MOVolatile;
911 case Intrinsic::amdgcn_atomic_inc:
912 case Intrinsic::amdgcn_atomic_dec:
913 case Intrinsic::amdgcn_ds_ordered_add:
914 case Intrinsic::amdgcn_ds_ordered_swap:
915 case Intrinsic::amdgcn_ds_fadd:
916 case Intrinsic::amdgcn_ds_fmin:
917 case Intrinsic::amdgcn_ds_fmax: {
918 Info.opc = ISD::INTRINSIC_W_CHAIN;
919 Info.memVT = MVT::getVT(CI.getType());
920 Info.ptrVal = CI.getOperand(0);
922 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
924 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
925 if (!Vol || !Vol->isZero())
926 Info.flags |= MachineMemOperand::MOVolatile;
936 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
937 SmallVectorImpl<Value*> &Ops,
938 Type *&AccessTy) const {
939 switch (II->getIntrinsicID()) {
940 case Intrinsic::amdgcn_atomic_inc:
941 case Intrinsic::amdgcn_atomic_dec:
942 case Intrinsic::amdgcn_ds_ordered_add:
943 case Intrinsic::amdgcn_ds_ordered_swap:
944 case Intrinsic::amdgcn_ds_fadd:
945 case Intrinsic::amdgcn_ds_fmin:
946 case Intrinsic::amdgcn_ds_fmax: {
947 Value *Ptr = II->getArgOperand(0);
948 AccessTy = II->getType();
957 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
958 if (!Subtarget->hasFlatInstOffsets()) {
959 // Flat instructions do not have offsets, and only have the register
961 return AM.BaseOffs == 0 && AM.Scale == 0;
964 // GFX9 added a 13-bit signed offset. When using regular flat instructions,
965 // the sign bit is ignored and is treated as a 12-bit unsigned offset.
968 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
971 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
972 if (Subtarget->hasFlatGlobalInsts())
973 return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
975 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
976 // Assume the we will use FLAT for all global memory accesses
978 // FIXME: This assumption is currently wrong. On VI we still use
979 // MUBUF instructions for the r + i addressing mode. As currently
980 // implemented, the MUBUF instructions only work on buffer < 4GB.
981 // It may be possible to support > 4GB buffers with MUBUF instructions,
982 // by setting the stride value in the resource descriptor which would
983 // increase the size limit to (stride * 4GB). However, this is risky,
984 // because it has never been validated.
985 return isLegalFlatAddressingMode(AM);
988 return isLegalMUBUFAddressingMode(AM);
991 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
992 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
993 // additionally can do r + r + i with addr64. 32-bit has more addressing
994 // mode options. Depending on the resource constant, it can also do
995 // (i64 r0) + (i32 r1) * (i14 i).
997 // Private arrays end up using a scratch buffer most of the time, so also
998 // assume those use MUBUF instructions. Scratch loads / stores are currently
999 // implemented as mubuf instructions with offen bit set, so slightly
1000 // different than the normal addr64.
1001 if (!isUInt<12>(AM.BaseOffs))
1004 // FIXME: Since we can split immediate into soffset and immediate offset,
1005 // would it make sense to allow any immediate?
1008 case 0: // r + i or just i, depending on HasBaseReg.
1011 return true; // We have r + r or r + i.
1013 if (AM.HasBaseReg) {
1014 // Reject 2 * r + r.
1018 // Allow 2 * r as r + r
1019 // Or 2 * r + i is allowed as r + r + i.
1021 default: // Don't allow n * r
1026 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1027 const AddrMode &AM, Type *Ty,
1028 unsigned AS, Instruction *I) const {
1029 // No global is ever allowed as a base.
1033 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1034 return isLegalGlobalAddressingMode(AM);
1036 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1037 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
1038 // If the offset isn't a multiple of 4, it probably isn't going to be
1039 // correctly aligned.
1040 // FIXME: Can we get the real alignment here?
1041 if (AM.BaseOffs % 4 != 0)
1042 return isLegalMUBUFAddressingMode(AM);
1044 // There are no SMRD extloads, so if we have to do a small type access we
1045 // will use a MUBUF load.
1046 // FIXME?: We also need to do this if unaligned, but we don't know the
1048 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1049 return isLegalGlobalAddressingMode(AM);
1051 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1052 // SMRD instructions have an 8-bit, dword offset on SI.
1053 if (!isUInt<8>(AM.BaseOffs / 4))
1055 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1056 // On CI+, this can also be a 32-bit literal constant offset. If it fits
1057 // in 8-bits, it can use a smaller encoding.
1058 if (!isUInt<32>(AM.BaseOffs / 4))
1060 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1061 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1062 if (!isUInt<20>(AM.BaseOffs))
1065 llvm_unreachable("unhandled generation");
1067 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1070 if (AM.Scale == 1 && AM.HasBaseReg)
1075 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1076 return isLegalMUBUFAddressingMode(AM);
1077 } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1078 AS == AMDGPUAS::REGION_ADDRESS) {
1079 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1081 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1082 // an 8-bit dword offset but we don't know the alignment here.
1083 if (!isUInt<16>(AM.BaseOffs))
1086 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1089 if (AM.Scale == 1 && AM.HasBaseReg)
1093 } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1094 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1095 // For an unknown address space, this usually means that this is for some
1096 // reason being used for pure arithmetic, and not based on some addressing
1097 // computation. We don't have instructions that compute pointers with any
1098 // addressing modes, so treat them as having no offset like flat
1100 return isLegalFlatAddressingMode(AM);
1102 llvm_unreachable("unhandled address space");
1106 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1107 const SelectionDAG &DAG) const {
1108 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1109 return (MemVT.getSizeInBits() <= 4 * 32);
1110 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1111 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1112 return (MemVT.getSizeInBits() <= MaxPrivateBits);
1113 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
1114 return (MemVT.getSizeInBits() <= 2 * 32);
1119 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1122 bool *IsFast) const {
1126 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1127 // which isn't a simple VT.
1128 // Until MVT is extended to handle this, simply check for the size and
1129 // rely on the condition below: allow accesses if the size is a multiple of 4.
1130 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1131 VT.getStoreSize() > 16)) {
1135 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1136 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1137 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1138 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1139 // with adjacent offsets.
1140 bool AlignedBy4 = (Align % 4 == 0);
1142 *IsFast = AlignedBy4;
1147 // FIXME: We have to be conservative here and assume that flat operations
1148 // will access scratch. If we had access to the IR function, then we
1149 // could determine if any private memory was used in the function.
1150 if (!Subtarget->hasUnalignedScratchAccess() &&
1151 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1152 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1153 bool AlignedBy4 = Align >= 4;
1155 *IsFast = AlignedBy4;
1160 if (Subtarget->hasUnalignedBufferAccess()) {
1161 // If we have an uniform constant load, it still requires using a slow
1162 // buffer instruction if unaligned.
1164 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1165 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1166 (Align % 4 == 0) : true;
1172 // Smaller than dword value must be aligned.
1173 if (VT.bitsLT(MVT::i32))
1176 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1177 // byte-address are ignored, thus forcing Dword alignment.
1178 // This applies to private, global, and constant memory.
1182 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1185 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
1186 unsigned SrcAlign, bool IsMemset,
1189 MachineFunction &MF) const {
1190 // FIXME: Should account for address space here.
1192 // The default fallback uses the private pointer size as a guess for a type to
1193 // use. Make sure we switch these to 64-bit accesses.
1195 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1198 if (Size >= 8 && DstAlign >= 4)
1205 static bool isFlatGlobalAddrSpace(unsigned AS) {
1206 return AS == AMDGPUAS::GLOBAL_ADDRESS ||
1207 AS == AMDGPUAS::FLAT_ADDRESS ||
1208 AS == AMDGPUAS::CONSTANT_ADDRESS;
1211 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1212 unsigned DestAS) const {
1213 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1216 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1217 const MemSDNode *MemNode = cast<MemSDNode>(N);
1218 const Value *Ptr = MemNode->getMemOperand()->getValue();
1219 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1220 return I && I->getMetadata("amdgpu.noclobber");
1223 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
1224 unsigned DestAS) const {
1225 // Flat -> private/local is a simple truncate.
1226 // Flat -> global is no-op
1227 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1230 return isNoopAddrSpaceCast(SrcAS, DestAS);
1233 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1234 const MemSDNode *MemNode = cast<MemSDNode>(N);
1236 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1239 TargetLoweringBase::LegalizeTypeAction
1240 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1241 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1242 return TypeSplitVector;
1244 return TargetLoweringBase::getPreferredVectorAction(VT);
1247 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1249 // FIXME: Could be smarter if called for vector constants.
1253 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1254 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1259 // These operations are done with 32-bit instructions anyway.
1264 // TODO: Extensions?
1271 // SimplifySetCC uses this function to determine whether or not it should
1272 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1273 if (VT == MVT::i1 && Op == ISD::SETCC)
1276 return TargetLowering::isTypeDesirableForOp(Op, VT);
1279 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1282 uint64_t Offset) const {
1283 const DataLayout &DL = DAG.getDataLayout();
1284 MachineFunction &MF = DAG.getMachineFunction();
1285 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1287 const ArgDescriptor *InputPtrReg;
1288 const TargetRegisterClass *RC;
1290 std::tie(InputPtrReg, RC)
1291 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1293 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1294 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1295 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1296 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1298 return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1301 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1302 const SDLoc &SL) const {
1303 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1305 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1308 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1309 const SDLoc &SL, SDValue Val,
1311 const ISD::InputArg *Arg) const {
1312 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1314 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1315 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1318 if (MemVT.isFloatingPoint())
1319 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1321 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1323 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1328 SDValue SITargetLowering::lowerKernargMemParameter(
1329 SelectionDAG &DAG, EVT VT, EVT MemVT,
1330 const SDLoc &SL, SDValue Chain,
1331 uint64_t Offset, unsigned Align, bool Signed,
1332 const ISD::InputArg *Arg) const {
1333 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1334 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
1335 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1337 // Try to avoid using an extload by loading earlier than the argument address,
1338 // and extracting the relevant bits. The load should hopefully be merged with
1339 // the previous argument.
1340 if (MemVT.getStoreSize() < 4 && Align < 4) {
1341 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1342 int64_t AlignDownOffset = alignDown(Offset, 4);
1343 int64_t OffsetDiff = Offset - AlignDownOffset;
1345 EVT IntVT = MemVT.changeTypeToInteger();
1347 // TODO: If we passed in the base kernel offset we could have a better
1348 // alignment than 4, but we don't really need it.
1349 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1350 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1351 MachineMemOperand::MODereferenceable |
1352 MachineMemOperand::MOInvariant);
1354 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1355 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1357 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1358 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1359 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1362 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1365 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1366 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1367 MachineMemOperand::MODereferenceable |
1368 MachineMemOperand::MOInvariant);
1370 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1371 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1374 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1375 const SDLoc &SL, SDValue Chain,
1376 const ISD::InputArg &Arg) const {
1377 MachineFunction &MF = DAG.getMachineFunction();
1378 MachineFrameInfo &MFI = MF.getFrameInfo();
1380 if (Arg.Flags.isByVal()) {
1381 unsigned Size = Arg.Flags.getByValSize();
1382 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1383 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1386 unsigned ArgOffset = VA.getLocMemOffset();
1387 unsigned ArgSize = VA.getValVT().getStoreSize();
1389 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1391 // Create load nodes to retrieve arguments from the stack.
1392 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1395 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1396 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1397 MVT MemVT = VA.getValVT();
1399 switch (VA.getLocInfo()) {
1402 case CCValAssign::BCvt:
1403 MemVT = VA.getLocVT();
1405 case CCValAssign::SExt:
1406 ExtType = ISD::SEXTLOAD;
1408 case CCValAssign::ZExt:
1409 ExtType = ISD::ZEXTLOAD;
1411 case CCValAssign::AExt:
1412 ExtType = ISD::EXTLOAD;
1416 ArgValue = DAG.getExtLoad(
1417 ExtType, SL, VA.getLocVT(), Chain, FIN,
1418 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1423 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1424 const SIMachineFunctionInfo &MFI,
1426 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1427 const ArgDescriptor *Reg;
1428 const TargetRegisterClass *RC;
1430 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1431 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1434 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1435 CallingConv::ID CallConv,
1436 ArrayRef<ISD::InputArg> Ins,
1438 FunctionType *FType,
1439 SIMachineFunctionInfo *Info) {
1440 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1441 const ISD::InputArg *Arg = &Ins[I];
1443 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1444 "vector type argument should have been split");
1446 // First check if it's a PS input addr.
1447 if (CallConv == CallingConv::AMDGPU_PS &&
1448 !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) {
1450 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1452 // Inconveniently only the first part of the split is marked as isSplit,
1453 // so skip to the end. We only want to increment PSInputNum once for the
1454 // entire split argument.
1455 if (Arg->Flags.isSplit()) {
1456 while (!Arg->Flags.isSplitEnd()) {
1457 assert(!Arg->VT.isVector() &&
1458 "unexpected vector split in ps argument type");
1460 Splits.push_back(*Arg);
1466 // We can safely skip PS inputs.
1467 Skipped.set(Arg->getOrigArgIndex());
1472 Info->markPSInputAllocated(PSInputNum);
1474 Info->markPSInputEnabled(PSInputNum);
1479 Splits.push_back(*Arg);
1483 // Allocate special inputs passed in VGPRs.
1484 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1485 MachineFunction &MF,
1486 const SIRegisterInfo &TRI,
1487 SIMachineFunctionInfo &Info) {
1488 if (Info.hasWorkItemIDX()) {
1489 unsigned Reg = AMDGPU::VGPR0;
1490 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1492 CCInfo.AllocateReg(Reg);
1493 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1496 if (Info.hasWorkItemIDY()) {
1497 unsigned Reg = AMDGPU::VGPR1;
1498 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1500 CCInfo.AllocateReg(Reg);
1501 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1504 if (Info.hasWorkItemIDZ()) {
1505 unsigned Reg = AMDGPU::VGPR2;
1506 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1508 CCInfo.AllocateReg(Reg);
1509 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1513 // Try to allocate a VGPR at the end of the argument list, or if no argument
1514 // VGPRs are left allocating a stack slot.
1515 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1516 ArrayRef<MCPhysReg> ArgVGPRs
1517 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1518 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1519 if (RegIdx == ArgVGPRs.size()) {
1520 // Spill to stack required.
1521 int64_t Offset = CCInfo.AllocateStack(4, 4);
1523 return ArgDescriptor::createStack(Offset);
1526 unsigned Reg = ArgVGPRs[RegIdx];
1527 Reg = CCInfo.AllocateReg(Reg);
1528 assert(Reg != AMDGPU::NoRegister);
1530 MachineFunction &MF = CCInfo.getMachineFunction();
1531 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1532 return ArgDescriptor::createRegister(Reg);
1535 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1536 const TargetRegisterClass *RC,
1537 unsigned NumArgRegs) {
1538 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1539 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1540 if (RegIdx == ArgSGPRs.size())
1541 report_fatal_error("ran out of SGPRs for arguments");
1543 unsigned Reg = ArgSGPRs[RegIdx];
1544 Reg = CCInfo.AllocateReg(Reg);
1545 assert(Reg != AMDGPU::NoRegister);
1547 MachineFunction &MF = CCInfo.getMachineFunction();
1548 MF.addLiveIn(Reg, RC);
1549 return ArgDescriptor::createRegister(Reg);
1552 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1553 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1556 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1557 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1560 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1561 MachineFunction &MF,
1562 const SIRegisterInfo &TRI,
1563 SIMachineFunctionInfo &Info) {
1564 if (Info.hasWorkItemIDX())
1565 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1567 if (Info.hasWorkItemIDY())
1568 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1570 if (Info.hasWorkItemIDZ())
1571 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1574 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1575 MachineFunction &MF,
1576 const SIRegisterInfo &TRI,
1577 SIMachineFunctionInfo &Info) {
1578 auto &ArgInfo = Info.getArgInfo();
1580 // TODO: Unify handling with private memory pointers.
1582 if (Info.hasDispatchPtr())
1583 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1585 if (Info.hasQueuePtr())
1586 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1588 if (Info.hasKernargSegmentPtr())
1589 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1591 if (Info.hasDispatchID())
1592 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1594 // flat_scratch_init is not applicable for non-kernel functions.
1596 if (Info.hasWorkGroupIDX())
1597 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1599 if (Info.hasWorkGroupIDY())
1600 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1602 if (Info.hasWorkGroupIDZ())
1603 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1605 if (Info.hasImplicitArgPtr())
1606 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1609 // Allocate special inputs passed in user SGPRs.
1610 static void allocateHSAUserSGPRs(CCState &CCInfo,
1611 MachineFunction &MF,
1612 const SIRegisterInfo &TRI,
1613 SIMachineFunctionInfo &Info) {
1614 if (Info.hasImplicitBufferPtr()) {
1615 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1616 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1617 CCInfo.AllocateReg(ImplicitBufferPtrReg);
1620 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1621 if (Info.hasPrivateSegmentBuffer()) {
1622 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1623 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1624 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1627 if (Info.hasDispatchPtr()) {
1628 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1629 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1630 CCInfo.AllocateReg(DispatchPtrReg);
1633 if (Info.hasQueuePtr()) {
1634 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1635 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1636 CCInfo.AllocateReg(QueuePtrReg);
1639 if (Info.hasKernargSegmentPtr()) {
1640 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1641 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1642 CCInfo.AllocateReg(InputPtrReg);
1645 if (Info.hasDispatchID()) {
1646 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1647 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1648 CCInfo.AllocateReg(DispatchIDReg);
1651 if (Info.hasFlatScratchInit()) {
1652 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1653 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1654 CCInfo.AllocateReg(FlatScratchInitReg);
1657 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1658 // these from the dispatch pointer.
1661 // Allocate special input registers that are initialized per-wave.
1662 static void allocateSystemSGPRs(CCState &CCInfo,
1663 MachineFunction &MF,
1664 SIMachineFunctionInfo &Info,
1665 CallingConv::ID CallConv,
1667 if (Info.hasWorkGroupIDX()) {
1668 unsigned Reg = Info.addWorkGroupIDX();
1669 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1670 CCInfo.AllocateReg(Reg);
1673 if (Info.hasWorkGroupIDY()) {
1674 unsigned Reg = Info.addWorkGroupIDY();
1675 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1676 CCInfo.AllocateReg(Reg);
1679 if (Info.hasWorkGroupIDZ()) {
1680 unsigned Reg = Info.addWorkGroupIDZ();
1681 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1682 CCInfo.AllocateReg(Reg);
1685 if (Info.hasWorkGroupInfo()) {
1686 unsigned Reg = Info.addWorkGroupInfo();
1687 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1688 CCInfo.AllocateReg(Reg);
1691 if (Info.hasPrivateSegmentWaveByteOffset()) {
1692 // Scratch wave offset passed in system SGPR.
1693 unsigned PrivateSegmentWaveByteOffsetReg;
1696 PrivateSegmentWaveByteOffsetReg =
1697 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1699 // This is true if the scratch wave byte offset doesn't have a fixed
1701 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1702 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1703 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1706 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1708 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1709 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1713 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1714 MachineFunction &MF,
1715 const SIRegisterInfo &TRI,
1716 SIMachineFunctionInfo &Info) {
1717 // Now that we've figured out where the scratch register inputs are, see if
1718 // should reserve the arguments and use them directly.
1719 MachineFrameInfo &MFI = MF.getFrameInfo();
1720 bool HasStackObjects = MFI.hasStackObjects();
1722 // Record that we know we have non-spill stack objects so we don't need to
1723 // check all stack objects later.
1724 if (HasStackObjects)
1725 Info.setHasNonSpillStackObjects(true);
1727 // Everything live out of a block is spilled with fast regalloc, so it's
1728 // almost certain that spilling will be required.
1729 if (TM.getOptLevel() == CodeGenOpt::None)
1730 HasStackObjects = true;
1732 // For now assume stack access is needed in any callee functions, so we need
1733 // the scratch registers to pass in.
1734 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1736 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1737 if (ST.isAmdHsaOrMesa(MF.getFunction())) {
1738 if (RequiresStackAccess) {
1739 // If we have stack objects, we unquestionably need the private buffer
1740 // resource. For the Code Object V2 ABI, this will be the first 4 user
1741 // SGPR inputs. We can reserve those and use them directly.
1743 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1744 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1745 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1747 if (MFI.hasCalls()) {
1748 // If we have calls, we need to keep the frame register in a register
1749 // that won't be clobbered by a call, so ensure it is copied somewhere.
1751 // This is not a problem for the scratch wave offset, because the same
1752 // registers are reserved in all functions.
1754 // FIXME: Nothing is really ensuring this is a call preserved register,
1755 // it's just selected from the end so it happens to be.
1756 unsigned ReservedOffsetReg
1757 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1758 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1760 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1761 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1762 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1765 unsigned ReservedBufferReg
1766 = TRI.reservedPrivateSegmentBufferReg(MF);
1767 unsigned ReservedOffsetReg
1768 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1770 // We tentatively reserve the last registers (skipping the last two
1771 // which may contain VCC). After register allocation, we'll replace
1772 // these with the ones immediately after those which were really
1773 // allocated. In the prologue copies will be inserted from the argument
1774 // to these reserved registers.
1775 Info.setScratchRSrcReg(ReservedBufferReg);
1776 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1779 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1781 // Without HSA, relocations are used for the scratch pointer and the
1782 // buffer resource setup is always inserted in the prologue. Scratch wave
1783 // offset is still in an input SGPR.
1784 Info.setScratchRSrcReg(ReservedBufferReg);
1786 if (HasStackObjects && !MFI.hasCalls()) {
1787 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1788 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1789 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1791 unsigned ReservedOffsetReg
1792 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1793 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1798 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1799 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1800 return !Info->isEntryFunction();
1803 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1807 void SITargetLowering::insertCopiesSplitCSR(
1808 MachineBasicBlock *Entry,
1809 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1810 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1812 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1816 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1817 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1818 MachineBasicBlock::iterator MBBI = Entry->begin();
1819 for (const MCPhysReg *I = IStart; *I; ++I) {
1820 const TargetRegisterClass *RC = nullptr;
1821 if (AMDGPU::SReg_64RegClass.contains(*I))
1822 RC = &AMDGPU::SGPR_64RegClass;
1823 else if (AMDGPU::SReg_32RegClass.contains(*I))
1824 RC = &AMDGPU::SGPR_32RegClass;
1826 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1828 unsigned NewVR = MRI->createVirtualRegister(RC);
1829 // Create copy from CSR to a virtual register.
1830 Entry->addLiveIn(*I);
1831 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1834 // Insert the copy-back instructions right before the terminator.
1835 for (auto *Exit : Exits)
1836 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1837 TII->get(TargetOpcode::COPY), *I)
1842 SDValue SITargetLowering::LowerFormalArguments(
1843 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1844 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1845 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1846 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1848 MachineFunction &MF = DAG.getMachineFunction();
1849 const Function &Fn = MF.getFunction();
1850 FunctionType *FType = MF.getFunction().getFunctionType();
1851 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1852 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1854 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1855 DiagnosticInfoUnsupported NoGraphicsHSA(
1856 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1857 DAG.getContext()->diagnose(NoGraphicsHSA);
1858 return DAG.getEntryNode();
1861 // Create stack objects that are used for emitting debugger prologue if
1862 // "amdgpu-debugger-emit-prologue" attribute was specified.
1863 if (ST.debuggerEmitPrologue())
1864 createDebuggerPrologueStackObjects(MF);
1866 SmallVector<ISD::InputArg, 16> Splits;
1867 SmallVector<CCValAssign, 16> ArgLocs;
1868 BitVector Skipped(Ins.size());
1869 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1872 bool IsShader = AMDGPU::isShader(CallConv);
1873 bool IsKernel = AMDGPU::isKernel(CallConv);
1874 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1877 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1878 // this when allocating argument fixed offsets.
1879 CCInfo.AllocateStack(4, 4);
1883 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1885 // At least one interpolation mode must be enabled or else the GPU will
1888 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1889 // set PSInputAddr, the user wants to enable some bits after the compilation
1890 // based on run-time states. Since we can't know what the final PSInputEna
1891 // will look like, so we shouldn't do anything here and the user should take
1892 // responsibility for the correct programming.
1894 // Otherwise, the following restrictions apply:
1895 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1896 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1898 if (CallConv == CallingConv::AMDGPU_PS) {
1899 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1900 ((Info->getPSInputAddr() & 0xF) == 0 &&
1901 Info->isPSInputAllocated(11))) {
1902 CCInfo.AllocateReg(AMDGPU::VGPR0);
1903 CCInfo.AllocateReg(AMDGPU::VGPR1);
1904 Info->markPSInputAllocated(0);
1905 Info->markPSInputEnabled(0);
1907 if (Subtarget->isAmdPalOS()) {
1908 // For isAmdPalOS, the user does not enable some bits after compilation
1909 // based on run-time states; the register values being generated here are
1910 // the final ones set in hardware. Therefore we need to apply the
1911 // workaround to PSInputAddr and PSInputEnable together. (The case where
1912 // a bit is set in PSInputAddr but not PSInputEnable is where the
1913 // frontend set up an input arg for a particular interpolation mode, but
1914 // nothing uses that input arg. Really we should have an earlier pass
1915 // that removes such an arg.)
1916 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1917 if ((PsInputBits & 0x7F) == 0 ||
1918 ((PsInputBits & 0xF) == 0 &&
1919 (PsInputBits >> 11 & 1)))
1920 Info->markPSInputEnabled(
1921 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1925 assert(!Info->hasDispatchPtr() &&
1926 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1927 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1928 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1929 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1930 !Info->hasWorkItemIDZ());
1931 } else if (IsKernel) {
1932 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1934 Splits.append(Ins.begin(), Ins.end());
1938 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1939 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1943 analyzeFormalArgumentsCompute(CCInfo, Ins);
1945 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1946 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1949 SmallVector<SDValue, 16> Chains;
1951 // FIXME: This is the minimum kernel argument alignment. We should improve
1952 // this to the maximum alignment of the arguments.
1954 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
1956 const unsigned KernelArgBaseAlign = 16;
1958 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1959 const ISD::InputArg &Arg = Ins[i];
1960 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
1961 InVals.push_back(DAG.getUNDEF(Arg.VT));
1965 CCValAssign &VA = ArgLocs[ArgIdx++];
1966 MVT VT = VA.getLocVT();
1968 if (IsEntryFunc && VA.isMemLoc()) {
1970 EVT MemVT = VA.getLocVT();
1972 const uint64_t Offset = VA.getLocMemOffset();
1973 unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
1975 SDValue Arg = lowerKernargMemParameter(
1976 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
1977 Chains.push_back(Arg.getValue(1));
1980 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1981 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
1982 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1983 // On SI local pointers are just offsets into LDS, so they are always
1984 // less than 16-bits. On CI and newer they could potentially be
1985 // real pointers, so we can't guarantee their size.
1986 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1987 DAG.getValueType(MVT::i16));
1990 InVals.push_back(Arg);
1992 } else if (!IsEntryFunc && VA.isMemLoc()) {
1993 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1994 InVals.push_back(Val);
1995 if (!Arg.Flags.isByVal())
1996 Chains.push_back(Val.getValue(1));
2000 assert(VA.isRegLoc() && "Parameter must be in a register!");
2002 unsigned Reg = VA.getLocReg();
2003 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2004 EVT ValVT = VA.getValVT();
2006 Reg = MF.addLiveIn(Reg, RC);
2007 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2009 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
2010 // The return object should be reasonably addressable.
2012 // FIXME: This helps when the return is a real sret. If it is a
2013 // automatically inserted sret (i.e. CanLowerReturn returns false), an
2014 // extra copy is inserted in SelectionDAGBuilder which obscures this.
2015 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
2016 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2017 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2020 // If this is an 8 or 16-bit value, it is really passed promoted
2021 // to 32 bits. Insert an assert[sz]ext to capture this, then
2022 // truncate to the right size.
2023 switch (VA.getLocInfo()) {
2024 case CCValAssign::Full:
2026 case CCValAssign::BCvt:
2027 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2029 case CCValAssign::SExt:
2030 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2031 DAG.getValueType(ValVT));
2032 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2034 case CCValAssign::ZExt:
2035 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2036 DAG.getValueType(ValVT));
2037 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2039 case CCValAssign::AExt:
2040 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2043 llvm_unreachable("Unknown loc info!");
2046 InVals.push_back(Val);
2050 // Special inputs come after user arguments.
2051 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2054 // Start adding system SGPRs.
2056 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2058 CCInfo.AllocateReg(Info->getScratchRSrcReg());
2059 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2060 CCInfo.AllocateReg(Info->getFrameOffsetReg());
2061 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2064 auto &ArgUsageInfo =
2065 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2066 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2068 unsigned StackArgSize = CCInfo.getNextStackOffset();
2069 Info->setBytesInStackArgArea(StackArgSize);
2071 return Chains.empty() ? Chain :
2072 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2075 // TODO: If return values can't fit in registers, we should return as many as
2076 // possible in registers before passing on stack.
2077 bool SITargetLowering::CanLowerReturn(
2078 CallingConv::ID CallConv,
2079 MachineFunction &MF, bool IsVarArg,
2080 const SmallVectorImpl<ISD::OutputArg> &Outs,
2081 LLVMContext &Context) const {
2082 // Replacing returns with sret/stack usage doesn't make sense for shaders.
2083 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2084 // for shaders. Vector types should be explicitly handled by CC.
2085 if (AMDGPU::isEntryFunctionCC(CallConv))
2088 SmallVector<CCValAssign, 16> RVLocs;
2089 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2090 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2094 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2096 const SmallVectorImpl<ISD::OutputArg> &Outs,
2097 const SmallVectorImpl<SDValue> &OutVals,
2098 const SDLoc &DL, SelectionDAG &DAG) const {
2099 MachineFunction &MF = DAG.getMachineFunction();
2100 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2102 if (AMDGPU::isKernel(CallConv)) {
2103 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2107 bool IsShader = AMDGPU::isShader(CallConv);
2109 Info->setIfReturnsVoid(Outs.empty());
2110 bool IsWaveEnd = Info->returnsVoid() && IsShader;
2112 // CCValAssign - represent the assignment of the return value to a location.
2113 SmallVector<CCValAssign, 48> RVLocs;
2114 SmallVector<ISD::OutputArg, 48> Splits;
2116 // CCState - Info about the registers and stack slots.
2117 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2120 // Analyze outgoing return values.
2121 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2124 SmallVector<SDValue, 48> RetOps;
2125 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2127 // Add return address for callable functions.
2128 if (!Info->isEntryFunction()) {
2129 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2130 SDValue ReturnAddrReg = CreateLiveInRegister(
2131 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2133 // FIXME: Should be able to use a vreg here, but need a way to prevent it
2134 // from being allcoated to a CSR.
2136 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2139 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2140 Flag = Chain.getValue(1);
2142 RetOps.push_back(PhysReturnAddrReg);
2145 // Copy the result values into the output registers.
2146 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2147 ++I, ++RealRVLocIdx) {
2148 CCValAssign &VA = RVLocs[I];
2149 assert(VA.isRegLoc() && "Can only return in registers!");
2150 // TODO: Partially return in registers if return values don't fit.
2151 SDValue Arg = OutVals[RealRVLocIdx];
2153 // Copied from other backends.
2154 switch (VA.getLocInfo()) {
2155 case CCValAssign::Full:
2157 case CCValAssign::BCvt:
2158 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2160 case CCValAssign::SExt:
2161 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2163 case CCValAssign::ZExt:
2164 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2166 case CCValAssign::AExt:
2167 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2170 llvm_unreachable("Unknown loc info!");
2173 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2174 Flag = Chain.getValue(1);
2175 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2178 // FIXME: Does sret work properly?
2179 if (!Info->isEntryFunction()) {
2180 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2181 const MCPhysReg *I =
2182 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2185 if (AMDGPU::SReg_64RegClass.contains(*I))
2186 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2187 else if (AMDGPU::SReg_32RegClass.contains(*I))
2188 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2190 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2195 // Update chain and glue.
2198 RetOps.push_back(Flag);
2200 unsigned Opc = AMDGPUISD::ENDPGM;
2202 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2203 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2206 SDValue SITargetLowering::LowerCallResult(
2207 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2208 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2209 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2210 SDValue ThisVal) const {
2211 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2213 // Assign locations to each value returned by this call.
2214 SmallVector<CCValAssign, 16> RVLocs;
2215 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2217 CCInfo.AnalyzeCallResult(Ins, RetCC);
2219 // Copy all of the result registers out of their specified physreg.
2220 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2221 CCValAssign VA = RVLocs[i];
2224 if (VA.isRegLoc()) {
2225 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2226 Chain = Val.getValue(1);
2227 InFlag = Val.getValue(2);
2228 } else if (VA.isMemLoc()) {
2229 report_fatal_error("TODO: return values in memory");
2231 llvm_unreachable("unknown argument location type");
2233 switch (VA.getLocInfo()) {
2234 case CCValAssign::Full:
2236 case CCValAssign::BCvt:
2237 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2239 case CCValAssign::ZExt:
2240 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2241 DAG.getValueType(VA.getValVT()));
2242 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2244 case CCValAssign::SExt:
2245 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2246 DAG.getValueType(VA.getValVT()));
2247 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2249 case CCValAssign::AExt:
2250 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2253 llvm_unreachable("Unknown loc info!");
2256 InVals.push_back(Val);
2262 // Add code to pass special inputs required depending on used features separate
2263 // from the explicit user arguments present in the IR.
2264 void SITargetLowering::passSpecialInputs(
2265 CallLoweringInfo &CLI,
2267 const SIMachineFunctionInfo &Info,
2268 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2269 SmallVectorImpl<SDValue> &MemOpChains,
2270 SDValue Chain) const {
2271 // If we don't have a call site, this was a call inserted by
2272 // legalization. These can never use special inputs.
2276 const Function *CalleeFunc = CLI.CS.getCalledFunction();
2279 SelectionDAG &DAG = CLI.DAG;
2280 const SDLoc &DL = CLI.DL;
2282 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2284 auto &ArgUsageInfo =
2285 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2286 const AMDGPUFunctionArgInfo &CalleeArgInfo
2287 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2289 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2291 // TODO: Unify with private memory register handling. This is complicated by
2292 // the fact that at least in kernels, the input argument is not necessarily
2293 // in the same location as the input.
2294 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2295 AMDGPUFunctionArgInfo::DISPATCH_PTR,
2296 AMDGPUFunctionArgInfo::QUEUE_PTR,
2297 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2298 AMDGPUFunctionArgInfo::DISPATCH_ID,
2299 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2300 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2301 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2302 AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2303 AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2304 AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2305 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2308 for (auto InputID : InputRegs) {
2309 const ArgDescriptor *OutgoingArg;
2310 const TargetRegisterClass *ArgRC;
2312 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2316 const ArgDescriptor *IncomingArg;
2317 const TargetRegisterClass *IncomingArgRC;
2318 std::tie(IncomingArg, IncomingArgRC)
2319 = CallerArgInfo.getPreloadedValue(InputID);
2320 assert(IncomingArgRC == ArgRC);
2322 // All special arguments are ints for now.
2323 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2327 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2329 // The implicit arg ptr is special because it doesn't have a corresponding
2330 // input for kernels, and is computed from the kernarg segment pointer.
2331 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2332 InputReg = getImplicitArgPtr(DAG, DL);
2335 if (OutgoingArg->isRegister()) {
2336 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2338 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2339 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2341 MemOpChains.push_back(ArgStore);
2346 static bool canGuaranteeTCO(CallingConv::ID CC) {
2347 return CC == CallingConv::Fast;
2350 /// Return true if we might ever do TCO for calls with this calling convention.
2351 static bool mayTailCallThisCC(CallingConv::ID CC) {
2353 case CallingConv::C:
2356 return canGuaranteeTCO(CC);
2360 bool SITargetLowering::isEligibleForTailCallOptimization(
2361 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2362 const SmallVectorImpl<ISD::OutputArg> &Outs,
2363 const SmallVectorImpl<SDValue> &OutVals,
2364 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2365 if (!mayTailCallThisCC(CalleeCC))
2368 MachineFunction &MF = DAG.getMachineFunction();
2369 const Function &CallerF = MF.getFunction();
2370 CallingConv::ID CallerCC = CallerF.getCallingConv();
2371 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2372 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2374 // Kernels aren't callable, and don't have a live in return address so it
2375 // doesn't make sense to do a tail call with entry functions.
2376 if (!CallerPreserved)
2379 bool CCMatch = CallerCC == CalleeCC;
2381 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2382 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2387 // TODO: Can we handle var args?
2391 for (const Argument &Arg : CallerF.args()) {
2392 if (Arg.hasByValAttr())
2396 LLVMContext &Ctx = *DAG.getContext();
2398 // Check that the call results are passed in the same way.
2399 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2400 CCAssignFnForCall(CalleeCC, IsVarArg),
2401 CCAssignFnForCall(CallerCC, IsVarArg)))
2404 // The callee has to preserve all registers the caller needs to preserve.
2406 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2407 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2411 // Nothing more to check if the callee is taking no arguments.
2415 SmallVector<CCValAssign, 16> ArgLocs;
2416 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2418 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2420 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2421 // If the stack arguments for this call do not fit into our own save area then
2422 // the call cannot be made tail.
2423 // TODO: Is this really necessary?
2424 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2427 const MachineRegisterInfo &MRI = MF.getRegInfo();
2428 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2431 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2432 if (!CI->isTailCall())
2435 const Function *ParentFn = CI->getParent()->getParent();
2436 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2439 auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2440 return (Attr.getValueAsString() != "true");
2443 // The wave scratch offset register is used as the global base pointer.
2444 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2445 SmallVectorImpl<SDValue> &InVals) const {
2446 SelectionDAG &DAG = CLI.DAG;
2447 const SDLoc &DL = CLI.DL;
2448 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2449 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2450 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2451 SDValue Chain = CLI.Chain;
2452 SDValue Callee = CLI.Callee;
2453 bool &IsTailCall = CLI.IsTailCall;
2454 CallingConv::ID CallConv = CLI.CallConv;
2455 bool IsVarArg = CLI.IsVarArg;
2456 bool IsSibCall = false;
2457 bool IsThisReturn = false;
2458 MachineFunction &MF = DAG.getMachineFunction();
2461 return lowerUnhandledCall(CLI, InVals,
2462 "unsupported call to variadic function ");
2465 if (!CLI.CS.getInstruction())
2466 report_fatal_error("unsupported libcall legalization");
2468 if (!CLI.CS.getCalledFunction()) {
2469 return lowerUnhandledCall(CLI, InVals,
2470 "unsupported indirect call to function ");
2473 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2474 return lowerUnhandledCall(CLI, InVals,
2475 "unsupported required tail call to function ");
2478 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2479 // Note the issue is with the CC of the calling function, not of the call
2481 return lowerUnhandledCall(CLI, InVals,
2482 "unsupported call from graphics shader of function ");
2485 // The first 4 bytes are reserved for the callee's emergency stack slot.
2487 IsTailCall = isEligibleForTailCallOptimization(
2488 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2489 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2490 report_fatal_error("failed to perform tail call elimination on a call "
2491 "site marked musttail");
2494 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2496 // A sibling call is one where we're under the usual C ABI and not planning
2497 // to change that but can still do a tail call:
2498 if (!TailCallOpt && IsTailCall)
2505 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2507 // Analyze operands of the call, assigning locations to each operand.
2508 SmallVector<CCValAssign, 16> ArgLocs;
2509 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2510 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2512 // The first 4 bytes are reserved for the callee's emergency stack slot.
2513 CCInfo.AllocateStack(4, 4);
2515 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2517 // Get a count of how many bytes are to be pushed on the stack.
2518 unsigned NumBytes = CCInfo.getNextStackOffset();
2521 // Since we're not changing the ABI to make this a tail call, the memory
2522 // operands are already available in the caller's incoming argument space.
2526 // FPDiff is the byte offset of the call's argument area from the callee's.
2527 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2528 // by this amount for a tail call. In a sibling call it must be 0 because the
2529 // caller will deallocate the entire stack and the callee still expects its
2530 // arguments to begin at SP+0. Completely unused for non-tail calls.
2532 MachineFrameInfo &MFI = MF.getFrameInfo();
2533 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2535 SDValue CallerSavedFP;
2537 // Adjust the stack pointer for the new arguments...
2538 // These operations are automatically eliminated by the prolog/epilog pass
2540 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2542 unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2544 // In the HSA case, this should be an identity copy.
2545 SDValue ScratchRSrcReg
2546 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2547 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2549 // TODO: Don't hardcode these registers and get from the callee function.
2550 SDValue ScratchWaveOffsetReg
2551 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2552 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2554 if (!Info->isEntryFunction()) {
2555 // Avoid clobbering this function's FP value. In the current convention
2556 // callee will overwrite this, so do save/restore around the call site.
2557 CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2558 Info->getFrameOffsetReg(), MVT::i32);
2562 SmallVector<SDValue, 8> MemOpChains;
2563 MVT PtrVT = MVT::i32;
2565 // Walk the register/memloc assignments, inserting copies/loads.
2566 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2567 ++i, ++realArgIdx) {
2568 CCValAssign &VA = ArgLocs[i];
2569 SDValue Arg = OutVals[realArgIdx];
2571 // Promote the value if needed.
2572 switch (VA.getLocInfo()) {
2573 case CCValAssign::Full:
2575 case CCValAssign::BCvt:
2576 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2578 case CCValAssign::ZExt:
2579 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2581 case CCValAssign::SExt:
2582 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2584 case CCValAssign::AExt:
2585 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2587 case CCValAssign::FPExt:
2588 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2591 llvm_unreachable("Unknown loc info!");
2594 if (VA.isRegLoc()) {
2595 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2597 assert(VA.isMemLoc());
2600 MachinePointerInfo DstInfo;
2602 unsigned LocMemOffset = VA.getLocMemOffset();
2603 int32_t Offset = LocMemOffset;
2605 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2609 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2610 unsigned OpSize = Flags.isByVal() ?
2611 Flags.getByValSize() : VA.getValVT().getStoreSize();
2613 // FIXME: We can have better than the minimum byval required alignment.
2614 Align = Flags.isByVal() ? Flags.getByValAlign() :
2615 MinAlign(Subtarget->getStackAlignment(), Offset);
2617 Offset = Offset + FPDiff;
2618 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2620 DstAddr = DAG.getFrameIndex(FI, PtrVT);
2621 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2623 // Make sure any stack arguments overlapping with where we're storing
2624 // are loaded before this eventual operation. Otherwise they'll be
2627 // FIXME: Why is this really necessary? This seems to just result in a
2628 // lot of code to copy the stack and write them back to the same
2629 // locations, which are supposed to be immutable?
2630 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2633 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2634 Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset);
2637 if (Outs[i].Flags.isByVal()) {
2639 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2640 SDValue Cpy = DAG.getMemcpy(
2641 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2642 /*isVol = */ false, /*AlwaysInline = */ true,
2643 /*isTailCall = */ false, DstInfo,
2644 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2645 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
2647 MemOpChains.push_back(Cpy);
2649 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align);
2650 MemOpChains.push_back(Store);
2655 // Copy special input registers after user input arguments.
2656 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2658 if (!MemOpChains.empty())
2659 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2661 // Build a sequence of copy-to-reg nodes chained together with token chain
2662 // and flag operands which copy the outgoing args into the appropriate regs.
2664 for (auto &RegToPass : RegsToPass) {
2665 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2666 RegToPass.second, InFlag);
2667 InFlag = Chain.getValue(1);
2671 SDValue PhysReturnAddrReg;
2673 // Since the return is being combined with the call, we need to pass on the
2676 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2677 SDValue ReturnAddrReg = CreateLiveInRegister(
2678 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2680 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2682 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2683 InFlag = Chain.getValue(1);
2686 // We don't usually want to end the call-sequence here because we would tidy
2687 // the frame up *after* the call, however in the ABI-changing tail-call case
2688 // we've carefully laid out the parameters so that when sp is reset they'll be
2689 // in the correct location.
2690 if (IsTailCall && !IsSibCall) {
2691 Chain = DAG.getCALLSEQ_END(Chain,
2692 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2693 DAG.getTargetConstant(0, DL, MVT::i32),
2695 InFlag = Chain.getValue(1);
2698 std::vector<SDValue> Ops;
2699 Ops.push_back(Chain);
2700 Ops.push_back(Callee);
2703 // Each tail call may have to adjust the stack by a different amount, so
2704 // this information must travel along with the operation for eventual
2705 // consumption by emitEpilogue.
2706 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2708 Ops.push_back(PhysReturnAddrReg);
2711 // Add argument registers to the end of the list so that they are known live
2713 for (auto &RegToPass : RegsToPass) {
2714 Ops.push_back(DAG.getRegister(RegToPass.first,
2715 RegToPass.second.getValueType()));
2718 // Add a register mask operand representing the call-preserved registers.
2720 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2721 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2722 assert(Mask && "Missing call preserved mask for calling convention");
2723 Ops.push_back(DAG.getRegisterMask(Mask));
2725 if (InFlag.getNode())
2726 Ops.push_back(InFlag);
2728 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2730 // If we're doing a tall call, use a TC_RETURN here rather than an
2731 // actual call instruction.
2733 MFI.setHasTailCall();
2734 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2737 // Returns a chain and a flag for retval copy to use.
2738 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2739 Chain = Call.getValue(0);
2740 InFlag = Call.getValue(1);
2742 if (CallerSavedFP) {
2743 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2744 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2745 InFlag = Chain.getValue(1);
2748 uint64_t CalleePopBytes = NumBytes;
2749 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2750 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2753 InFlag = Chain.getValue(1);
2755 // Handle result values, copying them out of physregs into vregs that we
2757 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2758 InVals, IsThisReturn,
2759 IsThisReturn ? OutVals[0] : SDValue());
2762 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2763 SelectionDAG &DAG) const {
2764 unsigned Reg = StringSwitch<unsigned>(RegName)
2765 .Case("m0", AMDGPU::M0)
2766 .Case("exec", AMDGPU::EXEC)
2767 .Case("exec_lo", AMDGPU::EXEC_LO)
2768 .Case("exec_hi", AMDGPU::EXEC_HI)
2769 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2770 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2771 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2772 .Default(AMDGPU::NoRegister);
2774 if (Reg == AMDGPU::NoRegister) {
2775 report_fatal_error(Twine("invalid register name \""
2776 + StringRef(RegName) + "\"."));
2780 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2781 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2782 report_fatal_error(Twine("invalid register \""
2783 + StringRef(RegName) + "\" for subtarget."));
2788 case AMDGPU::EXEC_LO:
2789 case AMDGPU::EXEC_HI:
2790 case AMDGPU::FLAT_SCR_LO:
2791 case AMDGPU::FLAT_SCR_HI:
2792 if (VT.getSizeInBits() == 32)
2796 case AMDGPU::FLAT_SCR:
2797 if (VT.getSizeInBits() == 64)
2801 llvm_unreachable("missing register type checking");
2804 report_fatal_error(Twine("invalid type for register \""
2805 + StringRef(RegName) + "\"."));
2808 // If kill is not the last instruction, split the block so kill is always a
2809 // proper terminator.
2810 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2811 MachineBasicBlock *BB) const {
2812 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2814 MachineBasicBlock::iterator SplitPoint(&MI);
2817 if (SplitPoint == BB->end()) {
2818 // Don't bother with a new block.
2819 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2823 MachineFunction *MF = BB->getParent();
2824 MachineBasicBlock *SplitBB
2825 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2827 MF->insert(++MachineFunction::iterator(BB), SplitBB);
2828 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2830 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2831 BB->addSuccessor(SplitBB);
2833 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2837 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2838 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2839 // will only do one iteration. In the worst case, this will loop 64 times.
2841 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2842 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2843 const SIInstrInfo *TII,
2844 MachineRegisterInfo &MRI,
2845 MachineBasicBlock &OrigBB,
2846 MachineBasicBlock &LoopBB,
2848 const MachineOperand &IdxReg,
2852 unsigned InitSaveExecReg,
2855 bool IsIndirectSrc) {
2856 MachineBasicBlock::iterator I = LoopBB.begin();
2858 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2859 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2860 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2861 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2863 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2869 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2870 .addReg(InitSaveExecReg)
2875 // Read the next variant <- also loop target.
2876 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2877 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2879 // Compare the just read M0 value to all possible Idx values.
2880 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2881 .addReg(CurrentIdxReg)
2882 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2884 // Update EXEC, save the original EXEC value to VCC.
2885 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2886 .addReg(CondReg, RegState::Kill);
2888 MRI.setSimpleHint(NewExec, CondReg);
2890 if (UseGPRIdxMode) {
2893 IdxReg = CurrentIdxReg;
2895 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2896 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2897 .addReg(CurrentIdxReg, RegState::Kill)
2900 unsigned IdxMode = IsIndirectSrc ?
2901 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2902 MachineInstr *SetOn =
2903 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2904 .addReg(IdxReg, RegState::Kill)
2906 SetOn->getOperand(3).setIsUndef();
2908 // Move index from VCC into M0
2910 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2911 .addReg(CurrentIdxReg, RegState::Kill);
2913 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2914 .addReg(CurrentIdxReg, RegState::Kill)
2919 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2920 MachineInstr *InsertPt =
2921 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2922 .addReg(AMDGPU::EXEC)
2925 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2928 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2929 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2932 return InsertPt->getIterator();
2935 // This has slightly sub-optimal regalloc when the source vector is killed by
2936 // the read. The register allocator does not understand that the kill is
2937 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2938 // subregister from it, using 1 more VGPR than necessary. This was saved when
2939 // this was expanded after register allocation.
2940 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2941 MachineBasicBlock &MBB,
2943 unsigned InitResultReg,
2947 bool IsIndirectSrc) {
2948 MachineFunction *MF = MBB.getParent();
2949 MachineRegisterInfo &MRI = MF->getRegInfo();
2950 const DebugLoc &DL = MI.getDebugLoc();
2951 MachineBasicBlock::iterator I(&MI);
2953 unsigned DstReg = MI.getOperand(0).getReg();
2954 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2955 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2957 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2959 // Save the EXEC mask
2960 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2961 .addReg(AMDGPU::EXEC);
2963 // To insert the loop we need to split the block. Move everything after this
2964 // point to a new block, and insert a new empty block between the two.
2965 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2966 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2967 MachineFunction::iterator MBBI(MBB);
2970 MF->insert(MBBI, LoopBB);
2971 MF->insert(MBBI, RemainderBB);
2973 LoopBB->addSuccessor(LoopBB);
2974 LoopBB->addSuccessor(RemainderBB);
2976 // Move the rest of the block into a new block.
2977 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2978 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2980 MBB.addSuccessor(LoopBB);
2982 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2984 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2985 InitResultReg, DstReg, PhiReg, TmpExec,
2986 Offset, UseGPRIdxMode, IsIndirectSrc);
2988 MachineBasicBlock::iterator First = RemainderBB->begin();
2989 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2995 // Returns subreg index, offset
2996 static std::pair<unsigned, int>
2997 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2998 const TargetRegisterClass *SuperRC,
3001 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3003 // Skip out of bounds offsets, or else we would end up using an undefined
3005 if (Offset >= NumElts || Offset < 0)
3006 return std::make_pair(AMDGPU::sub0, Offset);
3008 return std::make_pair(AMDGPU::sub0 + Offset, 0);
3011 // Return true if the index is an SGPR and was set.
3012 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3013 MachineRegisterInfo &MRI,
3017 bool IsIndirectSrc) {
3018 MachineBasicBlock *MBB = MI.getParent();
3019 const DebugLoc &DL = MI.getDebugLoc();
3020 MachineBasicBlock::iterator I(&MI);
3022 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3023 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3025 assert(Idx->getReg() != AMDGPU::NoRegister);
3027 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3030 if (UseGPRIdxMode) {
3031 unsigned IdxMode = IsIndirectSrc ?
3032 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
3034 MachineInstr *SetOn =
3035 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3039 SetOn->getOperand(3).setIsUndef();
3041 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3042 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3045 MachineInstr *SetOn =
3046 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3047 .addReg(Tmp, RegState::Kill)
3050 SetOn->getOperand(3).setIsUndef();
3057 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3060 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3068 // Control flow needs to be inserted if indexing with a VGPR.
3069 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3070 MachineBasicBlock &MBB,
3071 const GCNSubtarget &ST) {
3072 const SIInstrInfo *TII = ST.getInstrInfo();
3073 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3074 MachineFunction *MF = MBB.getParent();
3075 MachineRegisterInfo &MRI = MF->getRegInfo();
3077 unsigned Dst = MI.getOperand(0).getReg();
3078 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3079 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3081 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3084 std::tie(SubReg, Offset)
3085 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3087 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3089 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3090 MachineBasicBlock::iterator I(&MI);
3091 const DebugLoc &DL = MI.getDebugLoc();
3093 if (UseGPRIdxMode) {
3094 // TODO: Look at the uses to avoid the copy. This may require rescheduling
3095 // to avoid interfering with other uses, so probably requires a new
3096 // optimization pass.
3097 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3098 .addReg(SrcReg, RegState::Undef, SubReg)
3099 .addReg(SrcReg, RegState::Implicit)
3100 .addReg(AMDGPU::M0, RegState::Implicit);
3101 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3103 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3104 .addReg(SrcReg, RegState::Undef, SubReg)
3105 .addReg(SrcReg, RegState::Implicit);
3108 MI.eraseFromParent();
3113 const DebugLoc &DL = MI.getDebugLoc();
3114 MachineBasicBlock::iterator I(&MI);
3116 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3117 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3119 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3121 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3122 Offset, UseGPRIdxMode, true);
3123 MachineBasicBlock *LoopBB = InsPt->getParent();
3125 if (UseGPRIdxMode) {
3126 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3127 .addReg(SrcReg, RegState::Undef, SubReg)
3128 .addReg(SrcReg, RegState::Implicit)
3129 .addReg(AMDGPU::M0, RegState::Implicit);
3130 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3132 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3133 .addReg(SrcReg, RegState::Undef, SubReg)
3134 .addReg(SrcReg, RegState::Implicit);
3137 MI.eraseFromParent();
3142 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3143 const TargetRegisterClass *VecRC) {
3144 switch (TRI.getRegSizeInBits(*VecRC)) {
3146 return AMDGPU::V_MOVRELD_B32_V1;
3148 return AMDGPU::V_MOVRELD_B32_V2;
3149 case 128: // 16 bytes
3150 return AMDGPU::V_MOVRELD_B32_V4;
3151 case 256: // 32 bytes
3152 return AMDGPU::V_MOVRELD_B32_V8;
3153 case 512: // 64 bytes
3154 return AMDGPU::V_MOVRELD_B32_V16;
3156 llvm_unreachable("unsupported size for MOVRELD pseudos");
3160 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3161 MachineBasicBlock &MBB,
3162 const GCNSubtarget &ST) {
3163 const SIInstrInfo *TII = ST.getInstrInfo();
3164 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3165 MachineFunction *MF = MBB.getParent();
3166 MachineRegisterInfo &MRI = MF->getRegInfo();
3168 unsigned Dst = MI.getOperand(0).getReg();
3169 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3170 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3171 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3172 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3173 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3175 // This can be an immediate, but will be folded later.
3176 assert(Val->getReg());
3179 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3182 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3184 if (Idx->getReg() == AMDGPU::NoRegister) {
3185 MachineBasicBlock::iterator I(&MI);
3186 const DebugLoc &DL = MI.getDebugLoc();
3188 assert(Offset == 0);
3190 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3195 MI.eraseFromParent();
3199 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3200 MachineBasicBlock::iterator I(&MI);
3201 const DebugLoc &DL = MI.getDebugLoc();
3203 if (UseGPRIdxMode) {
3204 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3205 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3207 .addReg(Dst, RegState::ImplicitDefine)
3208 .addReg(SrcVec->getReg(), RegState::Implicit)
3209 .addReg(AMDGPU::M0, RegState::Implicit);
3211 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3213 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3215 BuildMI(MBB, I, DL, MovRelDesc)
3216 .addReg(Dst, RegState::Define)
3217 .addReg(SrcVec->getReg())
3219 .addImm(SubReg - AMDGPU::sub0);
3222 MI.eraseFromParent();
3227 MRI.clearKillFlags(Val->getReg());
3229 const DebugLoc &DL = MI.getDebugLoc();
3231 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3233 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3234 Offset, UseGPRIdxMode, false);
3235 MachineBasicBlock *LoopBB = InsPt->getParent();
3237 if (UseGPRIdxMode) {
3238 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3239 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3241 .addReg(Dst, RegState::ImplicitDefine)
3242 .addReg(PhiReg, RegState::Implicit)
3243 .addReg(AMDGPU::M0, RegState::Implicit);
3244 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3246 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3248 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3249 .addReg(Dst, RegState::Define)
3252 .addImm(SubReg - AMDGPU::sub0);
3255 MI.eraseFromParent();
3260 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3261 MachineInstr &MI, MachineBasicBlock *BB) const {
3263 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3264 MachineFunction *MF = BB->getParent();
3265 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3267 if (TII->isMIMG(MI)) {
3268 if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3269 report_fatal_error("missing mem operand from MIMG instruction");
3271 // Add a memoperand for mimg instructions so that they aren't assumed to
3272 // be ordered memory instuctions.
3277 switch (MI.getOpcode()) {
3278 case AMDGPU::S_ADD_U64_PSEUDO:
3279 case AMDGPU::S_SUB_U64_PSEUDO: {
3280 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3281 const DebugLoc &DL = MI.getDebugLoc();
3283 MachineOperand &Dest = MI.getOperand(0);
3284 MachineOperand &Src0 = MI.getOperand(1);
3285 MachineOperand &Src1 = MI.getOperand(2);
3287 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3288 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3290 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3291 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3292 &AMDGPU::SReg_32_XM0RegClass);
3293 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3294 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3295 &AMDGPU::SReg_32_XM0RegClass);
3297 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3298 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3299 &AMDGPU::SReg_32_XM0RegClass);
3300 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3301 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3302 &AMDGPU::SReg_32_XM0RegClass);
3304 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3306 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3307 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3308 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3311 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3314 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3316 .addImm(AMDGPU::sub0)
3318 .addImm(AMDGPU::sub1);
3319 MI.eraseFromParent();
3322 case AMDGPU::SI_INIT_M0: {
3323 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3324 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3325 .add(MI.getOperand(0));
3326 MI.eraseFromParent();
3329 case AMDGPU::SI_INIT_EXEC:
3330 // This should be before all vector instructions.
3331 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3333 .addImm(MI.getOperand(0).getImm());
3334 MI.eraseFromParent();
3337 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3338 // Extract the thread count from an SGPR input and set EXEC accordingly.
3339 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3341 // S_BFE_U32 count, input, {shift, 7}
3342 // S_BFM_B64 exec, count, 0
3343 // S_CMP_EQ_U32 count, 64
3344 // S_CMOV_B64 exec, -1
3345 MachineInstr *FirstMI = &*BB->begin();
3346 MachineRegisterInfo &MRI = MF->getRegInfo();
3347 unsigned InputReg = MI.getOperand(0).getReg();
3348 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3351 // Move the COPY of the input reg to the beginning, so that we can use it.
3352 for (auto I = BB->begin(); I != &MI; I++) {
3353 if (I->getOpcode() != TargetOpcode::COPY ||
3354 I->getOperand(0).getReg() != InputReg)
3358 FirstMI = &*++BB->begin();
3360 I->removeFromParent();
3361 BB->insert(FirstMI, &*I);
3369 // This should be before all vector instructions.
3370 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3372 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3373 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3377 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3378 .addReg(CountReg, RegState::Kill)
3380 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3383 MI.eraseFromParent();
3387 case AMDGPU::GET_GROUPSTATICSIZE: {
3388 DebugLoc DL = MI.getDebugLoc();
3389 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3390 .add(MI.getOperand(0))
3391 .addImm(MFI->getLDSSize());
3392 MI.eraseFromParent();
3395 case AMDGPU::SI_INDIRECT_SRC_V1:
3396 case AMDGPU::SI_INDIRECT_SRC_V2:
3397 case AMDGPU::SI_INDIRECT_SRC_V4:
3398 case AMDGPU::SI_INDIRECT_SRC_V8:
3399 case AMDGPU::SI_INDIRECT_SRC_V16:
3400 return emitIndirectSrc(MI, *BB, *getSubtarget());
3401 case AMDGPU::SI_INDIRECT_DST_V1:
3402 case AMDGPU::SI_INDIRECT_DST_V2:
3403 case AMDGPU::SI_INDIRECT_DST_V4:
3404 case AMDGPU::SI_INDIRECT_DST_V8:
3405 case AMDGPU::SI_INDIRECT_DST_V16:
3406 return emitIndirectDst(MI, *BB, *getSubtarget());
3407 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3408 case AMDGPU::SI_KILL_I1_PSEUDO:
3409 return splitKillBlock(MI, BB);
3410 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3411 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3413 unsigned Dst = MI.getOperand(0).getReg();
3414 unsigned Src0 = MI.getOperand(1).getReg();
3415 unsigned Src1 = MI.getOperand(2).getReg();
3416 const DebugLoc &DL = MI.getDebugLoc();
3417 unsigned SrcCond = MI.getOperand(3).getReg();
3419 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3420 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3421 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3423 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3425 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3426 .addReg(Src0, 0, AMDGPU::sub0)
3427 .addReg(Src1, 0, AMDGPU::sub0)
3428 .addReg(SrcCondCopy);
3429 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3430 .addReg(Src0, 0, AMDGPU::sub1)
3431 .addReg(Src1, 0, AMDGPU::sub1)
3432 .addReg(SrcCondCopy);
3434 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3436 .addImm(AMDGPU::sub0)
3438 .addImm(AMDGPU::sub1);
3439 MI.eraseFromParent();
3442 case AMDGPU::SI_BR_UNDEF: {
3443 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3444 const DebugLoc &DL = MI.getDebugLoc();
3445 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3446 .add(MI.getOperand(0));
3447 Br->getOperand(1).setIsUndef(true); // read undef SCC
3448 MI.eraseFromParent();
3451 case AMDGPU::ADJCALLSTACKUP:
3452 case AMDGPU::ADJCALLSTACKDOWN: {
3453 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3454 MachineInstrBuilder MIB(*MF, &MI);
3456 // Add an implicit use of the frame offset reg to prevent the restore copy
3457 // inserted after the call from being reorderd after stack operations in the
3458 // the caller's frame.
3459 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3460 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3461 .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3464 case AMDGPU::SI_CALL_ISEL:
3465 case AMDGPU::SI_TCRETURN_ISEL: {
3466 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3467 const DebugLoc &DL = MI.getDebugLoc();
3468 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3470 MachineRegisterInfo &MRI = MF->getRegInfo();
3471 unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3472 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3473 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3475 const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3477 MachineInstrBuilder MIB;
3478 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3479 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3480 .add(MI.getOperand(0))
3481 .addGlobalAddress(G);
3483 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3484 .add(MI.getOperand(0))
3485 .addGlobalAddress(G);
3487 // There is an additional imm operand for tcreturn, but it should be in the
3488 // right place already.
3491 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3492 MIB.add(MI.getOperand(I));
3494 MIB.cloneMemRefs(MI);
3495 MI.eraseFromParent();
3499 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3503 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3504 return isTypeLegal(VT.getScalarType());
3507 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3508 // This currently forces unfolding various combinations of fsub into fma with
3509 // free fneg'd operands. As long as we have fast FMA (controlled by
3510 // isFMAFasterThanFMulAndFAdd), we should perform these.
3512 // When fma is quarter rate, for f64 where add / sub are at best half rate,
3513 // most of these combines appear to be cycle neutral but save on instruction
3514 // count / code size.
3518 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3520 if (!VT.isVector()) {
3523 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3526 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3527 // TODO: Should i16 be used always if legal? For now it would force VALU
3529 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3532 // Answering this is somewhat tricky and depends on the specific device which
3533 // have different rates for fma or all f64 operations.
3535 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3536 // regardless of which device (although the number of cycles differs between
3537 // devices), so it is always profitable for f64.
3539 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3540 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3541 // which we can always do even without fused FP ops since it returns the same
3542 // result as the separate operations and since it is always full
3543 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3544 // however does not support denormals, so we do report fma as faster if we have
3545 // a fast fma device and require denormals.
3547 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3548 VT = VT.getScalarType();
3550 switch (VT.getSimpleVT().SimpleTy) {
3552 // This is as fast on some subtargets. However, we always have full rate f32
3553 // mad available which returns the same result as the separate operations
3554 // which we should prefer over fma. We can't use this if we want to support
3555 // denormals, so only report this in these cases.
3556 if (Subtarget->hasFP32Denormals())
3557 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3559 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3560 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3565 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3573 //===----------------------------------------------------------------------===//
3574 // Custom DAG Lowering Operations
3575 //===----------------------------------------------------------------------===//
3577 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3578 // wider vector type is legal.
3579 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3580 SelectionDAG &DAG) const {
3581 unsigned Opc = Op.getOpcode();
3582 EVT VT = Op.getValueType();
3583 assert(VT == MVT::v4f16);
3586 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3589 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3591 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3594 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3597 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3598 // wider vector type is legal.
3599 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3600 SelectionDAG &DAG) const {
3601 unsigned Opc = Op.getOpcode();
3602 EVT VT = Op.getValueType();
3603 assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3606 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3608 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3612 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3614 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3617 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3620 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3621 switch (Op.getOpcode()) {
3622 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3623 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3625 SDValue Result = LowerLOAD(Op, DAG);
3626 assert((!Result.getNode() ||
3627 Result.getNode()->getNumValues() == 2) &&
3628 "Load should return a value and a chain");
3634 return LowerTrig(Op, DAG);
3635 case ISD::SELECT: return LowerSELECT(Op, DAG);
3636 case ISD::FDIV: return LowerFDIV(Op, DAG);
3637 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3638 case ISD::STORE: return LowerSTORE(Op, DAG);
3639 case ISD::GlobalAddress: {
3640 MachineFunction &MF = DAG.getMachineFunction();
3641 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3642 return LowerGlobalAddress(MFI, Op, DAG);
3644 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3645 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3646 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3647 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3648 case ISD::INSERT_VECTOR_ELT:
3649 return lowerINSERT_VECTOR_ELT(Op, DAG);
3650 case ISD::EXTRACT_VECTOR_ELT:
3651 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3652 case ISD::BUILD_VECTOR:
3653 return lowerBUILD_VECTOR(Op, DAG);
3655 return lowerFP_ROUND(Op, DAG);
3657 return lowerTRAP(Op, DAG);
3658 case ISD::DEBUGTRAP:
3659 return lowerDEBUGTRAP(Op, DAG);
3662 case ISD::FCANONICALIZE:
3663 return splitUnaryVectorOp(Op, DAG);
3666 return lowerFMINNUM_FMAXNUM(Op, DAG);
3679 case ISD::FMINNUM_IEEE:
3680 case ISD::FMAXNUM_IEEE:
3681 return splitBinaryVectorOp(Op, DAG);
3686 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
3688 SelectionDAG &DAG, bool Unpacked) {
3689 if (!LoadVT.isVector())
3692 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3693 // Truncate to v2i16/v4i16.
3694 EVT IntLoadVT = LoadVT.changeTypeToInteger();
3696 // Workaround legalizer not scalarizing truncate after vector op
3697 // legalization byt not creating intermediate vector trunc.
3698 SmallVector<SDValue, 4> Elts;
3699 DAG.ExtractVectorElements(Result, Elts);
3700 for (SDValue &Elt : Elts)
3701 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3703 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3705 // Bitcast to original type (v2f16/v4f16).
3706 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3709 // Cast back to the original packed type.
3710 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3713 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
3716 ArrayRef<SDValue> Ops,
3717 bool IsIntrinsic) const {
3720 bool Unpacked = Subtarget->hasUnpackedD16VMem();
3721 EVT LoadVT = M->getValueType(0);
3723 EVT EquivLoadVT = LoadVT;
3724 if (Unpacked && LoadVT.isVector()) {
3725 EquivLoadVT = LoadVT.isVector() ?
3726 EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3727 LoadVT.getVectorNumElements()) : LoadVT;
3730 // Change from v4f16/v2f16 to EquivLoadVT.
3731 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3734 = DAG.getMemIntrinsicNode(
3735 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
3736 VTList, Ops, M->getMemoryVT(),
3737 M->getMemOperand());
3738 if (!Unpacked) // Just adjusted the opcode.
3741 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
3743 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
3746 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
3747 SDNode *N, SelectionDAG &DAG) {
3748 EVT VT = N->getValueType(0);
3749 const auto *CD = dyn_cast<ConstantSDNode>(N->getOperand(3));
3751 return DAG.getUNDEF(VT);
3753 int CondCode = CD->getSExtValue();
3754 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
3755 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
3756 return DAG.getUNDEF(VT);
3758 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
3761 SDValue LHS = N->getOperand(1);
3762 SDValue RHS = N->getOperand(2);
3766 EVT CmpVT = LHS.getValueType();
3767 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
3768 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
3769 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3770 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
3771 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
3774 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
3776 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, LHS, RHS,
3777 DAG.getCondCode(CCOpcode));
3780 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
3781 SDNode *N, SelectionDAG &DAG) {
3782 EVT VT = N->getValueType(0);
3783 const auto *CD = dyn_cast<ConstantSDNode>(N->getOperand(3));
3785 return DAG.getUNDEF(VT);
3787 int CondCode = CD->getSExtValue();
3788 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
3789 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
3790 return DAG.getUNDEF(VT);
3793 SDValue Src0 = N->getOperand(1);
3794 SDValue Src1 = N->getOperand(2);
3795 EVT CmpVT = Src0.getValueType();
3798 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
3799 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3800 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3803 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
3804 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
3805 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src0,
3806 Src1, DAG.getCondCode(CCOpcode));
3809 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3810 SmallVectorImpl<SDValue> &Results,
3811 SelectionDAG &DAG) const {
3812 switch (N->getOpcode()) {
3813 case ISD::INSERT_VECTOR_ELT: {
3814 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3815 Results.push_back(Res);
3818 case ISD::EXTRACT_VECTOR_ELT: {
3819 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3820 Results.push_back(Res);
3823 case ISD::INTRINSIC_WO_CHAIN: {
3824 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3826 case Intrinsic::amdgcn_cvt_pkrtz: {
3827 SDValue Src0 = N->getOperand(1);
3828 SDValue Src1 = N->getOperand(2);
3830 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3832 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3835 case Intrinsic::amdgcn_cvt_pknorm_i16:
3836 case Intrinsic::amdgcn_cvt_pknorm_u16:
3837 case Intrinsic::amdgcn_cvt_pk_i16:
3838 case Intrinsic::amdgcn_cvt_pk_u16: {
3839 SDValue Src0 = N->getOperand(1);
3840 SDValue Src1 = N->getOperand(2);
3844 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3845 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
3846 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3847 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
3848 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3849 Opcode = AMDGPUISD::CVT_PK_I16_I32;
3851 Opcode = AMDGPUISD::CVT_PK_U16_U32;
3853 EVT VT = N->getValueType(0);
3854 if (isTypeLegal(VT))
3855 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
3857 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
3858 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
3865 case ISD::INTRINSIC_W_CHAIN: {
3866 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
3867 Results.push_back(Res);
3868 Results.push_back(Res.getValue(1));
3876 EVT VT = N->getValueType(0);
3877 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3878 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3879 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3881 EVT SelectVT = NewVT;
3882 if (NewVT.bitsLT(MVT::i32)) {
3883 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3884 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3885 SelectVT = MVT::i32;
3888 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3889 N->getOperand(0), LHS, RHS);
3891 if (NewVT != SelectVT)
3892 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3893 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3897 if (N->getValueType(0) != MVT::v2f16)
3901 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3903 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
3905 DAG.getConstant(0x80008000, SL, MVT::i32));
3906 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3910 if (N->getValueType(0) != MVT::v2f16)
3914 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3916 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
3918 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
3919 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3927 /// Helper function for LowerBRCOND
3928 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3930 SDNode *Parent = Value.getNode();
3931 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3934 if (I.getUse().get() != Value)
3937 if (I->getOpcode() == Opcode)
3943 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3944 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3945 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3946 case Intrinsic::amdgcn_if:
3947 return AMDGPUISD::IF;
3948 case Intrinsic::amdgcn_else:
3949 return AMDGPUISD::ELSE;
3950 case Intrinsic::amdgcn_loop:
3951 return AMDGPUISD::LOOP;
3952 case Intrinsic::amdgcn_end_cf:
3953 llvm_unreachable("should not occur");
3959 // break, if_break, else_break are all only used as inputs to loop, not
3960 // directly as branch conditions.
3964 void SITargetLowering::createDebuggerPrologueStackObjects(
3965 MachineFunction &MF) const {
3966 // Create stack objects that are used for emitting debugger prologue.
3968 // Debugger prologue writes work group IDs and work item IDs to scratch memory
3969 // at fixed location in the following format:
3970 // offset 0: work group ID x
3971 // offset 4: work group ID y
3972 // offset 8: work group ID z
3973 // offset 16: work item ID x
3974 // offset 20: work item ID y
3975 // offset 24: work item ID z
3976 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3979 // For each dimension:
3980 for (unsigned i = 0; i < 3; ++i) {
3981 // Create fixed stack object for work group ID.
3982 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
3983 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
3984 // Create fixed stack object for work item ID.
3985 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
3986 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
3990 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
3991 const Triple &TT = getTargetMachine().getTargetTriple();
3992 return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
3993 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
3994 AMDGPU::shouldEmitConstantsToTextSection(TT);
3997 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
3998 return (GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
3999 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4000 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4001 !shouldEmitFixup(GV) &&
4002 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4005 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4006 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4009 /// This transforms the control flow intrinsics to get the branch destination as
4010 /// last parameter, also switches branch target with BR if the need arise
4011 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4012 SelectionDAG &DAG) const {
4015 SDNode *Intr = BRCOND.getOperand(1).getNode();
4016 SDValue Target = BRCOND.getOperand(2);
4017 SDNode *BR = nullptr;
4018 SDNode *SetCC = nullptr;
4020 if (Intr->getOpcode() == ISD::SETCC) {
4021 // As long as we negate the condition everything is fine
4023 Intr = SetCC->getOperand(0).getNode();
4026 // Get the target from BR if we don't negate the condition
4027 BR = findUser(BRCOND, ISD::BR);
4028 Target = BR->getOperand(1);
4031 // FIXME: This changes the types of the intrinsics instead of introducing new
4032 // nodes with the correct types.
4033 // e.g. llvm.amdgcn.loop
4035 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4036 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4038 unsigned CFNode = isCFIntrinsic(Intr);
4040 // This is a uniform branch so we don't need to legalize.
4044 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4045 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4048 (SetCC->getConstantOperandVal(1) == 1 &&
4049 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4052 // operands of the new intrinsic call
4053 SmallVector<SDValue, 4> Ops;
4055 Ops.push_back(BRCOND.getOperand(0));
4057 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
4058 Ops.push_back(Target);
4060 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4062 // build the new intrinsic call
4063 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4068 BRCOND.getOperand(0)
4071 Result = DAG.getMergeValues(Ops, DL).getNode();
4075 // Give the branch instruction our target
4078 BRCOND.getOperand(2)
4080 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4081 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4082 BR = NewBR.getNode();
4085 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4087 // Copy the intrinsic results to registers
4088 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4089 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4093 Chain = DAG.getCopyToReg(
4095 CopyToReg->getOperand(1),
4096 SDValue(Result, i - 1),
4099 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4102 // Remove the old intrinsic from the chain
4103 DAG.ReplaceAllUsesOfValueWith(
4104 SDValue(Intr, Intr->getNumValues() - 1),
4105 Intr->getOperand(0));
4110 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4114 return Op.getValueType().bitsLE(VT) ?
4115 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4116 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4119 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4120 assert(Op.getValueType() == MVT::f16 &&
4121 "Do not know how to custom lower FP_ROUND for non-f16 type");
4123 SDValue Src = Op.getOperand(0);
4124 EVT SrcVT = Src.getValueType();
4125 if (SrcVT != MVT::f64)
4130 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4131 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4132 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4135 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4136 SelectionDAG &DAG) const {
4137 EVT VT = Op.getValueType();
4138 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
4140 // FIXME: Assert during eslection that this is only selected for
4141 // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4142 // mode functions, but this happens to be OK since it's only done in cases
4143 // where there is known no sNaN.
4145 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4147 if (VT == MVT::v4f16)
4148 return splitBinaryVectorOp(Op, DAG);
4152 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4154 SDValue Chain = Op.getOperand(0);
4156 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4157 !Subtarget->isTrapHandlerEnabled())
4158 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4160 MachineFunction &MF = DAG.getMachineFunction();
4161 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4162 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4163 assert(UserSGPR != AMDGPU::NoRegister);
4164 SDValue QueuePtr = CreateLiveInRegister(
4165 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4166 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4167 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4168 QueuePtr, SDValue());
4171 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4175 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4178 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4180 SDValue Chain = Op.getOperand(0);
4181 MachineFunction &MF = DAG.getMachineFunction();
4183 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4184 !Subtarget->isTrapHandlerEnabled()) {
4185 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4186 "debugtrap handler not supported",
4189 LLVMContext &Ctx = MF.getFunction().getContext();
4190 Ctx.diagnose(NoTrap);
4196 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4198 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4201 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4202 SelectionDAG &DAG) const {
4203 // FIXME: Use inline constants (src_{shared, private}_base) instead.
4204 if (Subtarget->hasApertureRegs()) {
4205 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4206 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4207 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4208 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4209 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4210 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4212 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4213 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4214 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4216 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4217 SDValue ApertureReg = SDValue(
4218 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4219 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4220 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4223 MachineFunction &MF = DAG.getMachineFunction();
4224 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4225 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4226 assert(UserSGPR != AMDGPU::NoRegister);
4228 SDValue QueuePtr = CreateLiveInRegister(
4229 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4231 // Offset into amd_queue_t for group_segment_aperture_base_hi /
4232 // private_segment_aperture_base_hi.
4233 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4235 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4237 // TODO: Use custom target PseudoSourceValue.
4238 // TODO: We should use the value from the IR intrinsic call, but it might not
4239 // be available and how do we get it?
4240 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4241 AMDGPUAS::CONSTANT_ADDRESS));
4243 MachinePointerInfo PtrInfo(V, StructOffset);
4244 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4245 MinAlign(64, StructOffset),
4246 MachineMemOperand::MODereferenceable |
4247 MachineMemOperand::MOInvariant);
4250 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4251 SelectionDAG &DAG) const {
4253 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4255 SDValue Src = ASC->getOperand(0);
4256 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4258 const AMDGPUTargetMachine &TM =
4259 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4261 // flat -> local/private
4262 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4263 unsigned DestAS = ASC->getDestAddressSpace();
4265 if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4266 DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4267 unsigned NullVal = TM.getNullPointerValue(DestAS);
4268 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4269 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4270 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4272 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4273 NonNull, Ptr, SegmentNullPtr);
4277 // local/private -> flat
4278 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4279 unsigned SrcAS = ASC->getSrcAddressSpace();
4281 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4282 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4283 unsigned NullVal = TM.getNullPointerValue(SrcAS);
4284 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4287 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4289 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4291 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4293 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4294 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4299 // global <-> flat are no-ops and never emitted.
4301 const MachineFunction &MF = DAG.getMachineFunction();
4302 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4303 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4304 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4306 return DAG.getUNDEF(ASC->getValueType(0));
4309 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4310 SelectionDAG &DAG) const {
4311 SDValue Vec = Op.getOperand(0);
4312 SDValue InsVal = Op.getOperand(1);
4313 SDValue Idx = Op.getOperand(2);
4314 EVT VecVT = Vec.getValueType();
4315 EVT EltVT = VecVT.getVectorElementType();
4316 unsigned VecSize = VecVT.getSizeInBits();
4317 unsigned EltSize = EltVT.getSizeInBits();
4320 assert(VecSize <= 64);
4322 unsigned NumElts = VecVT.getVectorNumElements();
4324 auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4326 if (NumElts == 4 && EltSize == 16 && KIdx) {
4327 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4329 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4330 DAG.getConstant(0, SL, MVT::i32));
4331 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4332 DAG.getConstant(1, SL, MVT::i32));
4334 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4335 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4337 unsigned Idx = KIdx->getZExtValue();
4338 bool InsertLo = Idx < 2;
4339 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4340 InsertLo ? LoVec : HiVec,
4341 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4342 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4344 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4346 SDValue Concat = InsertLo ?
4347 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4348 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4350 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4353 if (isa<ConstantSDNode>(Idx))
4356 MVT IntVT = MVT::getIntegerVT(VecSize);
4358 // Avoid stack access for dynamic indexing.
4359 SDValue Val = InsVal;
4360 if (InsVal.getValueType() == MVT::f16)
4361 Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal);
4363 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4364 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Val);
4366 assert(isPowerOf2_32(EltSize));
4367 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4369 // Convert vector index to bit-index.
4370 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4372 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4373 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4374 DAG.getConstant(0xffff, SL, IntVT),
4377 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4378 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4379 DAG.getNOT(SL, BFM, IntVT), BCVec);
4381 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4382 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4385 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4386 SelectionDAG &DAG) const {
4389 EVT ResultVT = Op.getValueType();
4390 SDValue Vec = Op.getOperand(0);
4391 SDValue Idx = Op.getOperand(1);
4392 EVT VecVT = Vec.getValueType();
4393 unsigned VecSize = VecVT.getSizeInBits();
4394 EVT EltVT = VecVT.getVectorElementType();
4395 assert(VecSize <= 64);
4397 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4399 // Make sure we do any optimizations that will make it easier to fold
4400 // source modifiers before obscuring it with bit operations.
4402 // XXX - Why doesn't this get called when vector_shuffle is expanded?
4403 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4406 unsigned EltSize = EltVT.getSizeInBits();
4407 assert(isPowerOf2_32(EltSize));
4409 MVT IntVT = MVT::getIntegerVT(VecSize);
4410 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4412 // Convert vector index to bit-index (* EltSize)
4413 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4415 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4416 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4418 if (ResultVT == MVT::f16) {
4419 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4420 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4423 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4426 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4427 SelectionDAG &DAG) const {
4429 EVT VT = Op.getValueType();
4431 if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4432 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4434 // Turn into pair of packed build_vectors.
4435 // TODO: Special case for constants that can be materialized with s_mov_b64.
4436 SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4437 { Op.getOperand(0), Op.getOperand(1) });
4438 SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4439 { Op.getOperand(2), Op.getOperand(3) });
4441 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4442 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4444 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4445 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4448 assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4449 assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4451 SDValue Lo = Op.getOperand(0);
4452 SDValue Hi = Op.getOperand(1);
4454 // Avoid adding defined bits with the zero_extend.
4456 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4457 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4458 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4461 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4462 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4464 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4465 DAG.getConstant(16, SL, MVT::i32));
4467 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4469 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4470 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4472 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4473 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4477 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4478 // We can fold offsets for anything that doesn't require a GOT relocation.
4479 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4480 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4481 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4482 !shouldEmitGOTReloc(GA->getGlobal());
4486 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4487 const SDLoc &DL, unsigned Offset, EVT PtrVT,
4488 unsigned GAFlags = SIInstrInfo::MO_NONE) {
4489 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4490 // lowered to the following code sequence:
4492 // For constant address space:
4493 // s_getpc_b64 s[0:1]
4494 // s_add_u32 s0, s0, $symbol
4495 // s_addc_u32 s1, s1, 0
4497 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4498 // a fixup or relocation is emitted to replace $symbol with a literal
4499 // constant, which is a pc-relative offset from the encoding of the $symbol
4500 // operand to the global variable.
4502 // For global address space:
4503 // s_getpc_b64 s[0:1]
4504 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4505 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4507 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4508 // fixups or relocations are emitted to replace $symbol@*@lo and
4509 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4510 // which is a 64-bit pc-relative offset from the encoding of the $symbol
4511 // operand to the global variable.
4513 // What we want here is an offset from the value returned by s_getpc
4514 // (which is the address of the s_add_u32 instruction) to the global
4515 // variable, but since the encoding of $symbol starts 4 bytes after the start
4516 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4517 // small. This requires us to add 4 to the global variable offset in order to
4518 // compute the correct address.
4519 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4521 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4522 GAFlags == SIInstrInfo::MO_NONE ?
4523 GAFlags : GAFlags + 1);
4524 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4527 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4529 SelectionDAG &DAG) const {
4530 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4531 const GlobalValue *GV = GSD->getGlobal();
4532 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
4533 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
4534 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
4535 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4538 EVT PtrVT = Op.getValueType();
4540 // FIXME: Should not make address space based decisions here.
4541 if (shouldEmitFixup(GV))
4542 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4543 else if (shouldEmitPCReloc(GV))
4544 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4545 SIInstrInfo::MO_REL32);
4547 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4548 SIInstrInfo::MO_GOTPCREL32);
4550 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4551 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
4552 const DataLayout &DataLayout = DAG.getDataLayout();
4553 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4554 MachinePointerInfo PtrInfo
4555 = MachinePointerInfo::getGOT(DAG.getMachineFunction());
4557 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4558 MachineMemOperand::MODereferenceable |
4559 MachineMemOperand::MOInvariant);
4562 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4563 const SDLoc &DL, SDValue V) const {
4564 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4565 // the destination register.
4567 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4568 // so we will end up with redundant moves to m0.
4570 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4572 // A Null SDValue creates a glue result.
4573 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4575 return SDValue(M0, 0);
4578 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4581 unsigned Offset) const {
4583 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4584 DAG.getEntryNode(), Offset, 4, false);
4585 // The local size values will have the hi 16-bits as zero.
4586 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4587 DAG.getValueType(VT));
4590 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4592 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4593 "non-hsa intrinsic with hsa target",
4595 DAG.getContext()->diagnose(BadIntrin);
4596 return DAG.getUNDEF(VT);
4599 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4601 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4602 "intrinsic not supported on subtarget",
4604 DAG.getContext()->diagnose(BadIntrin);
4605 return DAG.getUNDEF(VT);
4608 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
4609 ArrayRef<SDValue> Elts) {
4610 assert(!Elts.empty());
4614 if (Elts.size() == 1) {
4617 } else if (Elts.size() == 2) {
4620 } else if (Elts.size() <= 4) {
4623 } else if (Elts.size() <= 8) {
4627 assert(Elts.size() <= 16);
4632 SmallVector<SDValue, 16> VecElts(NumElts);
4633 for (unsigned i = 0; i < Elts.size(); ++i) {
4634 SDValue Elt = Elts[i];
4635 if (Elt.getValueType() != MVT::f32)
4636 Elt = DAG.getBitcast(MVT::f32, Elt);
4639 for (unsigned i = Elts.size(); i < NumElts; ++i)
4640 VecElts[i] = DAG.getUNDEF(MVT::f32);
4644 return DAG.getBuildVector(Type, DL, VecElts);
4647 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
4648 SDValue *GLC, SDValue *SLC) {
4649 auto CachePolicyConst = dyn_cast<ConstantSDNode>(CachePolicy.getNode());
4650 if (!CachePolicyConst)
4653 uint64_t Value = CachePolicyConst->getZExtValue();
4654 SDLoc DL(CachePolicy);
4656 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4657 Value &= ~(uint64_t)0x1;
4660 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4661 Value &= ~(uint64_t)0x2;
4667 // Re-construct the required return value for a image load intrinsic.
4668 // This is more complicated due to the optional use TexFailCtrl which means the required
4669 // return type is an aggregate
4670 static SDValue constructRetValue(SelectionDAG &DAG,
4671 MachineSDNode *Result,
4672 ArrayRef<EVT> ResultTypes,
4673 bool IsTexFail, bool Unpacked, bool IsD16,
4674 int DMaskPop, int NumVDataDwords,
4675 const SDLoc &DL, LLVMContext &Context) {
4676 // Determine the required return type. This is the same regardless of IsTexFail flag
4677 EVT ReqRetVT = ResultTypes[0];
4678 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
4679 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
4680 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
4681 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
4685 // Extract data part of the result
4686 // Bitcast the result to the same type as the required return type
4688 if (IsD16 && !Unpacked)
4689 NumElts = NumVDataDwords << 1;
4691 NumElts = NumVDataDwords;
4693 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
4696 // Special case for v8f16. Rather than add support for this, use v4i32 to
4697 // extract the data elements
4698 bool V8F16Special = false;
4699 if (CastVT == MVT::v8f16) {
4700 CastVT = MVT::v4i32;
4702 ReqRetNumElts >>= 1;
4703 V8F16Special = true;
4707 SDValue N = SDValue(Result, 0);
4708 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
4710 // Iterate over the result
4711 SmallVector<SDValue, 4> BVElts;
4713 if (CastVT.isVector()) {
4714 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
4716 BVElts.push_back(CastRes);
4718 int ExtraElts = ReqRetNumElts - DMaskPop;
4720 BVElts.push_back(DAG.getUNDEF(AdjEltVT));
4723 if (ReqRetNumElts > 1) {
4724 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
4725 if (IsD16 && Unpacked)
4726 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
4730 PreTFCRes = BVElts[0];
4734 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
4737 if (Result->getNumValues() > 1)
4738 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
4743 // Extract the TexFail result and insert into aggregate return
4744 SmallVector<SDValue, 1> TFCElt;
4745 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
4746 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
4747 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
4750 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
4751 SDValue *LWE, bool &IsTexFail) {
4752 auto TexFailCtrlConst = dyn_cast<ConstantSDNode>(TexFailCtrl.getNode());
4753 if (!TexFailCtrlConst)
4756 uint64_t Value = TexFailCtrlConst->getZExtValue();
4761 SDLoc DL(TexFailCtrlConst);
4762 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4763 Value &= ~(uint64_t)0x1;
4764 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4765 Value &= ~(uint64_t)0x2;
4770 SDValue SITargetLowering::lowerImage(SDValue Op,
4771 const AMDGPU::ImageDimIntrinsicInfo *Intr,
4772 SelectionDAG &DAG) const {
4774 MachineFunction &MF = DAG.getMachineFunction();
4775 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
4776 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4777 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
4778 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
4779 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
4780 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
4781 unsigned IntrOpcode = Intr->BaseOpcode;
4783 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
4784 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
4789 bool AdjustRetType = false;
4791 unsigned AddrIdx; // Index of first address argument
4793 unsigned DMaskLanes = 0;
4795 if (BaseOpcode->Atomic) {
4796 VData = Op.getOperand(2);
4798 bool Is64Bit = VData.getValueType() == MVT::i64;
4799 if (BaseOpcode->AtomicX2) {
4800 SDValue VData2 = Op.getOperand(3);
4801 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
4804 VData = DAG.getBitcast(MVT::v4i32, VData);
4806 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
4807 DMask = Is64Bit ? 0xf : 0x3;
4808 NumVDataDwords = Is64Bit ? 4 : 2;
4811 DMask = Is64Bit ? 0x3 : 0x1;
4812 NumVDataDwords = Is64Bit ? 2 : 1;
4816 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
4817 auto DMaskConst = dyn_cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
4820 DMask = DMaskConst->getZExtValue();
4821 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
4823 if (BaseOpcode->Store) {
4824 VData = Op.getOperand(2);
4826 MVT StoreVT = VData.getSimpleValueType();
4827 if (StoreVT.getScalarType() == MVT::f16) {
4828 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4829 !BaseOpcode->HasD16)
4830 return Op; // D16 is unsupported for this instruction
4833 VData = handleD16VData(VData, DAG);
4836 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
4838 // Work out the num dwords based on the dmask popcount and underlying type
4839 // and whether packing is supported.
4840 MVT LoadVT = ResultTypes[0].getSimpleVT();
4841 if (LoadVT.getScalarType() == MVT::f16) {
4842 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4843 !BaseOpcode->HasD16)
4844 return Op; // D16 is unsupported for this instruction
4849 // Confirm that the return type is large enough for the dmask specified
4850 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
4851 (!LoadVT.isVector() && DMaskLanes > 1))
4854 if (IsD16 && !Subtarget->hasUnpackedD16VMem())
4855 NumVDataDwords = (DMaskLanes + 1) / 2;
4857 NumVDataDwords = DMaskLanes;
4859 AdjustRetType = true;
4862 AddrIdx = DMaskIdx + 1;
4865 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
4866 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
4867 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
4868 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
4870 unsigned NumMIVAddrs = NumVAddrs;
4872 SmallVector<SDValue, 4> VAddrs;
4874 // Optimize _L to _LZ when _L is zero
4875 if (LZMappingInfo) {
4876 if (auto ConstantLod =
4877 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
4878 if (ConstantLod->isZero() || ConstantLod->isNegative()) {
4879 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l
4880 NumMIVAddrs--; // remove 'lod'
4885 // Check for 16 bit addresses and pack if true.
4886 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
4887 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
4888 const MVT VAddrScalarVT = VAddrVT.getScalarType();
4889 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
4890 ST->hasFeature(AMDGPU::FeatureR128A16)) {
4892 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
4893 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
4894 SDValue AddrLo, AddrHi;
4895 // Push back extra arguments.
4897 AddrLo = Op.getOperand(i);
4899 AddrLo = Op.getOperand(i);
4900 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
4901 // in 1D, derivatives dx/dh and dx/dv are packed with undef.
4902 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
4903 ((NumGradients / 2) % 2 == 1 &&
4904 (i == DimIdx + (NumGradients / 2) - 1 ||
4905 i == DimIdx + NumGradients - 1))) {
4906 AddrHi = DAG.getUNDEF(MVT::f16);
4908 AddrHi = Op.getOperand(i + 1);
4911 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
4913 AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
4915 VAddrs.push_back(AddrLo);
4918 for (unsigned i = 0; i < NumMIVAddrs; ++i)
4919 VAddrs.push_back(Op.getOperand(AddrIdx + i));
4922 SDValue VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
4924 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
4925 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
4926 unsigned CtrlIdx; // Index of texfailctrl argument
4928 if (!BaseOpcode->Sampler) {
4930 CtrlIdx = AddrIdx + NumVAddrs + 1;
4933 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
4937 Unorm = UnormConst->getZExtValue() ? True : False;
4938 CtrlIdx = AddrIdx + NumVAddrs + 3;
4943 SDValue TexFail = Op.getOperand(CtrlIdx);
4944 bool IsTexFail = false;
4945 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
4950 // Expecting to get an error flag since TFC is on - and dmask is 0
4951 // Force dmask to be at least 1 otherwise the instruction will fail
4956 NumVDataDwords += 1;
4957 AdjustRetType = true;
4960 // Has something earlier tagged that the return type needs adjusting
4961 // This happens if the instruction is a load or has set TexFailCtrl flags
4962 if (AdjustRetType) {
4963 // NumVDataDwords reflects the true number of dwords required in the return type
4964 if (DMaskLanes == 0 && !BaseOpcode->Store) {
4965 // This is a no-op load. This can be eliminated
4966 SDValue Undef = DAG.getUNDEF(Op.getValueType());
4967 if (isa<MemSDNode>(Op))
4968 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
4972 // Have to use a power of 2 number of dwords
4973 NumVDataDwords = 1 << Log2_32_Ceil(NumVDataDwords);
4975 EVT NewVT = NumVDataDwords > 1 ?
4976 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
4979 ResultTypes[0] = NewVT;
4980 if (ResultTypes.size() == 3) {
4981 // Original result was aggregate type used for TexFailCtrl results
4982 // The actual instruction returns as a vector type which has now been
4983 // created. Remove the aggregate result.
4984 ResultTypes.erase(&ResultTypes[1]);
4990 if (BaseOpcode->Atomic) {
4991 GLC = True; // TODO no-return optimization
4992 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC))
4995 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC))
4999 SmallVector<SDValue, 14> Ops;
5000 if (BaseOpcode->Store || BaseOpcode->Atomic)
5001 Ops.push_back(VData); // vdata
5002 Ops.push_back(VAddr);
5003 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5004 if (BaseOpcode->Sampler)
5005 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5006 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5007 Ops.push_back(Unorm);
5010 Ops.push_back(IsA16 && // a16 or r128
5011 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5012 Ops.push_back(TFE); // tfe
5013 Ops.push_back(LWE); // lwe
5014 Ops.push_back(DimInfo->DA ? True : False);
5015 if (BaseOpcode->HasD16)
5016 Ops.push_back(IsD16 ? True : False);
5017 if (isa<MemSDNode>(Op))
5018 Ops.push_back(Op.getOperand(0)); // chain
5020 int NumVAddrDwords = VAddr.getValueType().getSizeInBits() / 32;
5023 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5024 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5025 NumVDataDwords, NumVAddrDwords);
5027 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5028 NumVDataDwords, NumVAddrDwords);
5029 assert(Opcode != -1);
5031 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5032 if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5033 MachineMemOperand *MemRef = MemOp->getMemOperand();
5034 DAG.setNodeMemRefs(NewNode, {MemRef});
5037 if (BaseOpcode->AtomicX2) {
5038 SmallVector<SDValue, 1> Elt;
5039 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5040 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5041 } else if (!BaseOpcode->Store) {
5042 return constructRetValue(DAG, NewNode,
5043 OrigResultTypes, IsTexFail,
5044 Subtarget->hasUnpackedD16VMem(), IsD16,
5045 DMaskLanes, NumVDataDwords, DL,
5049 return SDValue(NewNode, 0);
5052 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5053 SDValue Offset, SDValue GLC,
5054 SelectionDAG &DAG) const {
5055 MachineFunction &MF = DAG.getMachineFunction();
5056 MachineMemOperand *MMO = MF.getMachineMemOperand(
5057 MachinePointerInfo(),
5058 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5059 MachineMemOperand::MOInvariant,
5060 VT.getStoreSize(), VT.getStoreSize());
5062 if (!Offset->isDivergent()) {
5068 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5069 DAG.getVTList(VT), Ops, VT, MMO);
5072 // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5073 // assume that the buffer is unswizzled.
5074 SmallVector<SDValue, 4> Loads;
5075 unsigned NumLoads = 1;
5076 MVT LoadVT = VT.getSimpleVT();
5077 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5078 assert((LoadVT.getScalarType() == MVT::i32 ||
5079 LoadVT.getScalarType() == MVT::f32) &&
5080 isPowerOf2_32(NumElts));
5082 if (NumElts == 8 || NumElts == 16) {
5083 NumLoads = NumElts == 16 ? 4 : 2;
5084 LoadVT = MVT::v4i32;
5087 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5088 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5090 DAG.getEntryNode(), // Chain
5092 DAG.getConstant(0, DL, MVT::i32), // vindex
5096 DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5097 DAG.getConstant(0, DL, MVT::i1), // idxen
5100 // Use the alignment to ensure that the required offsets will fit into the
5101 // immediate offsets.
5102 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5104 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5105 for (unsigned i = 0; i < NumLoads; ++i) {
5106 Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32);
5107 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
5111 if (VT == MVT::v8i32 || VT == MVT::v16i32)
5112 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5117 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5118 SelectionDAG &DAG) const {
5119 MachineFunction &MF = DAG.getMachineFunction();
5120 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5122 EVT VT = Op.getValueType();
5124 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5126 // TODO: Should this propagate fast-math-flags?
5128 switch (IntrinsicID) {
5129 case Intrinsic::amdgcn_implicit_buffer_ptr: {
5130 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5131 return emitNonHSAIntrinsicError(DAG, DL, VT);
5132 return getPreloadedValue(DAG, *MFI, VT,
5133 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5135 case Intrinsic::amdgcn_dispatch_ptr:
5136 case Intrinsic::amdgcn_queue_ptr: {
5137 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5138 DiagnosticInfoUnsupported BadIntrin(
5139 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5141 DAG.getContext()->diagnose(BadIntrin);
5142 return DAG.getUNDEF(VT);
5145 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5146 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5147 return getPreloadedValue(DAG, *MFI, VT, RegID);
5149 case Intrinsic::amdgcn_implicitarg_ptr: {
5150 if (MFI->isEntryFunction())
5151 return getImplicitArgPtr(DAG, DL);
5152 return getPreloadedValue(DAG, *MFI, VT,
5153 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5155 case Intrinsic::amdgcn_kernarg_segment_ptr: {
5156 return getPreloadedValue(DAG, *MFI, VT,
5157 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5159 case Intrinsic::amdgcn_dispatch_id: {
5160 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5162 case Intrinsic::amdgcn_rcp:
5163 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5164 case Intrinsic::amdgcn_rsq:
5165 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5166 case Intrinsic::amdgcn_rsq_legacy:
5167 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5168 return emitRemovedIntrinsicError(DAG, DL, VT);
5170 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5171 case Intrinsic::amdgcn_rcp_legacy:
5172 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5173 return emitRemovedIntrinsicError(DAG, DL, VT);
5174 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5175 case Intrinsic::amdgcn_rsq_clamp: {
5176 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5177 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5179 Type *Type = VT.getTypeForEVT(*DAG.getContext());
5180 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5181 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5183 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5184 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5185 DAG.getConstantFP(Max, DL, VT));
5186 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5187 DAG.getConstantFP(Min, DL, VT));
5189 case Intrinsic::r600_read_ngroups_x:
5190 if (Subtarget->isAmdHsaOS())
5191 return emitNonHSAIntrinsicError(DAG, DL, VT);
5193 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5194 SI::KernelInputOffsets::NGROUPS_X, 4, false);
5195 case Intrinsic::r600_read_ngroups_y:
5196 if (Subtarget->isAmdHsaOS())
5197 return emitNonHSAIntrinsicError(DAG, DL, VT);
5199 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5200 SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5201 case Intrinsic::r600_read_ngroups_z:
5202 if (Subtarget->isAmdHsaOS())
5203 return emitNonHSAIntrinsicError(DAG, DL, VT);
5205 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5206 SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5207 case Intrinsic::r600_read_global_size_x:
5208 if (Subtarget->isAmdHsaOS())
5209 return emitNonHSAIntrinsicError(DAG, DL, VT);
5211 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5212 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5213 case Intrinsic::r600_read_global_size_y:
5214 if (Subtarget->isAmdHsaOS())
5215 return emitNonHSAIntrinsicError(DAG, DL, VT);
5217 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5218 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5219 case Intrinsic::r600_read_global_size_z:
5220 if (Subtarget->isAmdHsaOS())
5221 return emitNonHSAIntrinsicError(DAG, DL, VT);
5223 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5224 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5225 case Intrinsic::r600_read_local_size_x:
5226 if (Subtarget->isAmdHsaOS())
5227 return emitNonHSAIntrinsicError(DAG, DL, VT);
5229 return lowerImplicitZextParam(DAG, Op, MVT::i16,
5230 SI::KernelInputOffsets::LOCAL_SIZE_X);
5231 case Intrinsic::r600_read_local_size_y:
5232 if (Subtarget->isAmdHsaOS())
5233 return emitNonHSAIntrinsicError(DAG, DL, VT);
5235 return lowerImplicitZextParam(DAG, Op, MVT::i16,
5236 SI::KernelInputOffsets::LOCAL_SIZE_Y);
5237 case Intrinsic::r600_read_local_size_z:
5238 if (Subtarget->isAmdHsaOS())
5239 return emitNonHSAIntrinsicError(DAG, DL, VT);
5241 return lowerImplicitZextParam(DAG, Op, MVT::i16,
5242 SI::KernelInputOffsets::LOCAL_SIZE_Z);
5243 case Intrinsic::amdgcn_workgroup_id_x:
5244 case Intrinsic::r600_read_tgid_x:
5245 return getPreloadedValue(DAG, *MFI, VT,
5246 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5247 case Intrinsic::amdgcn_workgroup_id_y:
5248 case Intrinsic::r600_read_tgid_y:
5249 return getPreloadedValue(DAG, *MFI, VT,
5250 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5251 case Intrinsic::amdgcn_workgroup_id_z:
5252 case Intrinsic::r600_read_tgid_z:
5253 return getPreloadedValue(DAG, *MFI, VT,
5254 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5255 case Intrinsic::amdgcn_workitem_id_x:
5256 case Intrinsic::r600_read_tidig_x:
5257 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5258 SDLoc(DAG.getEntryNode()),
5259 MFI->getArgInfo().WorkItemIDX);
5260 case Intrinsic::amdgcn_workitem_id_y:
5261 case Intrinsic::r600_read_tidig_y:
5262 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5263 SDLoc(DAG.getEntryNode()),
5264 MFI->getArgInfo().WorkItemIDY);
5265 case Intrinsic::amdgcn_workitem_id_z:
5266 case Intrinsic::r600_read_tidig_z:
5267 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5268 SDLoc(DAG.getEntryNode()),
5269 MFI->getArgInfo().WorkItemIDZ);
5270 case SIIntrinsic::SI_load_const: {
5272 lowerSBuffer(MVT::i32, DL, Op.getOperand(1), Op.getOperand(2),
5273 DAG.getTargetConstant(0, DL, MVT::i1), DAG);
5274 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Load);
5276 case Intrinsic::amdgcn_s_buffer_load: {
5277 unsigned Cache = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
5278 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2),
5279 DAG.getTargetConstant(Cache & 1, DL, MVT::i1), DAG);
5281 case Intrinsic::amdgcn_fdiv_fast:
5282 return lowerFDIV_FAST(Op, DAG);
5283 case Intrinsic::amdgcn_interp_mov: {
5284 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5285 SDValue Glue = M0.getValue(1);
5286 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
5287 Op.getOperand(2), Op.getOperand(3), Glue);
5289 case Intrinsic::amdgcn_interp_p1: {
5290 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5291 SDValue Glue = M0.getValue(1);
5292 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
5293 Op.getOperand(2), Op.getOperand(3), Glue);
5295 case Intrinsic::amdgcn_interp_p2: {
5296 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5297 SDValue Glue = SDValue(M0.getNode(), 1);
5298 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
5299 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
5302 case Intrinsic::amdgcn_sin:
5303 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5305 case Intrinsic::amdgcn_cos:
5306 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5308 case Intrinsic::amdgcn_log_clamp: {
5309 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5312 DiagnosticInfoUnsupported BadIntrin(
5313 MF.getFunction(), "intrinsic not supported on subtarget",
5315 DAG.getContext()->diagnose(BadIntrin);
5316 return DAG.getUNDEF(VT);
5318 case Intrinsic::amdgcn_ldexp:
5319 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5320 Op.getOperand(1), Op.getOperand(2));
5322 case Intrinsic::amdgcn_fract:
5323 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5325 case Intrinsic::amdgcn_class:
5326 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5327 Op.getOperand(1), Op.getOperand(2));
5328 case Intrinsic::amdgcn_div_fmas:
5329 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5330 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5333 case Intrinsic::amdgcn_div_fixup:
5334 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5335 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5337 case Intrinsic::amdgcn_trig_preop:
5338 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5339 Op.getOperand(1), Op.getOperand(2));
5340 case Intrinsic::amdgcn_div_scale: {
5341 // 3rd parameter required to be a constant.
5342 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
5344 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
5346 // Translate to the operands expected by the machine instruction. The
5347 // first parameter must be the same as the first instruction.
5348 SDValue Numerator = Op.getOperand(1);
5349 SDValue Denominator = Op.getOperand(2);
5351 // Note this order is opposite of the machine instruction's operations,
5352 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5353 // intrinsic has the numerator as the first operand to match a normal
5354 // division operation.
5356 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5358 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5359 Denominator, Numerator);
5361 case Intrinsic::amdgcn_icmp: {
5362 // There is a Pat that handles this variant, so return it as-is.
5363 if (Op.getOperand(1).getValueType() == MVT::i1 &&
5364 Op.getConstantOperandVal(2) == 0 &&
5365 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
5367 return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
5369 case Intrinsic::amdgcn_fcmp: {
5370 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
5372 case Intrinsic::amdgcn_fmed3:
5373 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
5374 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5375 case Intrinsic::amdgcn_fdot2:
5376 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
5377 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5379 case Intrinsic::amdgcn_fmul_legacy:
5380 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
5381 Op.getOperand(1), Op.getOperand(2));
5382 case Intrinsic::amdgcn_sffbh:
5383 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
5384 case Intrinsic::amdgcn_sbfe:
5385 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
5386 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5387 case Intrinsic::amdgcn_ubfe:
5388 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
5389 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5390 case Intrinsic::amdgcn_cvt_pkrtz:
5391 case Intrinsic::amdgcn_cvt_pknorm_i16:
5392 case Intrinsic::amdgcn_cvt_pknorm_u16:
5393 case Intrinsic::amdgcn_cvt_pk_i16:
5394 case Intrinsic::amdgcn_cvt_pk_u16: {
5395 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
5396 EVT VT = Op.getValueType();
5399 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
5400 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
5401 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
5402 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5403 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
5404 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5405 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
5406 Opcode = AMDGPUISD::CVT_PK_I16_I32;
5408 Opcode = AMDGPUISD::CVT_PK_U16_U32;
5410 if (isTypeLegal(VT))
5411 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
5413 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
5414 Op.getOperand(1), Op.getOperand(2));
5415 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
5417 case Intrinsic::amdgcn_wqm: {
5418 SDValue Src = Op.getOperand(1);
5419 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
5422 case Intrinsic::amdgcn_wwm: {
5423 SDValue Src = Op.getOperand(1);
5424 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
5427 case Intrinsic::amdgcn_fmad_ftz:
5428 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
5429 Op.getOperand(2), Op.getOperand(3));
5431 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5432 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5433 return lowerImage(Op, ImageDimIntr, DAG);
5439 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
5440 SelectionDAG &DAG) const {
5441 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5445 case Intrinsic::amdgcn_ds_ordered_add:
5446 case Intrinsic::amdgcn_ds_ordered_swap: {
5447 MemSDNode *M = cast<MemSDNode>(Op);
5448 SDValue Chain = M->getOperand(0);
5449 SDValue M0 = M->getOperand(2);
5450 SDValue Value = M->getOperand(3);
5451 unsigned OrderedCountIndex = M->getConstantOperandVal(7);
5452 unsigned WaveRelease = M->getConstantOperandVal(8);
5453 unsigned WaveDone = M->getConstantOperandVal(9);
5454 unsigned ShaderType;
5455 unsigned Instruction;
5458 case Intrinsic::amdgcn_ds_ordered_add:
5461 case Intrinsic::amdgcn_ds_ordered_swap:
5466 if (WaveDone && !WaveRelease)
5467 report_fatal_error("ds_ordered_count: wave_done requires wave_release");
5469 switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
5470 case CallingConv::AMDGPU_CS:
5471 case CallingConv::AMDGPU_KERNEL:
5474 case CallingConv::AMDGPU_PS:
5477 case CallingConv::AMDGPU_VS:
5480 case CallingConv::AMDGPU_GS:
5484 report_fatal_error("ds_ordered_count unsupported for this calling conv");
5487 unsigned Offset0 = OrderedCountIndex << 2;
5488 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
5490 unsigned Offset = Offset0 | (Offset1 << 8);
5495 DAG.getTargetConstant(Offset, DL, MVT::i16),
5496 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
5498 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
5499 M->getVTList(), Ops, M->getMemoryVT(),
5500 M->getMemOperand());
5502 case Intrinsic::amdgcn_atomic_inc:
5503 case Intrinsic::amdgcn_atomic_dec:
5504 case Intrinsic::amdgcn_ds_fadd:
5505 case Intrinsic::amdgcn_ds_fmin:
5506 case Intrinsic::amdgcn_ds_fmax: {
5507 MemSDNode *M = cast<MemSDNode>(Op);
5510 case Intrinsic::amdgcn_atomic_inc:
5511 Opc = AMDGPUISD::ATOMIC_INC;
5513 case Intrinsic::amdgcn_atomic_dec:
5514 Opc = AMDGPUISD::ATOMIC_DEC;
5516 case Intrinsic::amdgcn_ds_fadd:
5517 Opc = AMDGPUISD::ATOMIC_LOAD_FADD;
5519 case Intrinsic::amdgcn_ds_fmin:
5520 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
5522 case Intrinsic::amdgcn_ds_fmax:
5523 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
5526 llvm_unreachable("Unknown intrinsic!");
5529 M->getOperand(0), // Chain
5530 M->getOperand(2), // Ptr
5531 M->getOperand(3) // Value
5534 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
5535 M->getMemoryVT(), M->getMemOperand());
5537 case Intrinsic::amdgcn_buffer_load:
5538 case Intrinsic::amdgcn_buffer_load_format: {
5539 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
5540 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
5542 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
5543 IdxEn = Idx->getZExtValue() != 0;
5545 Op.getOperand(0), // Chain
5546 Op.getOperand(2), // rsrc
5547 Op.getOperand(3), // vindex
5548 SDValue(), // voffset -- will be set by setBufferOffsets
5549 SDValue(), // soffset -- will be set by setBufferOffsets
5550 SDValue(), // offset -- will be set by setBufferOffsets
5551 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
5552 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
5555 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
5556 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
5557 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5559 EVT VT = Op.getValueType();
5560 EVT IntVT = VT.changeTypeToInteger();
5561 auto *M = cast<MemSDNode>(Op);
5562 EVT LoadVT = Op.getValueType();
5564 if (LoadVT.getScalarType() == MVT::f16)
5565 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5567 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5568 M->getMemOperand());
5570 case Intrinsic::amdgcn_raw_buffer_load:
5571 case Intrinsic::amdgcn_raw_buffer_load_format: {
5572 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
5574 Op.getOperand(0), // Chain
5575 Op.getOperand(2), // rsrc
5576 DAG.getConstant(0, DL, MVT::i32), // vindex
5577 Offsets.first, // voffset
5578 Op.getOperand(4), // soffset
5579 Offsets.second, // offset
5580 Op.getOperand(5), // cachepolicy
5581 DAG.getConstant(0, DL, MVT::i1), // idxen
5584 unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ?
5585 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5587 EVT VT = Op.getValueType();
5588 EVT IntVT = VT.changeTypeToInteger();
5589 auto *M = cast<MemSDNode>(Op);
5590 EVT LoadVT = Op.getValueType();
5592 if (LoadVT.getScalarType() == MVT::f16)
5593 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5595 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5596 M->getMemOperand());
5598 case Intrinsic::amdgcn_struct_buffer_load:
5599 case Intrinsic::amdgcn_struct_buffer_load_format: {
5600 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
5602 Op.getOperand(0), // Chain
5603 Op.getOperand(2), // rsrc
5604 Op.getOperand(3), // vindex
5605 Offsets.first, // voffset
5606 Op.getOperand(5), // soffset
5607 Offsets.second, // offset
5608 Op.getOperand(6), // cachepolicy
5609 DAG.getConstant(1, DL, MVT::i1), // idxen
5612 unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ?
5613 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5615 EVT VT = Op.getValueType();
5616 EVT IntVT = VT.changeTypeToInteger();
5617 auto *M = cast<MemSDNode>(Op);
5618 EVT LoadVT = Op.getValueType();
5620 if (LoadVT.getScalarType() == MVT::f16)
5621 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5623 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5624 M->getMemOperand());
5626 case Intrinsic::amdgcn_tbuffer_load: {
5627 MemSDNode *M = cast<MemSDNode>(Op);
5628 EVT LoadVT = Op.getValueType();
5630 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
5631 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
5632 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
5633 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
5635 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
5636 IdxEn = Idx->getZExtValue() != 0;
5638 Op.getOperand(0), // Chain
5639 Op.getOperand(2), // rsrc
5640 Op.getOperand(3), // vindex
5641 Op.getOperand(4), // voffset
5642 Op.getOperand(5), // soffset
5643 Op.getOperand(6), // offset
5644 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
5645 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
5646 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
5649 if (LoadVT.getScalarType() == MVT::f16)
5650 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
5652 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5653 Op->getVTList(), Ops, LoadVT,
5654 M->getMemOperand());
5656 case Intrinsic::amdgcn_raw_tbuffer_load: {
5657 MemSDNode *M = cast<MemSDNode>(Op);
5658 EVT LoadVT = Op.getValueType();
5659 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
5662 Op.getOperand(0), // Chain
5663 Op.getOperand(2), // rsrc
5664 DAG.getConstant(0, DL, MVT::i32), // vindex
5665 Offsets.first, // voffset
5666 Op.getOperand(4), // soffset
5667 Offsets.second, // offset
5668 Op.getOperand(5), // format
5669 Op.getOperand(6), // cachepolicy
5670 DAG.getConstant(0, DL, MVT::i1), // idxen
5673 if (LoadVT.getScalarType() == MVT::f16)
5674 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
5676 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5677 Op->getVTList(), Ops, LoadVT,
5678 M->getMemOperand());
5680 case Intrinsic::amdgcn_struct_tbuffer_load: {
5681 MemSDNode *M = cast<MemSDNode>(Op);
5682 EVT LoadVT = Op.getValueType();
5683 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
5686 Op.getOperand(0), // Chain
5687 Op.getOperand(2), // rsrc
5688 Op.getOperand(3), // vindex
5689 Offsets.first, // voffset
5690 Op.getOperand(5), // soffset
5691 Offsets.second, // offset
5692 Op.getOperand(6), // format
5693 Op.getOperand(7), // cachepolicy
5694 DAG.getConstant(1, DL, MVT::i1), // idxen
5697 if (LoadVT.getScalarType() == MVT::f16)
5698 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
5700 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5701 Op->getVTList(), Ops, LoadVT,
5702 M->getMemOperand());
5704 case Intrinsic::amdgcn_buffer_atomic_swap:
5705 case Intrinsic::amdgcn_buffer_atomic_add:
5706 case Intrinsic::amdgcn_buffer_atomic_sub:
5707 case Intrinsic::amdgcn_buffer_atomic_smin:
5708 case Intrinsic::amdgcn_buffer_atomic_umin:
5709 case Intrinsic::amdgcn_buffer_atomic_smax:
5710 case Intrinsic::amdgcn_buffer_atomic_umax:
5711 case Intrinsic::amdgcn_buffer_atomic_and:
5712 case Intrinsic::amdgcn_buffer_atomic_or:
5713 case Intrinsic::amdgcn_buffer_atomic_xor: {
5714 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
5716 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
5717 IdxEn = Idx->getZExtValue() != 0;
5719 Op.getOperand(0), // Chain
5720 Op.getOperand(2), // vdata
5721 Op.getOperand(3), // rsrc
5722 Op.getOperand(4), // vindex
5723 SDValue(), // voffset -- will be set by setBufferOffsets
5724 SDValue(), // soffset -- will be set by setBufferOffsets
5725 SDValue(), // offset -- will be set by setBufferOffsets
5726 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
5727 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
5729 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
5730 EVT VT = Op.getValueType();
5732 auto *M = cast<MemSDNode>(Op);
5733 unsigned Opcode = 0;
5736 case Intrinsic::amdgcn_buffer_atomic_swap:
5737 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
5739 case Intrinsic::amdgcn_buffer_atomic_add:
5740 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
5742 case Intrinsic::amdgcn_buffer_atomic_sub:
5743 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
5745 case Intrinsic::amdgcn_buffer_atomic_smin:
5746 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
5748 case Intrinsic::amdgcn_buffer_atomic_umin:
5749 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
5751 case Intrinsic::amdgcn_buffer_atomic_smax:
5752 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
5754 case Intrinsic::amdgcn_buffer_atomic_umax:
5755 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
5757 case Intrinsic::amdgcn_buffer_atomic_and:
5758 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
5760 case Intrinsic::amdgcn_buffer_atomic_or:
5761 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5763 case Intrinsic::amdgcn_buffer_atomic_xor:
5764 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5767 llvm_unreachable("unhandled atomic opcode");
5770 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5771 M->getMemOperand());
5773 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
5774 case Intrinsic::amdgcn_raw_buffer_atomic_add:
5775 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
5776 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
5777 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
5778 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
5779 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
5780 case Intrinsic::amdgcn_raw_buffer_atomic_and:
5781 case Intrinsic::amdgcn_raw_buffer_atomic_or:
5782 case Intrinsic::amdgcn_raw_buffer_atomic_xor: {
5783 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
5785 Op.getOperand(0), // Chain
5786 Op.getOperand(2), // vdata
5787 Op.getOperand(3), // rsrc
5788 DAG.getConstant(0, DL, MVT::i32), // vindex
5789 Offsets.first, // voffset
5790 Op.getOperand(5), // soffset
5791 Offsets.second, // offset
5792 Op.getOperand(6), // cachepolicy
5793 DAG.getConstant(0, DL, MVT::i1), // idxen
5795 EVT VT = Op.getValueType();
5797 auto *M = cast<MemSDNode>(Op);
5798 unsigned Opcode = 0;
5801 case Intrinsic::amdgcn_raw_buffer_atomic_swap:
5802 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
5804 case Intrinsic::amdgcn_raw_buffer_atomic_add:
5805 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
5807 case Intrinsic::amdgcn_raw_buffer_atomic_sub:
5808 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
5810 case Intrinsic::amdgcn_raw_buffer_atomic_smin:
5811 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
5813 case Intrinsic::amdgcn_raw_buffer_atomic_umin:
5814 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
5816 case Intrinsic::amdgcn_raw_buffer_atomic_smax:
5817 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
5819 case Intrinsic::amdgcn_raw_buffer_atomic_umax:
5820 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
5822 case Intrinsic::amdgcn_raw_buffer_atomic_and:
5823 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
5825 case Intrinsic::amdgcn_raw_buffer_atomic_or:
5826 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5828 case Intrinsic::amdgcn_raw_buffer_atomic_xor:
5829 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5832 llvm_unreachable("unhandled atomic opcode");
5835 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5836 M->getMemOperand());
5838 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
5839 case Intrinsic::amdgcn_struct_buffer_atomic_add:
5840 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
5841 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
5842 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
5843 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
5844 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
5845 case Intrinsic::amdgcn_struct_buffer_atomic_and:
5846 case Intrinsic::amdgcn_struct_buffer_atomic_or:
5847 case Intrinsic::amdgcn_struct_buffer_atomic_xor: {
5848 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
5850 Op.getOperand(0), // Chain
5851 Op.getOperand(2), // vdata
5852 Op.getOperand(3), // rsrc
5853 Op.getOperand(4), // vindex
5854 Offsets.first, // voffset
5855 Op.getOperand(6), // soffset
5856 Offsets.second, // offset
5857 Op.getOperand(7), // cachepolicy
5858 DAG.getConstant(1, DL, MVT::i1), // idxen
5860 EVT VT = Op.getValueType();
5862 auto *M = cast<MemSDNode>(Op);
5863 unsigned Opcode = 0;
5866 case Intrinsic::amdgcn_struct_buffer_atomic_swap:
5867 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
5869 case Intrinsic::amdgcn_struct_buffer_atomic_add:
5870 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
5872 case Intrinsic::amdgcn_struct_buffer_atomic_sub:
5873 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
5875 case Intrinsic::amdgcn_struct_buffer_atomic_smin:
5876 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
5878 case Intrinsic::amdgcn_struct_buffer_atomic_umin:
5879 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
5881 case Intrinsic::amdgcn_struct_buffer_atomic_smax:
5882 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
5884 case Intrinsic::amdgcn_struct_buffer_atomic_umax:
5885 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
5887 case Intrinsic::amdgcn_struct_buffer_atomic_and:
5888 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
5890 case Intrinsic::amdgcn_struct_buffer_atomic_or:
5891 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5893 case Intrinsic::amdgcn_struct_buffer_atomic_xor:
5894 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5897 llvm_unreachable("unhandled atomic opcode");
5900 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5901 M->getMemOperand());
5903 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
5904 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
5906 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
5907 IdxEn = Idx->getZExtValue() != 0;
5909 Op.getOperand(0), // Chain
5910 Op.getOperand(2), // src
5911 Op.getOperand(3), // cmp
5912 Op.getOperand(4), // rsrc
5913 Op.getOperand(5), // vindex
5914 SDValue(), // voffset -- will be set by setBufferOffsets
5915 SDValue(), // soffset -- will be set by setBufferOffsets
5916 SDValue(), // offset -- will be set by setBufferOffsets
5917 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
5918 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
5920 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
5921 EVT VT = Op.getValueType();
5922 auto *M = cast<MemSDNode>(Op);
5924 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
5925 Op->getVTList(), Ops, VT, M->getMemOperand());
5927 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
5928 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
5930 Op.getOperand(0), // Chain
5931 Op.getOperand(2), // src
5932 Op.getOperand(3), // cmp
5933 Op.getOperand(4), // rsrc
5934 DAG.getConstant(0, DL, MVT::i32), // vindex
5935 Offsets.first, // voffset
5936 Op.getOperand(6), // soffset
5937 Offsets.second, // offset
5938 Op.getOperand(7), // cachepolicy
5939 DAG.getConstant(0, DL, MVT::i1), // idxen
5941 EVT VT = Op.getValueType();
5942 auto *M = cast<MemSDNode>(Op);
5944 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
5945 Op->getVTList(), Ops, VT, M->getMemOperand());
5947 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
5948 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
5950 Op.getOperand(0), // Chain
5951 Op.getOperand(2), // src
5952 Op.getOperand(3), // cmp
5953 Op.getOperand(4), // rsrc
5954 Op.getOperand(5), // vindex
5955 Offsets.first, // voffset
5956 Op.getOperand(7), // soffset
5957 Offsets.second, // offset
5958 Op.getOperand(8), // cachepolicy
5959 DAG.getConstant(1, DL, MVT::i1), // idxen
5961 EVT VT = Op.getValueType();
5962 auto *M = cast<MemSDNode>(Op);
5964 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
5965 Op->getVTList(), Ops, VT, M->getMemOperand());
5969 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5970 AMDGPU::getImageDimIntrinsicInfo(IntrID))
5971 return lowerImage(Op, ImageDimIntr, DAG);
5977 SDValue SITargetLowering::handleD16VData(SDValue VData,
5978 SelectionDAG &DAG) const {
5979 EVT StoreVT = VData.getValueType();
5981 // No change for f16 and legal vector D16 types.
5982 if (!StoreVT.isVector())
5986 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
5988 if (Subtarget->hasUnpackedD16VMem()) {
5989 // We need to unpack the packed data to store.
5990 EVT IntStoreVT = StoreVT.changeTypeToInteger();
5991 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
5993 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
5994 StoreVT.getVectorNumElements());
5995 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
5996 return DAG.UnrollVectorOp(ZExt.getNode());
5999 assert(isTypeLegal(StoreVT));
6003 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6004 SelectionDAG &DAG) const {
6006 SDValue Chain = Op.getOperand(0);
6007 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6008 MachineFunction &MF = DAG.getMachineFunction();
6010 switch (IntrinsicID) {
6011 case Intrinsic::amdgcn_exp: {
6012 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6013 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6014 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
6015 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
6017 const SDValue Ops[] = {
6019 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6020 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
6021 Op.getOperand(4), // src0
6022 Op.getOperand(5), // src1
6023 Op.getOperand(6), // src2
6024 Op.getOperand(7), // src3
6025 DAG.getTargetConstant(0, DL, MVT::i1), // compr
6026 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6029 unsigned Opc = Done->isNullValue() ?
6030 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6031 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6033 case Intrinsic::amdgcn_exp_compr: {
6034 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6035 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6036 SDValue Src0 = Op.getOperand(4);
6037 SDValue Src1 = Op.getOperand(5);
6038 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6039 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
6041 SDValue Undef = DAG.getUNDEF(MVT::f32);
6042 const SDValue Ops[] = {
6044 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6045 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
6046 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
6047 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
6050 DAG.getTargetConstant(1, DL, MVT::i1), // compr
6051 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6054 unsigned Opc = Done->isNullValue() ?
6055 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6056 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6058 case Intrinsic::amdgcn_s_sendmsg:
6059 case Intrinsic::amdgcn_s_sendmsghalt: {
6060 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
6061 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
6062 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
6063 SDValue Glue = Chain.getValue(1);
6064 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
6065 Op.getOperand(2), Glue);
6067 case Intrinsic::amdgcn_init_exec: {
6068 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
6071 case Intrinsic::amdgcn_init_exec_from_input: {
6072 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
6073 Op.getOperand(2), Op.getOperand(3));
6075 case Intrinsic::amdgcn_s_barrier: {
6076 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6077 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6078 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6079 if (WGSize <= ST.getWavefrontSize())
6080 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6081 Op.getOperand(0)), 0);
6085 case Intrinsic::amdgcn_tbuffer_store: {
6086 SDValue VData = Op.getOperand(2);
6087 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6089 VData = handleD16VData(VData, DAG);
6090 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6091 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6092 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6093 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6095 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6096 IdxEn = Idx->getZExtValue() != 0;
6100 Op.getOperand(3), // rsrc
6101 Op.getOperand(4), // vindex
6102 Op.getOperand(5), // voffset
6103 Op.getOperand(6), // soffset
6104 Op.getOperand(7), // offset
6105 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6106 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6107 DAG.getConstant(IdxEn, DL, MVT::i1), // idexen
6109 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6110 AMDGPUISD::TBUFFER_STORE_FORMAT;
6111 MemSDNode *M = cast<MemSDNode>(Op);
6112 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6113 M->getMemoryVT(), M->getMemOperand());
6116 case Intrinsic::amdgcn_struct_tbuffer_store: {
6117 SDValue VData = Op.getOperand(2);
6118 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6120 VData = handleD16VData(VData, DAG);
6121 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6125 Op.getOperand(3), // rsrc
6126 Op.getOperand(4), // vindex
6127 Offsets.first, // voffset
6128 Op.getOperand(6), // soffset
6129 Offsets.second, // offset
6130 Op.getOperand(7), // format
6131 Op.getOperand(8), // cachepolicy
6132 DAG.getConstant(1, DL, MVT::i1), // idexen
6134 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6135 AMDGPUISD::TBUFFER_STORE_FORMAT;
6136 MemSDNode *M = cast<MemSDNode>(Op);
6137 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6138 M->getMemoryVT(), M->getMemOperand());
6141 case Intrinsic::amdgcn_raw_tbuffer_store: {
6142 SDValue VData = Op.getOperand(2);
6143 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6145 VData = handleD16VData(VData, DAG);
6146 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6150 Op.getOperand(3), // rsrc
6151 DAG.getConstant(0, DL, MVT::i32), // vindex
6152 Offsets.first, // voffset
6153 Op.getOperand(5), // soffset
6154 Offsets.second, // offset
6155 Op.getOperand(6), // format
6156 Op.getOperand(7), // cachepolicy
6157 DAG.getConstant(0, DL, MVT::i1), // idexen
6159 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6160 AMDGPUISD::TBUFFER_STORE_FORMAT;
6161 MemSDNode *M = cast<MemSDNode>(Op);
6162 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6163 M->getMemoryVT(), M->getMemOperand());
6166 case Intrinsic::amdgcn_buffer_store:
6167 case Intrinsic::amdgcn_buffer_store_format: {
6168 SDValue VData = Op.getOperand(2);
6169 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6171 VData = handleD16VData(VData, DAG);
6172 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6173 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6175 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6176 IdxEn = Idx->getZExtValue() != 0;
6180 Op.getOperand(3), // rsrc
6181 Op.getOperand(4), // vindex
6182 SDValue(), // voffset -- will be set by setBufferOffsets
6183 SDValue(), // soffset -- will be set by setBufferOffsets
6184 SDValue(), // offset -- will be set by setBufferOffsets
6185 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6186 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6188 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6189 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6190 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6191 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6192 MemSDNode *M = cast<MemSDNode>(Op);
6193 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6194 M->getMemoryVT(), M->getMemOperand());
6197 case Intrinsic::amdgcn_raw_buffer_store:
6198 case Intrinsic::amdgcn_raw_buffer_store_format: {
6199 SDValue VData = Op.getOperand(2);
6200 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6202 VData = handleD16VData(VData, DAG);
6203 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6207 Op.getOperand(3), // rsrc
6208 DAG.getConstant(0, DL, MVT::i32), // vindex
6209 Offsets.first, // voffset
6210 Op.getOperand(5), // soffset
6211 Offsets.second, // offset
6212 Op.getOperand(6), // cachepolicy
6213 DAG.getConstant(0, DL, MVT::i1), // idxen
6215 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ?
6216 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6217 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6218 MemSDNode *M = cast<MemSDNode>(Op);
6219 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6220 M->getMemoryVT(), M->getMemOperand());
6223 case Intrinsic::amdgcn_struct_buffer_store:
6224 case Intrinsic::amdgcn_struct_buffer_store_format: {
6225 SDValue VData = Op.getOperand(2);
6226 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6228 VData = handleD16VData(VData, DAG);
6229 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6233 Op.getOperand(3), // rsrc
6234 Op.getOperand(4), // vindex
6235 Offsets.first, // voffset
6236 Op.getOperand(6), // soffset
6237 Offsets.second, // offset
6238 Op.getOperand(7), // cachepolicy
6239 DAG.getConstant(1, DL, MVT::i1), // idxen
6241 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6242 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6243 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6244 MemSDNode *M = cast<MemSDNode>(Op);
6245 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6246 M->getMemoryVT(), M->getMemOperand());
6250 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6251 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6252 return lowerImage(Op, ImageDimIntr, DAG);
6259 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
6260 // offset (the offset that is included in bounds checking and swizzling, to be
6261 // split between the instruction's voffset and immoffset fields) and soffset
6262 // (the offset that is excluded from bounds checking and swizzling, to go in
6263 // the instruction's soffset field). This function takes the first kind of
6264 // offset and figures out how to split it between voffset and immoffset.
6265 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
6266 SDValue Offset, SelectionDAG &DAG) const {
6268 const unsigned MaxImm = 4095;
6269 SDValue N0 = Offset;
6270 ConstantSDNode *C1 = nullptr;
6272 if ((C1 = dyn_cast<ConstantSDNode>(N0)))
6274 else if (DAG.isBaseWithConstantOffset(N0)) {
6275 C1 = cast<ConstantSDNode>(N0.getOperand(1));
6276 N0 = N0.getOperand(0);
6280 unsigned ImmOffset = C1->getZExtValue();
6281 // If the immediate value is too big for the immoffset field, put the value
6282 // and -4096 into the immoffset field so that the value that is copied/added
6283 // for the voffset field is a multiple of 4096, and it stands more chance
6284 // of being CSEd with the copy/add for another similar load/store.
6285 // However, do not do that rounding down to a multiple of 4096 if that is a
6286 // negative number, as it appears to be illegal to have a negative offset
6287 // in the vgpr, even if adding the immediate offset makes it positive.
6288 unsigned Overflow = ImmOffset & ~MaxImm;
6289 ImmOffset -= Overflow;
6290 if ((int32_t)Overflow < 0) {
6291 Overflow += ImmOffset;
6294 C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32));
6296 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
6300 SDValue Ops[] = { N0, OverflowVal };
6301 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
6306 N0 = DAG.getConstant(0, DL, MVT::i32);
6308 C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32));
6309 return {N0, SDValue(C1, 0)};
6312 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
6313 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
6314 // pointed to by Offsets.
6315 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
6316 SelectionDAG &DAG, SDValue *Offsets,
6317 unsigned Align) const {
6318 SDLoc DL(CombinedOffset);
6319 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
6320 uint32_t Imm = C->getZExtValue();
6321 uint32_t SOffset, ImmOffset;
6322 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
6323 Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
6324 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6325 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6329 if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
6330 SDValue N0 = CombinedOffset.getOperand(0);
6331 SDValue N1 = CombinedOffset.getOperand(1);
6332 uint32_t SOffset, ImmOffset;
6333 int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
6334 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
6335 Subtarget, Align)) {
6337 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6338 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6342 Offsets[0] = CombinedOffset;
6343 Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
6344 Offsets[2] = DAG.getConstant(0, DL, MVT::i32);
6347 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
6348 ISD::LoadExtType ExtType, SDValue Op,
6349 const SDLoc &SL, EVT VT) {
6350 if (VT.bitsLT(Op.getValueType()))
6351 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
6355 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
6357 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
6359 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
6360 case ISD::NON_EXTLOAD:
6364 llvm_unreachable("invalid ext type");
6367 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
6368 SelectionDAG &DAG = DCI.DAG;
6369 if (Ld->getAlignment() < 4 || Ld->isDivergent())
6372 // FIXME: Constant loads should all be marked invariant.
6373 unsigned AS = Ld->getAddressSpace();
6374 if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
6375 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
6376 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
6379 // Don't do this early, since it may interfere with adjacent load merging for
6380 // illegal types. We can avoid losing alignment information for exotic types
6382 EVT MemVT = Ld->getMemoryVT();
6383 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
6384 MemVT.getSizeInBits() >= 32)
6389 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
6390 "unexpected vector extload");
6392 // TODO: Drop only high part of range.
6393 SDValue Ptr = Ld->getBasePtr();
6394 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
6395 MVT::i32, SL, Ld->getChain(), Ptr,
6397 Ld->getPointerInfo(), MVT::i32,
6399 Ld->getMemOperand()->getFlags(),
6401 nullptr); // Drop ranges
6403 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
6404 if (MemVT.isFloatingPoint()) {
6405 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
6406 "unexpected fp extload");
6407 TruncVT = MemVT.changeTypeToInteger();
6410 SDValue Cvt = NewLoad;
6411 if (Ld->getExtensionType() == ISD::SEXTLOAD) {
6412 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
6413 DAG.getValueType(TruncVT));
6414 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
6415 Ld->getExtensionType() == ISD::NON_EXTLOAD) {
6416 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
6418 assert(Ld->getExtensionType() == ISD::EXTLOAD);
6421 EVT VT = Ld->getValueType(0);
6422 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6424 DCI.AddToWorklist(Cvt.getNode());
6426 // We may need to handle exotic cases, such as i16->i64 extloads, so insert
6427 // the appropriate extension from the 32-bit load.
6428 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
6429 DCI.AddToWorklist(Cvt.getNode());
6431 // Handle conversion back to floating point if necessary.
6432 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
6434 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
6437 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6439 LoadSDNode *Load = cast<LoadSDNode>(Op);
6440 ISD::LoadExtType ExtType = Load->getExtensionType();
6441 EVT MemVT = Load->getMemoryVT();
6443 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
6444 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
6447 // FIXME: Copied from PPC
6448 // First, load into 32 bits, then truncate to 1 bit.
6450 SDValue Chain = Load->getChain();
6451 SDValue BasePtr = Load->getBasePtr();
6452 MachineMemOperand *MMO = Load->getMemOperand();
6454 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
6456 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
6457 BasePtr, RealMemVT, MMO);
6460 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
6464 return DAG.getMergeValues(Ops, DL);
6467 if (!MemVT.isVector())
6470 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
6471 "Custom lowering for non-i32 vectors hasn't been implemented.");
6473 unsigned Alignment = Load->getAlignment();
6474 unsigned AS = Load->getAddressSpace();
6475 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
6478 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
6479 return DAG.getMergeValues(Ops, DL);
6482 MachineFunction &MF = DAG.getMachineFunction();
6483 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
6484 // If there is a possibilty that flat instruction access scratch memory
6485 // then we need to use the same legalization rules we use for private.
6486 if (AS == AMDGPUAS::FLAT_ADDRESS)
6487 AS = MFI->hasFlatScratchInit() ?
6488 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
6490 unsigned NumElements = MemVT.getVectorNumElements();
6492 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6493 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
6494 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32)
6496 // Non-uniform loads will be selected to MUBUF instructions, so they
6497 // have the same legalization requirements as global and private
6502 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6503 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
6504 AS == AMDGPUAS::GLOBAL_ADDRESS) {
6505 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
6506 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
6507 Alignment >= 4 && NumElements < 32)
6509 // Non-uniform loads will be selected to MUBUF instructions, so they
6510 // have the same legalization requirements as global and private
6514 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6515 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
6516 AS == AMDGPUAS::GLOBAL_ADDRESS ||
6517 AS == AMDGPUAS::FLAT_ADDRESS) {
6518 if (NumElements > 4)
6519 return SplitVectorLoad(Op, DAG);
6520 // v4 loads are supported for private and global memory.
6523 if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
6524 // Depending on the setting of the private_element_size field in the
6525 // resource descriptor, we can only make private accesses up to a certain
6527 switch (Subtarget->getMaxPrivateElementSize()) {
6529 return scalarizeVectorLoad(Load, DAG);
6531 if (NumElements > 2)
6532 return SplitVectorLoad(Op, DAG);
6535 // Same as global/flat
6536 if (NumElements > 4)
6537 return SplitVectorLoad(Op, DAG);
6540 llvm_unreachable("unsupported private_element_size");
6542 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
6543 // Use ds_read_b128 if possible.
6544 if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
6545 MemVT.getStoreSize() == 16)
6548 if (NumElements > 2)
6549 return SplitVectorLoad(Op, DAG);
6551 // SI has a hardware bug in the LDS / GDS boounds checking: if the base
6552 // address is negative, then the instruction is incorrectly treated as
6553 // out-of-bounds even if base + offsets is in bounds. Split vectorized
6554 // loads here to avoid emitting ds_read2_b32. We may re-combine the
6555 // load later in the SILoadStoreOptimizer.
6556 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
6557 NumElements == 2 && MemVT.getStoreSize() == 8 &&
6558 Load->getAlignment() < 8) {
6559 return SplitVectorLoad(Op, DAG);
6565 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6566 EVT VT = Op.getValueType();
6567 assert(VT.getSizeInBits() == 64);
6570 SDValue Cond = Op.getOperand(0);
6572 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
6573 SDValue One = DAG.getConstant(1, DL, MVT::i32);
6575 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
6576 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
6578 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
6579 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
6581 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
6583 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
6584 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
6586 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
6588 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
6589 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6592 // Catch division cases where we can use shortcuts with rcp and rsq
6594 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
6595 SelectionDAG &DAG) const {
6597 SDValue LHS = Op.getOperand(0);
6598 SDValue RHS = Op.getOperand(1);
6599 EVT VT = Op.getValueType();
6600 const SDNodeFlags Flags = Op->getFlags();
6601 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
6603 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
6606 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
6607 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
6608 if (CLHS->isExactlyValue(1.0)) {
6609 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
6610 // the CI documentation has a worst case error of 1 ulp.
6611 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
6612 // use it as long as we aren't trying to use denormals.
6614 // v_rcp_f16 and v_rsq_f16 DO support denormals.
6616 // 1.0 / sqrt(x) -> rsq(x)
6618 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
6619 // error seems really high at 2^29 ULP.
6620 if (RHS.getOpcode() == ISD::FSQRT)
6621 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
6623 // 1.0 / x -> rcp(x)
6624 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
6627 // Same as for 1.0, but expand the sign out of the constant.
6628 if (CLHS->isExactlyValue(-1.0)) {
6629 // -1.0 / x -> rcp (fneg x)
6630 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
6631 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
6637 // Turn into multiply by the reciprocal.
6638 // x / y -> x * (1.0 / y)
6639 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
6640 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
6646 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
6647 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
6648 if (GlueChain->getNumValues() <= 1) {
6649 return DAG.getNode(Opcode, SL, VT, A, B);
6652 assert(GlueChain->getNumValues() == 3);
6654 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
6656 default: llvm_unreachable("no chain equivalent for opcode");
6658 Opcode = AMDGPUISD::FMUL_W_CHAIN;
6662 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
6663 GlueChain.getValue(2));
6666 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
6667 EVT VT, SDValue A, SDValue B, SDValue C,
6668 SDValue GlueChain) {
6669 if (GlueChain->getNumValues() <= 1) {
6670 return DAG.getNode(Opcode, SL, VT, A, B, C);
6673 assert(GlueChain->getNumValues() == 3);
6675 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
6677 default: llvm_unreachable("no chain equivalent for opcode");
6679 Opcode = AMDGPUISD::FMA_W_CHAIN;
6683 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
6684 GlueChain.getValue(2));
6687 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
6688 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
6692 SDValue Src0 = Op.getOperand(0);
6693 SDValue Src1 = Op.getOperand(1);
6695 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
6696 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
6698 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
6699 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
6701 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
6702 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
6704 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
6707 // Faster 2.5 ULP division that does not support denormals.
6708 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
6710 SDValue LHS = Op.getOperand(1);
6711 SDValue RHS = Op.getOperand(2);
6713 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
6715 const APFloat K0Val(BitsToFloat(0x6f800000));
6716 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
6718 const APFloat K1Val(BitsToFloat(0x2f800000));
6719 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
6721 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
6724 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
6726 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
6728 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
6730 // TODO: Should this propagate fast-math-flags?
6731 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
6733 // rcp does not support denormals.
6734 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
6736 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
6738 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
6741 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
6742 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
6746 SDValue LHS = Op.getOperand(0);
6747 SDValue RHS = Op.getOperand(1);
6749 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
6751 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
6753 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
6755 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
6758 // Denominator is scaled to not be denormal, so using rcp is ok.
6759 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
6761 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
6764 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
6765 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
6766 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
6768 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
6770 if (!Subtarget->hasFP32Denormals()) {
6771 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
6772 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
6774 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
6776 EnableDenormValue, BitField);
6779 EnableDenorm.getValue(0),
6780 EnableDenorm.getValue(1)
6783 NegDivScale0 = DAG.getMergeValues(Ops, SL);
6786 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
6787 ApproxRcp, One, NegDivScale0);
6789 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
6792 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
6795 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
6796 NumeratorScaled, Mul);
6798 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
6800 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
6801 NumeratorScaled, Fma3);
6803 if (!Subtarget->hasFP32Denormals()) {
6804 const SDValue DisableDenormValue =
6805 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
6806 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
6812 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
6813 DisableDenorm, DAG.getRoot());
6814 DAG.setRoot(OutputChain);
6817 SDValue Scale = NumeratorScaled.getValue(1);
6818 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
6819 Fma4, Fma1, Fma3, Scale);
6821 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
6824 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
6825 if (DAG.getTarget().Options.UnsafeFPMath)
6826 return lowerFastUnsafeFDIV(Op, DAG);
6829 SDValue X = Op.getOperand(0);
6830 SDValue Y = Op.getOperand(1);
6832 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
6834 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
6836 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
6838 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
6840 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
6842 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
6844 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
6846 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
6848 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
6850 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
6851 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
6853 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
6854 NegDivScale0, Mul, DivScale1);
6858 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
6859 // Workaround a hardware bug on SI where the condition output from div_scale
6862 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
6864 // Figure out if the scale to use for div_fmas.
6865 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
6866 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
6867 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
6868 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
6870 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
6871 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
6874 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
6876 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
6878 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
6879 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
6880 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
6882 Scale = DivScale1.getValue(1);
6885 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
6886 Fma4, Fma3, Mul, Scale);
6888 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
6891 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
6892 EVT VT = Op.getValueType();
6895 return LowerFDIV32(Op, DAG);
6898 return LowerFDIV64(Op, DAG);
6901 return LowerFDIV16(Op, DAG);
6903 llvm_unreachable("Unexpected type for fdiv");
6906 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6908 StoreSDNode *Store = cast<StoreSDNode>(Op);
6909 EVT VT = Store->getMemoryVT();
6911 if (VT == MVT::i1) {
6912 return DAG.getTruncStore(Store->getChain(), DL,
6913 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
6914 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
6917 assert(VT.isVector() &&
6918 Store->getValue().getValueType().getScalarType() == MVT::i32);
6920 unsigned AS = Store->getAddressSpace();
6921 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
6922 AS, Store->getAlignment())) {
6923 return expandUnalignedStore(Store, DAG);
6926 MachineFunction &MF = DAG.getMachineFunction();
6927 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
6928 // If there is a possibilty that flat instruction access scratch memory
6929 // then we need to use the same legalization rules we use for private.
6930 if (AS == AMDGPUAS::FLAT_ADDRESS)
6931 AS = MFI->hasFlatScratchInit() ?
6932 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
6934 unsigned NumElements = VT.getVectorNumElements();
6935 if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
6936 AS == AMDGPUAS::FLAT_ADDRESS) {
6937 if (NumElements > 4)
6938 return SplitVectorStore(Op, DAG);
6940 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
6941 switch (Subtarget->getMaxPrivateElementSize()) {
6943 return scalarizeVectorStore(Store, DAG);
6945 if (NumElements > 2)
6946 return SplitVectorStore(Op, DAG);
6949 if (NumElements > 4)
6950 return SplitVectorStore(Op, DAG);
6953 llvm_unreachable("unsupported private_element_size");
6955 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
6956 // Use ds_write_b128 if possible.
6957 if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
6958 VT.getStoreSize() == 16)
6961 if (NumElements > 2)
6962 return SplitVectorStore(Op, DAG);
6964 // SI has a hardware bug in the LDS / GDS boounds checking: if the base
6965 // address is negative, then the instruction is incorrectly treated as
6966 // out-of-bounds even if base + offsets is in bounds. Split vectorized
6967 // stores here to avoid emitting ds_write2_b32. We may re-combine the
6968 // store later in the SILoadStoreOptimizer.
6969 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
6970 NumElements == 2 && VT.getStoreSize() == 8 &&
6971 Store->getAlignment() < 8) {
6972 return SplitVectorStore(Op, DAG);
6977 llvm_unreachable("unhandled address space");
6981 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
6983 EVT VT = Op.getValueType();
6984 SDValue Arg = Op.getOperand(0);
6987 // TODO: Should this propagate fast-math-flags?
6989 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
6991 if (Subtarget->hasTrigReducedRange()) {
6992 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
6993 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
6995 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
6998 switch (Op.getOpcode()) {
7000 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7002 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7004 llvm_unreachable("Wrong trig opcode");
7008 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7009 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7010 assert(AtomicNode->isCompareAndSwap());
7011 unsigned AS = AtomicNode->getAddressSpace();
7013 // No custom lowering required for local address space
7014 if (!isFlatGlobalAddrSpace(AS))
7017 // Non-local address space requires custom lowering for atomic compare
7018 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7020 SDValue ChainIn = Op.getOperand(0);
7021 SDValue Addr = Op.getOperand(1);
7022 SDValue Old = Op.getOperand(2);
7023 SDValue New = Op.getOperand(3);
7024 EVT VT = Op.getValueType();
7025 MVT SimpleVT = VT.getSimpleVT();
7026 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7028 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
7029 SDValue Ops[] = { ChainIn, Addr, NewOld };
7031 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7032 Ops, VT, AtomicNode->getMemOperand());
7035 //===----------------------------------------------------------------------===//
7036 // Custom DAG optimizations
7037 //===----------------------------------------------------------------------===//
7039 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
7040 DAGCombinerInfo &DCI) const {
7041 EVT VT = N->getValueType(0);
7042 EVT ScalarVT = VT.getScalarType();
7043 if (ScalarVT != MVT::f32)
7046 SelectionDAG &DAG = DCI.DAG;
7049 SDValue Src = N->getOperand(0);
7050 EVT SrcVT = Src.getValueType();
7052 // TODO: We could try to match extracting the higher bytes, which would be
7053 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7054 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7055 // about in practice.
7056 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
7057 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7058 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7059 DCI.AddToWorklist(Cvt.getNode());
7067 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7069 // This is a variant of
7070 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7072 // The normal DAG combiner will do this, but only if the add has one use since
7073 // that would increase the number of instructions.
7075 // This prevents us from seeing a constant offset that can be folded into a
7076 // memory instruction's addressing mode. If we know the resulting add offset of
7077 // a pointer can be folded into an addressing offset, we can replace the pointer
7078 // operand with the add of new constant offset. This eliminates one of the uses,
7079 // and may allow the remaining use to also be simplified.
7081 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7084 DAGCombinerInfo &DCI) const {
7085 SDValue N0 = N->getOperand(0);
7086 SDValue N1 = N->getOperand(1);
7088 // We only do this to handle cases where it's profitable when there are
7089 // multiple uses of the add, so defer to the standard combine.
7090 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
7094 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
7098 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7102 // If the resulting offset is too large, we can't fold it into the addressing
7104 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
7105 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
7108 AM.HasBaseReg = true;
7109 AM.BaseOffs = Offset.getSExtValue();
7110 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
7113 SelectionDAG &DAG = DCI.DAG;
7115 EVT VT = N->getValueType(0);
7117 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
7118 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
7121 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
7122 (N0.getOpcode() == ISD::OR ||
7123 N0->getFlags().hasNoUnsignedWrap()));
7125 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
7128 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
7129 DAGCombinerInfo &DCI) const {
7130 SDValue Ptr = N->getBasePtr();
7131 SelectionDAG &DAG = DCI.DAG;
7134 // TODO: We could also do this for multiplies.
7135 if (Ptr.getOpcode() == ISD::SHL) {
7136 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
7137 N->getMemoryVT(), DCI);
7139 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
7141 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
7142 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
7149 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
7150 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
7151 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
7152 (Opc == ISD::XOR && Val == 0);
7155 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
7156 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
7157 // integer combine opportunities since most 64-bit operations are decomposed
7158 // this way. TODO: We won't want this for SALU especially if it is an inline
7160 SDValue SITargetLowering::splitBinaryBitConstantOp(
7161 DAGCombinerInfo &DCI,
7163 unsigned Opc, SDValue LHS,
7164 const ConstantSDNode *CRHS) const {
7165 uint64_t Val = CRHS->getZExtValue();
7166 uint32_t ValLo = Lo_32(Val);
7167 uint32_t ValHi = Hi_32(Val);
7168 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7170 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
7171 bitOpWithConstantIsReducible(Opc, ValHi)) ||
7172 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
7173 // If we need to materialize a 64-bit immediate, it will be split up later
7174 // anyway. Avoid creating the harder to understand 64-bit immediate
7176 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
7182 // Returns true if argument is a boolean value which is not serialized into
7183 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
7184 static bool isBoolSGPR(SDValue V) {
7185 if (V.getValueType() != MVT::i1)
7187 switch (V.getOpcode()) {
7193 case AMDGPUISD::FP_CLASS:
7199 // If a constant has all zeroes or all ones within each byte return it.
7200 // Otherwise return 0.
7201 static uint32_t getConstantPermuteMask(uint32_t C) {
7202 // 0xff for any zero byte in the mask
7203 uint32_t ZeroByteMask = 0;
7204 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
7205 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
7206 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
7207 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
7208 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
7209 if ((NonZeroByteMask & C) != NonZeroByteMask)
7210 return 0; // Partial bytes selected.
7214 // Check if a node selects whole bytes from its operand 0 starting at a byte
7215 // boundary while masking the rest. Returns select mask as in the v_perm_b32
7216 // or -1 if not succeeded.
7217 // Note byte select encoding:
7218 // value 0-3 selects corresponding source byte;
7219 // value 0xc selects zero;
7220 // value 0xff selects 0xff.
7221 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
7222 assert(V.getValueSizeInBits() == 32);
7224 if (V.getNumOperands() != 2)
7227 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
7231 uint32_t C = N1->getZExtValue();
7233 switch (V.getOpcode()) {
7237 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7238 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
7243 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7244 return (0x03020100 & ~ConstMask) | ConstMask;
7252 return uint32_t((0x030201000c0c0c0cull << C) >> 32);
7258 return uint32_t(0x0c0c0c0c03020100ull >> C);
7264 SDValue SITargetLowering::performAndCombine(SDNode *N,
7265 DAGCombinerInfo &DCI) const {
7266 if (DCI.isBeforeLegalize())
7269 SelectionDAG &DAG = DCI.DAG;
7270 EVT VT = N->getValueType(0);
7271 SDValue LHS = N->getOperand(0);
7272 SDValue RHS = N->getOperand(1);
7275 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
7276 if (VT == MVT::i64 && CRHS) {
7278 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
7282 if (CRHS && VT == MVT::i32) {
7283 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
7284 // nb = number of trailing zeroes in mask
7285 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
7286 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
7287 uint64_t Mask = CRHS->getZExtValue();
7288 unsigned Bits = countPopulation(Mask);
7289 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
7290 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
7291 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
7292 unsigned Shift = CShift->getZExtValue();
7293 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
7294 unsigned Offset = NB + Shift;
7295 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
7297 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
7299 DAG.getConstant(Offset, SL, MVT::i32),
7300 DAG.getConstant(Bits, SL, MVT::i32));
7301 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7302 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
7303 DAG.getValueType(NarrowVT));
7304 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
7305 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
7311 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
7312 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
7313 isa<ConstantSDNode>(LHS.getOperand(2))) {
7314 uint32_t Sel = getConstantPermuteMask(Mask);
7318 // Select 0xc for all zero bytes
7319 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
7321 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
7322 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
7326 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
7327 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
7328 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
7329 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7330 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
7332 SDValue X = LHS.getOperand(0);
7333 SDValue Y = RHS.getOperand(0);
7334 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
7337 if (LCC == ISD::SETO) {
7338 if (X != LHS.getOperand(1))
7341 if (RCC == ISD::SETUNE) {
7342 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
7343 if (!C1 || !C1->isInfinity() || C1->isNegative())
7346 const uint32_t Mask = SIInstrFlags::N_NORMAL |
7347 SIInstrFlags::N_SUBNORMAL |
7348 SIInstrFlags::N_ZERO |
7349 SIInstrFlags::P_ZERO |
7350 SIInstrFlags::P_SUBNORMAL |
7351 SIInstrFlags::P_NORMAL;
7353 static_assert(((~(SIInstrFlags::S_NAN |
7354 SIInstrFlags::Q_NAN |
7355 SIInstrFlags::N_INFINITY |
7356 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
7360 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
7361 X, DAG.getConstant(Mask, DL, MVT::i32));
7366 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
7367 std::swap(LHS, RHS);
7369 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
7371 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7372 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
7373 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
7374 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7375 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
7376 (RHS.getOperand(0) == LHS.getOperand(0) &&
7377 LHS.getOperand(0) == LHS.getOperand(1))) {
7378 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
7379 unsigned NewMask = LCC == ISD::SETO ?
7380 Mask->getZExtValue() & ~OrdMask :
7381 Mask->getZExtValue() & OrdMask;
7384 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
7385 DAG.getConstant(NewMask, DL, MVT::i32));
7389 if (VT == MVT::i32 &&
7390 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
7391 // and x, (sext cc from i1) => select cc, x, 0
7392 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
7393 std::swap(LHS, RHS);
7394 if (isBoolSGPR(RHS.getOperand(0)))
7395 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
7396 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
7399 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
7400 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7401 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
7402 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
7403 uint32_t LHSMask = getPermuteMask(DAG, LHS);
7404 uint32_t RHSMask = getPermuteMask(DAG, RHS);
7405 if (LHSMask != ~0u && RHSMask != ~0u) {
7406 // Canonicalize the expression in an attempt to have fewer unique masks
7407 // and therefore fewer registers used to hold the masks.
7408 if (LHSMask > RHSMask) {
7409 std::swap(LHSMask, RHSMask);
7410 std::swap(LHS, RHS);
7413 // Select 0xc for each lane used from source operand. Zero has 0xc mask
7414 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
7415 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7416 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7418 // Check of we need to combine values from two sources within a byte.
7419 if (!(LHSUsedLanes & RHSUsedLanes) &&
7420 // If we select high and lower word keep it for SDWA.
7421 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
7422 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
7423 // Each byte in each mask is either selector mask 0-3, or has higher
7424 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
7425 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
7426 // mask which is not 0xff wins. By anding both masks we have a correct
7427 // result except that 0x0c shall be corrected to give 0x0c only.
7428 uint32_t Mask = LHSMask & RHSMask;
7429 for (unsigned I = 0; I < 32; I += 8) {
7430 uint32_t ByteSel = 0xff << I;
7431 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
7432 Mask &= (0x0c << I) & 0xffffffff;
7435 // Add 4 to each active LHS lane. It will not affect any existing 0xff
7437 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
7440 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
7441 LHS.getOperand(0), RHS.getOperand(0),
7442 DAG.getConstant(Sel, DL, MVT::i32));
7450 SDValue SITargetLowering::performOrCombine(SDNode *N,
7451 DAGCombinerInfo &DCI) const {
7452 SelectionDAG &DAG = DCI.DAG;
7453 SDValue LHS = N->getOperand(0);
7454 SDValue RHS = N->getOperand(1);
7456 EVT VT = N->getValueType(0);
7457 if (VT == MVT::i1) {
7458 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
7459 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
7460 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
7461 SDValue Src = LHS.getOperand(0);
7462 if (Src != RHS.getOperand(0))
7465 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
7466 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7470 // Only 10 bits are used.
7471 static const uint32_t MaxMask = 0x3ff;
7473 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
7475 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
7476 Src, DAG.getConstant(NewMask, DL, MVT::i32));
7482 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
7483 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
7484 LHS.getOpcode() == AMDGPUISD::PERM &&
7485 isa<ConstantSDNode>(LHS.getOperand(2))) {
7486 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
7490 Sel |= LHS.getConstantOperandVal(2);
7492 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
7493 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
7496 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
7497 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7498 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
7499 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
7500 uint32_t LHSMask = getPermuteMask(DAG, LHS);
7501 uint32_t RHSMask = getPermuteMask(DAG, RHS);
7502 if (LHSMask != ~0u && RHSMask != ~0u) {
7503 // Canonicalize the expression in an attempt to have fewer unique masks
7504 // and therefore fewer registers used to hold the masks.
7505 if (LHSMask > RHSMask) {
7506 std::swap(LHSMask, RHSMask);
7507 std::swap(LHS, RHS);
7510 // Select 0xc for each lane used from source operand. Zero has 0xc mask
7511 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
7512 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7513 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7515 // Check of we need to combine values from two sources within a byte.
7516 if (!(LHSUsedLanes & RHSUsedLanes) &&
7517 // If we select high and lower word keep it for SDWA.
7518 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
7519 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
7520 // Kill zero bytes selected by other mask. Zero value is 0xc.
7521 LHSMask &= ~RHSUsedLanes;
7522 RHSMask &= ~LHSUsedLanes;
7523 // Add 4 to each active LHS lane
7524 LHSMask |= LHSUsedLanes & 0x04040404;
7526 uint32_t Sel = LHSMask | RHSMask;
7529 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
7530 LHS.getOperand(0), RHS.getOperand(0),
7531 DAG.getConstant(Sel, DL, MVT::i32));
7539 // TODO: This could be a generic combine with a predicate for extracting the
7540 // high half of an integer being free.
7542 // (or i64:x, (zero_extend i32:y)) ->
7543 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
7544 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
7545 RHS.getOpcode() != ISD::ZERO_EXTEND)
7546 std::swap(LHS, RHS);
7548 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
7549 SDValue ExtSrc = RHS.getOperand(0);
7550 EVT SrcVT = ExtSrc.getValueType();
7551 if (SrcVT == MVT::i32) {
7553 SDValue LowLHS, HiBits;
7554 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
7555 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
7557 DCI.AddToWorklist(LowOr.getNode());
7558 DCI.AddToWorklist(HiBits.getNode());
7560 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
7562 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
7566 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
7569 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
7576 SDValue SITargetLowering::performXorCombine(SDNode *N,
7577 DAGCombinerInfo &DCI) const {
7578 EVT VT = N->getValueType(0);
7582 SDValue LHS = N->getOperand(0);
7583 SDValue RHS = N->getOperand(1);
7585 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
7588 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
7595 // Instructions that will be lowered with a final instruction that zeros the
7596 // high result bits.
7597 // XXX - probably only need to list legal operations.
7598 static bool fp16SrcZerosHighBits(unsigned Opc) {
7607 case ISD::FCANONICALIZE:
7609 case ISD::UINT_TO_FP:
7610 case ISD::SINT_TO_FP:
7612 // Fabs is lowered to a bit operation, but it's an and which will clear the
7613 // high bits anyway.
7627 case ISD::FNEARBYINT:
7632 case AMDGPUISD::FRACT:
7633 case AMDGPUISD::CLAMP:
7634 case AMDGPUISD::COS_HW:
7635 case AMDGPUISD::SIN_HW:
7636 case AMDGPUISD::FMIN3:
7637 case AMDGPUISD::FMAX3:
7638 case AMDGPUISD::FMED3:
7639 case AMDGPUISD::FMAD_FTZ:
7640 case AMDGPUISD::RCP:
7641 case AMDGPUISD::RSQ:
7642 case AMDGPUISD::RCP_IFLAG:
7643 case AMDGPUISD::LDEXP:
7646 // fcopysign, select and others may be lowered to 32-bit bit operations
7647 // which don't zero the high bits.
7652 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
7653 DAGCombinerInfo &DCI) const {
7654 if (!Subtarget->has16BitInsts() ||
7655 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7658 EVT VT = N->getValueType(0);
7662 SDValue Src = N->getOperand(0);
7663 if (Src.getValueType() != MVT::i16)
7666 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
7667 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
7668 if (Src.getOpcode() == ISD::BITCAST) {
7669 SDValue BCSrc = Src.getOperand(0);
7670 if (BCSrc.getValueType() == MVT::f16 &&
7671 fp16SrcZerosHighBits(BCSrc.getOpcode()))
7672 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
7678 SDValue SITargetLowering::performClassCombine(SDNode *N,
7679 DAGCombinerInfo &DCI) const {
7680 SelectionDAG &DAG = DCI.DAG;
7681 SDValue Mask = N->getOperand(1);
7683 // fp_class x, 0 -> false
7684 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
7685 if (CMask->isNullValue())
7686 return DAG.getConstant(0, SDLoc(N), MVT::i1);
7689 if (N->getOperand(0).isUndef())
7690 return DAG.getUNDEF(MVT::i1);
7695 SDValue SITargetLowering::performRcpCombine(SDNode *N,
7696 DAGCombinerInfo &DCI) const {
7697 EVT VT = N->getValueType(0);
7698 SDValue N0 = N->getOperand(0);
7703 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
7704 N0.getOpcode() == ISD::SINT_TO_FP)) {
7705 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
7709 return AMDGPUTargetLowering::performRcpCombine(N, DCI);
7712 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
7713 unsigned MaxDepth) const {
7714 unsigned Opcode = Op.getOpcode();
7715 if (Opcode == ISD::FCANONICALIZE)
7718 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
7719 auto F = CFP->getValueAPF();
7720 if (F.isNaN() && F.isSignaling())
7722 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType());
7725 // If source is a result of another standard FP operation it is already in
7731 // These will flush denorms if required.
7743 case ISD::FP_EXTEND:
7744 case AMDGPUISD::FMUL_LEGACY:
7745 case AMDGPUISD::FMAD_FTZ:
7746 case AMDGPUISD::RCP:
7747 case AMDGPUISD::RSQ:
7748 case AMDGPUISD::RSQ_CLAMP:
7749 case AMDGPUISD::RCP_LEGACY:
7750 case AMDGPUISD::RSQ_LEGACY:
7751 case AMDGPUISD::RCP_IFLAG:
7752 case AMDGPUISD::TRIG_PREOP:
7753 case AMDGPUISD::DIV_SCALE:
7754 case AMDGPUISD::DIV_FMAS:
7755 case AMDGPUISD::DIV_FIXUP:
7756 case AMDGPUISD::FRACT:
7757 case AMDGPUISD::LDEXP:
7758 case AMDGPUISD::CVT_PKRTZ_F16_F32:
7759 case AMDGPUISD::CVT_F32_UBYTE0:
7760 case AMDGPUISD::CVT_F32_UBYTE1:
7761 case AMDGPUISD::CVT_F32_UBYTE2:
7762 case AMDGPUISD::CVT_F32_UBYTE3:
7765 // It can/will be lowered or combined as a bit operation.
7766 // Need to check their input recursively to handle.
7769 case ISD::FCOPYSIGN:
7770 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
7775 return Op.getValueType().getScalarType() != MVT::f16;
7779 case ISD::FMINNUM_IEEE:
7780 case ISD::FMAXNUM_IEEE:
7781 case AMDGPUISD::CLAMP:
7782 case AMDGPUISD::FMED3:
7783 case AMDGPUISD::FMAX3:
7784 case AMDGPUISD::FMIN3: {
7785 // FIXME: Shouldn't treat the generic operations different based these.
7786 // However, we aren't really required to flush the result from
7789 // snans will be quieted, so we only need to worry about denormals.
7790 if (Subtarget->supportsMinMaxDenormModes() ||
7791 denormalsEnabledForType(Op.getValueType()))
7794 // Flushing may be required.
7795 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
7796 // targets need to check their input recursively.
7798 // FIXME: Does this apply with clamp? It's implemented with max.
7799 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
7800 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
7807 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
7808 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
7810 case ISD::BUILD_VECTOR: {
7811 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
7812 SDValue SrcOp = Op.getOperand(i);
7813 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
7819 case ISD::EXTRACT_VECTOR_ELT:
7820 case ISD::EXTRACT_SUBVECTOR: {
7821 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
7823 case ISD::INSERT_VECTOR_ELT: {
7824 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
7825 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
7828 // Could be anything.
7831 case ISD::BITCAST: {
7832 // Hack round the mess we make when legalizing extract_vector_elt
7833 SDValue Src = Op.getOperand(0);
7834 if (Src.getValueType() == MVT::i16 &&
7835 Src.getOpcode() == ISD::TRUNCATE) {
7836 SDValue TruncSrc = Src.getOperand(0);
7837 if (TruncSrc.getValueType() == MVT::i32 &&
7838 TruncSrc.getOpcode() == ISD::BITCAST &&
7839 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
7840 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
7846 case ISD::INTRINSIC_WO_CHAIN: {
7847 unsigned IntrinsicID
7848 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7849 // TODO: Handle more intrinsics
7850 switch (IntrinsicID) {
7851 case Intrinsic::amdgcn_cvt_pkrtz:
7852 case Intrinsic::amdgcn_cubeid:
7853 case Intrinsic::amdgcn_frexp_mant:
7854 case Intrinsic::amdgcn_fdot2:
7863 return denormalsEnabledForType(Op.getValueType()) &&
7864 DAG.isKnownNeverSNaN(Op);
7867 llvm_unreachable("invalid operation");
7870 // Constant fold canonicalize.
7871 SDValue SITargetLowering::getCanonicalConstantFP(
7872 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
7873 // Flush denormals to 0 if not enabled.
7874 if (C.isDenormal() && !denormalsEnabledForType(VT))
7875 return DAG.getConstantFP(0.0, SL, VT);
7878 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
7879 if (C.isSignaling()) {
7880 // Quiet a signaling NaN.
7881 // FIXME: Is this supposed to preserve payload bits?
7882 return DAG.getConstantFP(CanonicalQNaN, SL, VT);
7885 // Make sure it is the canonical NaN bitpattern.
7887 // TODO: Can we use -1 as the canonical NaN value since it's an inline
7889 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
7890 return DAG.getConstantFP(CanonicalQNaN, SL, VT);
7893 // Already canonical.
7894 return DAG.getConstantFP(C, SL, VT);
7897 static bool vectorEltWillFoldAway(SDValue Op) {
7898 return Op.isUndef() || isa<ConstantFPSDNode>(Op);
7901 SDValue SITargetLowering::performFCanonicalizeCombine(
7903 DAGCombinerInfo &DCI) const {
7904 SelectionDAG &DAG = DCI.DAG;
7905 SDValue N0 = N->getOperand(0);
7906 EVT VT = N->getValueType(0);
7908 // fcanonicalize undef -> qnan
7910 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
7911 return DAG.getConstantFP(QNaN, SDLoc(N), VT);
7914 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
7915 EVT VT = N->getValueType(0);
7916 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
7919 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
7920 // (fcanonicalize k)
7922 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
7924 // TODO: This could be better with wider vectors that will be split to v2f16,
7925 // and to consider uses since there aren't that many packed operations.
7926 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
7927 isTypeLegal(MVT::v2f16)) {
7930 SDValue Lo = N0.getOperand(0);
7931 SDValue Hi = N0.getOperand(1);
7932 EVT EltVT = Lo.getValueType();
7934 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
7935 for (unsigned I = 0; I != 2; ++I) {
7936 SDValue Op = N0.getOperand(I);
7937 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
7938 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
7939 CFP->getValueAPF());
7940 } else if (Op.isUndef()) {
7941 // Handled below based on what the other operand is.
7944 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
7948 // If one half is undef, and one is constant, perfer a splat vector rather
7949 // than the normal qNaN. If it's a register, prefer 0.0 since that's
7950 // cheaper to use and may be free with a packed operation.
7951 if (NewElts[0].isUndef()) {
7952 if (isa<ConstantFPSDNode>(NewElts[1]))
7953 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
7954 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
7957 if (NewElts[1].isUndef()) {
7958 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
7959 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
7962 return DAG.getBuildVector(VT, SL, NewElts);
7966 unsigned SrcOpc = N0.getOpcode();
7968 // If it's free to do so, push canonicalizes further up the source, which may
7969 // find a canonical source.
7971 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
7973 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
7974 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7975 if (CRHS && N0.hasOneUse()) {
7977 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
7979 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
7980 DCI.AddToWorklist(Canon0.getNode());
7982 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
7986 return isCanonicalized(DAG, N0) ? N0 : SDValue();
7989 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
7992 case ISD::FMAXNUM_IEEE:
7993 return AMDGPUISD::FMAX3;
7995 return AMDGPUISD::SMAX3;
7997 return AMDGPUISD::UMAX3;
7999 case ISD::FMINNUM_IEEE:
8000 return AMDGPUISD::FMIN3;
8002 return AMDGPUISD::SMIN3;
8004 return AMDGPUISD::UMIN3;
8006 llvm_unreachable("Not a min/max opcode");
8010 SDValue SITargetLowering::performIntMed3ImmCombine(
8011 SelectionDAG &DAG, const SDLoc &SL,
8012 SDValue Op0, SDValue Op1, bool Signed) const {
8013 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8017 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8022 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8025 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8029 EVT VT = K0->getValueType(0);
8030 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8031 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8032 return DAG.getNode(Med3Opc, SL, VT,
8033 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8036 // If there isn't a 16-bit med3 operation, convert to 32-bit.
8038 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8040 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8041 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8042 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
8044 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8045 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
8048 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8049 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8052 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8053 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
8060 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
8063 SDValue Op1) const {
8064 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
8068 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
8072 // Ordered >= (although NaN inputs should have folded away by now).
8073 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
8074 if (Cmp == APFloat::cmpGreaterThan)
8077 // TODO: Check IEEE bit enabled?
8078 EVT VT = Op0.getValueType();
8079 if (Subtarget->enableDX10Clamp()) {
8080 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
8081 // hardware fmed3 behavior converting to a min.
8082 // FIXME: Should this be allowing -0.0?
8083 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
8084 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
8087 // med3 for f16 is only available on gfx9+, and not available for v2f16.
8088 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
8089 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
8090 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
8091 // then give the other result, which is different from med3 with a NaN
8093 SDValue Var = Op0.getOperand(0);
8094 if (!DAG.isKnownNeverSNaN(Var))
8097 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8099 if ((!K0->hasOneUse() ||
8100 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
8101 (!K1->hasOneUse() ||
8102 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
8103 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
8104 Var, SDValue(K0, 0), SDValue(K1, 0));
8111 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
8112 DAGCombinerInfo &DCI) const {
8113 SelectionDAG &DAG = DCI.DAG;
8115 EVT VT = N->getValueType(0);
8116 unsigned Opc = N->getOpcode();
8117 SDValue Op0 = N->getOperand(0);
8118 SDValue Op1 = N->getOperand(1);
8120 // Only do this if the inner op has one use since this will just increases
8121 // register pressure for no benefit.
8124 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
8125 !VT.isVector() && VT != MVT::f64 &&
8126 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
8127 // max(max(a, b), c) -> max3(a, b, c)
8128 // min(min(a, b), c) -> min3(a, b, c)
8129 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
8131 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8140 // max(a, max(b, c)) -> max3(a, b, c)
8141 // min(a, min(b, c)) -> min3(a, b, c)
8142 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
8144 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8153 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
8154 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
8155 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
8159 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
8160 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
8164 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
8165 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
8166 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
8167 (Opc == AMDGPUISD::FMIN_LEGACY &&
8168 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
8169 (VT == MVT::f32 || VT == MVT::f64 ||
8170 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
8171 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
8173 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
8180 static bool isClampZeroToOne(SDValue A, SDValue B) {
8181 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
8182 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
8183 // FIXME: Should this be allowing -0.0?
8184 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
8185 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
8192 // FIXME: Should only worry about snans for version with chain.
8193 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
8194 DAGCombinerInfo &DCI) const {
8195 EVT VT = N->getValueType(0);
8196 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
8197 // NaNs. With a NaN input, the order of the operands may change the result.
8199 SelectionDAG &DAG = DCI.DAG;
8202 SDValue Src0 = N->getOperand(0);
8203 SDValue Src1 = N->getOperand(1);
8204 SDValue Src2 = N->getOperand(2);
8206 if (isClampZeroToOne(Src0, Src1)) {
8207 // const_a, const_b, x -> clamp is safe in all cases including signaling
8209 // FIXME: Should this be allowing -0.0?
8210 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
8213 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
8214 // handling no dx10-clamp?
8215 if (Subtarget->enableDX10Clamp()) {
8216 // If NaNs is clamped to 0, we are free to reorder the inputs.
8218 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8219 std::swap(Src0, Src1);
8221 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
8222 std::swap(Src1, Src2);
8224 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8225 std::swap(Src0, Src1);
8227 if (isClampZeroToOne(Src1, Src2))
8228 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
8234 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
8235 DAGCombinerInfo &DCI) const {
8236 SDValue Src0 = N->getOperand(0);
8237 SDValue Src1 = N->getOperand(1);
8238 if (Src0.isUndef() && Src1.isUndef())
8239 return DCI.DAG.getUNDEF(N->getValueType(0));
8243 SDValue SITargetLowering::performExtractVectorEltCombine(
8244 SDNode *N, DAGCombinerInfo &DCI) const {
8245 SDValue Vec = N->getOperand(0);
8246 SelectionDAG &DAG = DCI.DAG;
8248 EVT VecVT = Vec.getValueType();
8249 EVT EltVT = VecVT.getVectorElementType();
8251 if ((Vec.getOpcode() == ISD::FNEG ||
8252 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
8254 EVT EltVT = N->getValueType(0);
8255 SDValue Idx = N->getOperand(1);
8256 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8257 Vec.getOperand(0), Idx);
8258 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
8261 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
8263 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
8264 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
8265 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
8266 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
8268 EVT EltVT = N->getValueType(0);
8269 SDValue Idx = N->getOperand(1);
8270 unsigned Opc = Vec.getOpcode();
8275 // TODO: Support other binary operations.
8286 case ISD::FMAXNUM_IEEE:
8287 case ISD::FMINNUM_IEEE: {
8288 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8289 Vec.getOperand(0), Idx);
8290 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8291 Vec.getOperand(1), Idx);
8293 DCI.AddToWorklist(Elt0.getNode());
8294 DCI.AddToWorklist(Elt1.getNode());
8295 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
8300 unsigned VecSize = VecVT.getSizeInBits();
8301 unsigned EltSize = EltVT.getSizeInBits();
8303 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
8304 // This elminates non-constant index and subsequent movrel or scratch access.
8305 // Sub-dword vectors of size 2 dword or less have better implementation.
8306 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
8308 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
8309 !isa<ConstantSDNode>(N->getOperand(1))) {
8311 SDValue Idx = N->getOperand(1);
8312 EVT IdxVT = Idx.getValueType();
8314 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
8315 SDValue IC = DAG.getConstant(I, SL, IdxVT);
8316 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
8320 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
8325 if (!DCI.isBeforeLegalize())
8328 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
8329 // elements. This exposes more load reduction opportunities by replacing
8330 // multiple small extract_vector_elements with a single 32-bit extract.
8331 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
8332 if (isa<MemSDNode>(Vec) &&
8334 EltVT.isByteSized() &&
8336 VecSize % 32 == 0 &&
8338 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
8340 unsigned BitIndex = Idx->getZExtValue() * EltSize;
8341 unsigned EltIdx = BitIndex / 32;
8342 unsigned LeftoverBitIdx = BitIndex % 32;
8345 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
8346 DCI.AddToWorklist(Cast.getNode());
8348 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
8349 DAG.getConstant(EltIdx, SL, MVT::i32));
8350 DCI.AddToWorklist(Elt.getNode());
8351 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
8352 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
8353 DCI.AddToWorklist(Srl.getNode());
8355 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
8356 DCI.AddToWorklist(Trunc.getNode());
8357 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
8364 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
8365 DAGCombinerInfo &DCI) const {
8366 SDValue Vec = N->getOperand(0);
8367 SDValue Idx = N->getOperand(2);
8368 EVT VecVT = Vec.getValueType();
8369 EVT EltVT = VecVT.getVectorElementType();
8370 unsigned VecSize = VecVT.getSizeInBits();
8371 unsigned EltSize = EltVT.getSizeInBits();
8373 // INSERT_VECTOR_ELT (<n x e>, var-idx)
8374 // => BUILD_VECTOR n x select (e, const-idx)
8375 // This elminates non-constant index and subsequent movrel or scratch access.
8376 // Sub-dword vectors of size 2 dword or less have better implementation.
8377 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
8379 if (isa<ConstantSDNode>(Idx) ||
8380 VecSize > 256 || (VecSize <= 64 && EltSize < 32))
8383 SelectionDAG &DAG = DCI.DAG;
8385 SDValue Ins = N->getOperand(1);
8386 EVT IdxVT = Idx.getValueType();
8388 SmallVector<SDValue, 16> Ops;
8389 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
8390 SDValue IC = DAG.getConstant(I, SL, IdxVT);
8391 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
8392 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
8396 return DAG.getBuildVector(VecVT, SL, Ops);
8399 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
8401 const SDNode *N1) const {
8402 EVT VT = N0->getValueType(0);
8404 // Only do this if we are not trying to support denormals. v_mad_f32 does not
8405 // support denormals ever.
8406 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
8407 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
8410 const TargetOptions &Options = DAG.getTarget().Options;
8411 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
8412 (N0->getFlags().hasAllowContract() &&
8413 N1->getFlags().hasAllowContract())) &&
8414 isFMAFasterThanFMulAndFAdd(VT)) {
8421 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
8423 SDValue N0, SDValue N1, SDValue N2,
8425 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
8426 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
8427 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
8428 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
8431 SDValue SITargetLowering::performAddCombine(SDNode *N,
8432 DAGCombinerInfo &DCI) const {
8433 SelectionDAG &DAG = DCI.DAG;
8434 EVT VT = N->getValueType(0);
8436 SDValue LHS = N->getOperand(0);
8437 SDValue RHS = N->getOperand(1);
8439 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
8440 && Subtarget->hasMad64_32() &&
8441 !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
8442 VT.getScalarSizeInBits() <= 64) {
8443 if (LHS.getOpcode() != ISD::MUL)
8444 std::swap(LHS, RHS);
8446 SDValue MulLHS = LHS.getOperand(0);
8447 SDValue MulRHS = LHS.getOperand(1);
8448 SDValue AddRHS = RHS;
8450 // TODO: Maybe restrict if SGPR inputs.
8451 if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
8452 numBitsUnsigned(MulRHS, DAG) <= 32) {
8453 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
8454 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
8455 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
8456 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
8459 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
8460 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
8461 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
8462 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
8463 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
8469 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
8472 // add x, zext (setcc) => addcarry x, 0, setcc
8473 // add x, sext (setcc) => subcarry x, 0, setcc
8474 unsigned Opc = LHS.getOpcode();
8475 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
8476 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
8477 std::swap(RHS, LHS);
8479 Opc = RHS.getOpcode();
8482 case ISD::ZERO_EXTEND:
8483 case ISD::SIGN_EXTEND:
8484 case ISD::ANY_EXTEND: {
8485 auto Cond = RHS.getOperand(0);
8486 if (!isBoolSGPR(Cond))
8488 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
8489 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
8490 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
8491 return DAG.getNode(Opc, SL, VTList, Args);
8493 case ISD::ADDCARRY: {
8494 // add x, (addcarry y, 0, cc) => addcarry x, y, cc
8495 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8496 if (!C || C->getZExtValue() != 0) break;
8497 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
8498 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
8504 SDValue SITargetLowering::performSubCombine(SDNode *N,
8505 DAGCombinerInfo &DCI) const {
8506 SelectionDAG &DAG = DCI.DAG;
8507 EVT VT = N->getValueType(0);
8513 SDValue LHS = N->getOperand(0);
8514 SDValue RHS = N->getOperand(1);
8516 unsigned Opc = LHS.getOpcode();
8517 if (Opc != ISD::SUBCARRY)
8518 std::swap(RHS, LHS);
8520 if (LHS.getOpcode() == ISD::SUBCARRY) {
8521 // sub (subcarry x, 0, cc), y => subcarry x, y, cc
8522 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8523 if (!C || C->getZExtValue() != 0)
8525 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
8526 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
8531 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
8532 DAGCombinerInfo &DCI) const {
8534 if (N->getValueType(0) != MVT::i32)
8537 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8538 if (!C || C->getZExtValue() != 0)
8541 SelectionDAG &DAG = DCI.DAG;
8542 SDValue LHS = N->getOperand(0);
8544 // addcarry (add x, y), 0, cc => addcarry x, y, cc
8545 // subcarry (sub x, y), 0, cc => subcarry x, y, cc
8546 unsigned LHSOpc = LHS.getOpcode();
8547 unsigned Opc = N->getOpcode();
8548 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
8549 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
8550 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
8551 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
8556 SDValue SITargetLowering::performFAddCombine(SDNode *N,
8557 DAGCombinerInfo &DCI) const {
8558 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8561 SelectionDAG &DAG = DCI.DAG;
8562 EVT VT = N->getValueType(0);
8565 SDValue LHS = N->getOperand(0);
8566 SDValue RHS = N->getOperand(1);
8568 // These should really be instruction patterns, but writing patterns with
8569 // source modiifiers is a pain.
8571 // fadd (fadd (a, a), b) -> mad 2.0, a, b
8572 if (LHS.getOpcode() == ISD::FADD) {
8573 SDValue A = LHS.getOperand(0);
8574 if (A == LHS.getOperand(1)) {
8575 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
8577 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
8578 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
8583 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
8584 if (RHS.getOpcode() == ISD::FADD) {
8585 SDValue A = RHS.getOperand(0);
8586 if (A == RHS.getOperand(1)) {
8587 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
8589 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
8590 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
8598 SDValue SITargetLowering::performFSubCombine(SDNode *N,
8599 DAGCombinerInfo &DCI) const {
8600 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8603 SelectionDAG &DAG = DCI.DAG;
8605 EVT VT = N->getValueType(0);
8606 assert(!VT.isVector());
8608 // Try to get the fneg to fold into the source modifier. This undoes generic
8609 // DAG combines and folds them into the mad.
8611 // Only do this if we are not trying to support denormals. v_mad_f32 does
8612 // not support denormals ever.
8613 SDValue LHS = N->getOperand(0);
8614 SDValue RHS = N->getOperand(1);
8615 if (LHS.getOpcode() == ISD::FADD) {
8616 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
8617 SDValue A = LHS.getOperand(0);
8618 if (A == LHS.getOperand(1)) {
8619 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
8621 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
8622 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8624 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
8629 if (RHS.getOpcode() == ISD::FADD) {
8630 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
8632 SDValue A = RHS.getOperand(0);
8633 if (A == RHS.getOperand(1)) {
8634 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
8636 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
8637 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
8645 SDValue SITargetLowering::performFMACombine(SDNode *N,
8646 DAGCombinerInfo &DCI) const {
8647 SelectionDAG &DAG = DCI.DAG;
8648 EVT VT = N->getValueType(0);
8651 if (!Subtarget->hasDotInsts() || VT != MVT::f32)
8654 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
8655 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
8656 SDValue Op1 = N->getOperand(0);
8657 SDValue Op2 = N->getOperand(1);
8658 SDValue FMA = N->getOperand(2);
8660 if (FMA.getOpcode() != ISD::FMA ||
8661 Op1.getOpcode() != ISD::FP_EXTEND ||
8662 Op2.getOpcode() != ISD::FP_EXTEND)
8665 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
8666 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
8667 // is sufficient to allow generaing fdot2.
8668 const TargetOptions &Options = DAG.getTarget().Options;
8669 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
8670 (N->getFlags().hasAllowContract() &&
8671 FMA->getFlags().hasAllowContract())) {
8672 Op1 = Op1.getOperand(0);
8673 Op2 = Op2.getOperand(0);
8674 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8675 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8678 SDValue Vec1 = Op1.getOperand(0);
8679 SDValue Idx1 = Op1.getOperand(1);
8680 SDValue Vec2 = Op2.getOperand(0);
8682 SDValue FMAOp1 = FMA.getOperand(0);
8683 SDValue FMAOp2 = FMA.getOperand(1);
8684 SDValue FMAAcc = FMA.getOperand(2);
8686 if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
8687 FMAOp2.getOpcode() != ISD::FP_EXTEND)
8690 FMAOp1 = FMAOp1.getOperand(0);
8691 FMAOp2 = FMAOp2.getOperand(0);
8692 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8693 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8696 SDValue Vec3 = FMAOp1.getOperand(0);
8697 SDValue Vec4 = FMAOp2.getOperand(0);
8698 SDValue Idx2 = FMAOp1.getOperand(1);
8700 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
8701 // Idx1 and Idx2 cannot be the same.
8705 if (Vec1 == Vec2 || Vec3 == Vec4)
8708 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
8711 if ((Vec1 == Vec3 && Vec2 == Vec4) ||
8712 (Vec1 == Vec4 && Vec2 == Vec3)) {
8713 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
8714 DAG.getTargetConstant(0, SL, MVT::i1));
8720 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
8721 DAGCombinerInfo &DCI) const {
8722 SelectionDAG &DAG = DCI.DAG;
8725 SDValue LHS = N->getOperand(0);
8726 SDValue RHS = N->getOperand(1);
8727 EVT VT = LHS.getValueType();
8728 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
8730 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
8732 CRHS = dyn_cast<ConstantSDNode>(LHS);
8734 std::swap(LHS, RHS);
8735 CC = getSetCCSwappedOperands(CC);
8740 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
8741 isBoolSGPR(LHS.getOperand(0))) {
8742 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
8743 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
8744 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
8745 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
8746 if ((CRHS->isAllOnesValue() &&
8747 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
8748 (CRHS->isNullValue() &&
8749 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
8750 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
8751 DAG.getConstant(-1, SL, MVT::i1));
8752 if ((CRHS->isAllOnesValue() &&
8753 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
8754 (CRHS->isNullValue() &&
8755 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
8756 return LHS.getOperand(0);
8759 uint64_t CRHSVal = CRHS->getZExtValue();
8760 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8761 LHS.getOpcode() == ISD::SELECT &&
8762 isa<ConstantSDNode>(LHS.getOperand(1)) &&
8763 isa<ConstantSDNode>(LHS.getOperand(2)) &&
8764 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
8765 isBoolSGPR(LHS.getOperand(0))) {
8767 // setcc (select cc, CT, CF), CF, eq => xor cc, -1
8768 // setcc (select cc, CT, CF), CF, ne => cc
8769 // setcc (select cc, CT, CF), CT, ne => xor cc, -1
8770 // setcc (select cc, CT, CF), CT, eq => cc
8771 uint64_t CT = LHS.getConstantOperandVal(1);
8772 uint64_t CF = LHS.getConstantOperandVal(2);
8774 if ((CF == CRHSVal && CC == ISD::SETEQ) ||
8775 (CT == CRHSVal && CC == ISD::SETNE))
8776 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
8777 DAG.getConstant(-1, SL, MVT::i1));
8778 if ((CF == CRHSVal && CC == ISD::SETNE) ||
8779 (CT == CRHSVal && CC == ISD::SETEQ))
8780 return LHS.getOperand(0);
8784 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
8788 // Match isinf/isfinite pattern
8789 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
8790 // (fcmp one (fabs x), inf) -> (fp_class x,
8791 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
8792 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
8793 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
8797 const APFloat &APF = CRHS->getValueAPF();
8798 if (APF.isInfinity() && !APF.isNegative()) {
8799 const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
8800 SIInstrFlags::N_INFINITY;
8801 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
8802 SIInstrFlags::P_ZERO |
8803 SIInstrFlags::N_NORMAL |
8804 SIInstrFlags::P_NORMAL |
8805 SIInstrFlags::N_SUBNORMAL |
8806 SIInstrFlags::P_SUBNORMAL;
8807 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
8808 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
8809 DAG.getConstant(Mask, SL, MVT::i32));
8816 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
8817 DAGCombinerInfo &DCI) const {
8818 SelectionDAG &DAG = DCI.DAG;
8820 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
8822 SDValue Src = N->getOperand(0);
8823 SDValue Srl = N->getOperand(0);
8824 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
8825 Srl = Srl.getOperand(0);
8827 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
8828 if (Srl.getOpcode() == ISD::SRL) {
8829 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
8830 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
8831 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
8833 if (const ConstantSDNode *C =
8834 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
8835 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
8838 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
8839 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
8840 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
8846 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
8849 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
8850 !DCI.isBeforeLegalizeOps());
8851 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8852 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
8853 DCI.CommitTargetLoweringOpt(TLO);
8859 SDValue SITargetLowering::performClampCombine(SDNode *N,
8860 DAGCombinerInfo &DCI) const {
8861 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
8865 const APFloat &F = CSrc->getValueAPF();
8866 APFloat Zero = APFloat::getZero(F.getSemantics());
8867 APFloat::cmpResult Cmp0 = F.compare(Zero);
8868 if (Cmp0 == APFloat::cmpLessThan ||
8869 (Cmp0 == APFloat::cmpUnordered && Subtarget->enableDX10Clamp())) {
8870 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
8873 APFloat One(F.getSemantics(), "1.0");
8874 APFloat::cmpResult Cmp1 = F.compare(One);
8875 if (Cmp1 == APFloat::cmpGreaterThan)
8876 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
8878 return SDValue(CSrc, 0);
8882 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
8883 DAGCombinerInfo &DCI) const {
8884 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
8887 switch (N->getOpcode()) {
8889 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
8891 return performAddCombine(N, DCI);
8893 return performSubCombine(N, DCI);
8896 return performAddCarrySubCarryCombine(N, DCI);
8898 return performFAddCombine(N, DCI);
8900 return performFSubCombine(N, DCI);
8902 return performSetCCCombine(N, DCI);
8905 case ISD::FMAXNUM_IEEE:
8906 case ISD::FMINNUM_IEEE:
8911 case AMDGPUISD::FMIN_LEGACY:
8912 case AMDGPUISD::FMAX_LEGACY:
8913 return performMinMaxCombine(N, DCI);
8915 return performFMACombine(N, DCI);
8917 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
8922 case ISD::ATOMIC_LOAD:
8923 case ISD::ATOMIC_STORE:
8924 case ISD::ATOMIC_CMP_SWAP:
8925 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
8926 case ISD::ATOMIC_SWAP:
8927 case ISD::ATOMIC_LOAD_ADD:
8928 case ISD::ATOMIC_LOAD_SUB:
8929 case ISD::ATOMIC_LOAD_AND:
8930 case ISD::ATOMIC_LOAD_OR:
8931 case ISD::ATOMIC_LOAD_XOR:
8932 case ISD::ATOMIC_LOAD_NAND:
8933 case ISD::ATOMIC_LOAD_MIN:
8934 case ISD::ATOMIC_LOAD_MAX:
8935 case ISD::ATOMIC_LOAD_UMIN:
8936 case ISD::ATOMIC_LOAD_UMAX:
8937 case AMDGPUISD::ATOMIC_INC:
8938 case AMDGPUISD::ATOMIC_DEC:
8939 case AMDGPUISD::ATOMIC_LOAD_FADD:
8940 case AMDGPUISD::ATOMIC_LOAD_FMIN:
8941 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
8942 if (DCI.isBeforeLegalize())
8944 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
8946 return performAndCombine(N, DCI);
8948 return performOrCombine(N, DCI);
8950 return performXorCombine(N, DCI);
8951 case ISD::ZERO_EXTEND:
8952 return performZeroExtendCombine(N, DCI);
8953 case AMDGPUISD::FP_CLASS:
8954 return performClassCombine(N, DCI);
8955 case ISD::FCANONICALIZE:
8956 return performFCanonicalizeCombine(N, DCI);
8957 case AMDGPUISD::RCP:
8958 return performRcpCombine(N, DCI);
8959 case AMDGPUISD::FRACT:
8960 case AMDGPUISD::RSQ:
8961 case AMDGPUISD::RCP_LEGACY:
8962 case AMDGPUISD::RSQ_LEGACY:
8963 case AMDGPUISD::RCP_IFLAG:
8964 case AMDGPUISD::RSQ_CLAMP:
8965 case AMDGPUISD::LDEXP: {
8966 SDValue Src = N->getOperand(0);
8971 case ISD::SINT_TO_FP:
8972 case ISD::UINT_TO_FP:
8973 return performUCharToFloatCombine(N, DCI);
8974 case AMDGPUISD::CVT_F32_UBYTE0:
8975 case AMDGPUISD::CVT_F32_UBYTE1:
8976 case AMDGPUISD::CVT_F32_UBYTE2:
8977 case AMDGPUISD::CVT_F32_UBYTE3:
8978 return performCvtF32UByteNCombine(N, DCI);
8979 case AMDGPUISD::FMED3:
8980 return performFMed3Combine(N, DCI);
8981 case AMDGPUISD::CVT_PKRTZ_F16_F32:
8982 return performCvtPkRTZCombine(N, DCI);
8983 case AMDGPUISD::CLAMP:
8984 return performClampCombine(N, DCI);
8985 case ISD::SCALAR_TO_VECTOR: {
8986 SelectionDAG &DAG = DCI.DAG;
8987 EVT VT = N->getValueType(0);
8989 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
8990 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
8992 SDValue Src = N->getOperand(0);
8993 EVT EltVT = Src.getValueType();
8994 if (EltVT == MVT::f16)
8995 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
8997 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
8998 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
9003 case ISD::EXTRACT_VECTOR_ELT:
9004 return performExtractVectorEltCombine(N, DCI);
9005 case ISD::INSERT_VECTOR_ELT:
9006 return performInsertVectorEltCombine(N, DCI);
9008 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9011 /// Helper function for adjustWritemask
9012 static unsigned SubIdx2Lane(unsigned Idx) {
9015 case AMDGPU::sub0: return 0;
9016 case AMDGPU::sub1: return 1;
9017 case AMDGPU::sub2: return 2;
9018 case AMDGPU::sub3: return 3;
9019 case AMDGPU::sub4: return 4; // Possible with TFE/LWE
9023 /// Adjust the writemask of MIMG instructions
9024 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
9025 SelectionDAG &DAG) const {
9026 unsigned Opcode = Node->getMachineOpcode();
9028 // Subtract 1 because the vdata output is not a MachineSDNode operand.
9029 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
9030 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
9031 return Node; // not implemented for D16
9033 SDNode *Users[5] = { nullptr };
9035 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
9036 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
9037 unsigned NewDmask = 0;
9038 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
9039 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
9040 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
9041 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
9042 unsigned TFCLane = 0;
9043 bool HasChain = Node->getNumValues() > 1;
9045 if (OldDmask == 0) {
9046 // These are folded out, but on the chance it happens don't assert.
9050 unsigned OldBitsSet = countPopulation(OldDmask);
9051 // Work out which is the TFE/LWE lane if that is enabled.
9053 TFCLane = OldBitsSet;
9056 // Try to figure out the used register components
9057 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
9060 // Don't look at users of the chain.
9061 if (I.getUse().getResNo() != 0)
9064 // Abort if we can't understand the usage
9065 if (!I->isMachineOpcode() ||
9066 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
9069 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
9070 // Note that subregs are packed, i.e. Lane==0 is the first bit set
9071 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
9073 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
9075 // Check if the use is for the TFE/LWE generated result at VGPRn+1.
9076 if (UsesTFC && Lane == TFCLane) {
9079 // Set which texture component corresponds to the lane.
9081 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
9082 Comp = countTrailingZeros(Dmask);
9083 Dmask &= ~(1 << Comp);
9086 // Abort if we have more than one user per component.
9091 NewDmask |= 1 << Comp;
9095 // Don't allow 0 dmask, as hardware assumes one channel enabled.
9096 bool NoChannels = !NewDmask;
9098 // If the original dmask has one channel - then nothing to do
9099 if (OldBitsSet == 1)
9101 // Use an arbitrary dmask - required for the instruction to work
9104 // Abort if there's no change
9105 if (NewDmask == OldDmask)
9108 unsigned BitsSet = countPopulation(NewDmask);
9110 // Check for TFE or LWE - increase the number of channels by one to account
9111 // for the extra return value
9112 // This will need adjustment for D16 if this is also included in
9113 // adjustWriteMask (this function) but at present D16 are excluded.
9114 unsigned NewChannels = BitsSet + UsesTFC;
9117 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
9118 assert(NewOpcode != -1 &&
9119 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
9120 "failed to find equivalent MIMG op");
9122 // Adjust the writemask in the node
9123 SmallVector<SDValue, 12> Ops;
9124 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
9125 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
9126 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
9128 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
9130 MVT ResultVT = NewChannels == 1 ?
9131 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
9132 NewChannels == 5 ? 8 : NewChannels);
9133 SDVTList NewVTList = HasChain ?
9134 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
9137 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
9142 DAG.setNodeMemRefs(NewNode, Node->memoperands());
9143 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
9146 if (NewChannels == 1) {
9147 assert(Node->hasNUsesOfValue(1, 0));
9148 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
9149 SDLoc(Node), Users[Lane]->getValueType(0),
9150 SDValue(NewNode, 0));
9151 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
9155 // Update the users of the node with the new indices
9156 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
9157 SDNode *User = Users[i];
9159 // Handle the special case of NoChannels. We set NewDmask to 1 above, but
9160 // Users[0] is still nullptr because channel 0 doesn't really have a use.
9161 if (i || !NoChannels)
9164 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
9165 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
9170 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
9171 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
9172 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
9173 case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
9177 DAG.RemoveDeadNode(Node);
9181 static bool isFrameIndexOp(SDValue Op) {
9182 if (Op.getOpcode() == ISD::AssertZext)
9183 Op = Op.getOperand(0);
9185 return isa<FrameIndexSDNode>(Op);
9188 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
9189 /// with frame index operands.
9190 /// LLVM assumes that inputs are to these instructions are registers.
9191 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
9192 SelectionDAG &DAG) const {
9193 if (Node->getOpcode() == ISD::CopyToReg) {
9194 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
9195 SDValue SrcVal = Node->getOperand(2);
9197 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
9198 // to try understanding copies to physical registers.
9199 if (SrcVal.getValueType() == MVT::i1 &&
9200 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
9202 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
9203 SDValue VReg = DAG.getRegister(
9204 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
9206 SDNode *Glued = Node->getGluedNode();
9208 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
9209 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
9211 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
9212 VReg, ToVReg.getValue(1));
9213 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
9214 DAG.RemoveDeadNode(Node);
9215 return ToResultReg.getNode();
9219 SmallVector<SDValue, 8> Ops;
9220 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
9221 if (!isFrameIndexOp(Node->getOperand(i))) {
9222 Ops.push_back(Node->getOperand(i));
9227 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
9228 Node->getOperand(i).getValueType(),
9229 Node->getOperand(i)), 0));
9232 return DAG.UpdateNodeOperands(Node, Ops);
9235 /// Fold the instructions after selecting them.
9236 /// Returns null if users were already updated.
9237 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
9238 SelectionDAG &DAG) const {
9239 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9240 unsigned Opcode = Node->getMachineOpcode();
9242 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
9243 !TII->isGather4(Opcode)) {
9244 return adjustWritemask(Node, DAG);
9247 if (Opcode == AMDGPU::INSERT_SUBREG ||
9248 Opcode == AMDGPU::REG_SEQUENCE) {
9249 legalizeTargetIndependentNode(Node, DAG);
9254 case AMDGPU::V_DIV_SCALE_F32:
9255 case AMDGPU::V_DIV_SCALE_F64: {
9256 // Satisfy the operand register constraint when one of the inputs is
9257 // undefined. Ordinarily each undef value will have its own implicit_def of
9258 // a vreg, so force these to use a single register.
9259 SDValue Src0 = Node->getOperand(0);
9260 SDValue Src1 = Node->getOperand(1);
9261 SDValue Src2 = Node->getOperand(2);
9263 if ((Src0.isMachineOpcode() &&
9264 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
9265 (Src0 == Src1 || Src0 == Src2))
9268 MVT VT = Src0.getValueType().getSimpleVT();
9269 const TargetRegisterClass *RC = getRegClassFor(VT);
9271 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
9272 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
9274 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
9275 UndefReg, Src0, SDValue());
9277 // src0 must be the same register as src1 or src2, even if the value is
9278 // undefined, so make sure we don't violate this constraint.
9279 if (Src0.isMachineOpcode() &&
9280 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
9281 if (Src1.isMachineOpcode() &&
9282 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
9284 else if (Src2.isMachineOpcode() &&
9285 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
9288 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
9295 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
9296 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
9297 Ops.push_back(Node->getOperand(I));
9299 Ops.push_back(ImpDef.getValue(1));
9300 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
9309 /// Assign the register class depending on the number of
9310 /// bits set in the writemask
9311 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9312 SDNode *Node) const {
9313 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9315 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
9317 if (TII->isVOP3(MI.getOpcode())) {
9318 // Make sure constant bus requirements are respected.
9319 TII->legalizeOperandsVOP3(MRI, MI);
9323 // Replace unused atomics with the no return version.
9324 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
9325 if (NoRetAtomicOp != -1) {
9326 if (!Node->hasAnyUseOfValue(0)) {
9327 MI.setDesc(TII->get(NoRetAtomicOp));
9328 MI.RemoveOperand(0);
9332 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
9333 // instruction, because the return type of these instructions is a vec2 of
9334 // the memory type, so it can be tied to the input operand.
9335 // This means these instructions always have a use, so we need to add a
9336 // special case to check if the atomic has only one extract_subreg use,
9337 // which itself has no uses.
9338 if ((Node->hasNUsesOfValue(1, 0) &&
9339 Node->use_begin()->isMachineOpcode() &&
9340 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
9341 !Node->use_begin()->hasAnyUseOfValue(0))) {
9342 unsigned Def = MI.getOperand(0).getReg();
9344 // Change this into a noret atomic.
9345 MI.setDesc(TII->get(NoRetAtomicOp));
9346 MI.RemoveOperand(0);
9348 // If we only remove the def operand from the atomic instruction, the
9349 // extract_subreg will be left with a use of a vreg without a def.
9350 // So we need to insert an implicit_def to avoid machine verifier
9352 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
9353 TII->get(AMDGPU::IMPLICIT_DEF), Def);
9359 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
9361 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
9362 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
9365 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
9367 SDValue Ptr) const {
9368 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9370 // Build the half of the subregister with the constants before building the
9371 // full 128-bit register. If we are building multiple resource descriptors,
9372 // this will allow CSEing of the 2-component register.
9373 const SDValue Ops0[] = {
9374 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
9375 buildSMovImm32(DAG, DL, 0),
9376 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
9377 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
9378 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
9381 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
9382 MVT::v2i32, Ops0), 0);
9384 // Combine the constants and the pointer.
9385 const SDValue Ops1[] = {
9386 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
9388 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
9390 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
9393 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
9396 /// Return a resource descriptor with the 'Add TID' bit enabled
9397 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
9398 /// of the resource descriptor) to create an offset, which is added to
9399 /// the resource pointer.
9400 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
9401 SDValue Ptr, uint32_t RsrcDword1,
9402 uint64_t RsrcDword2And3) const {
9403 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
9404 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
9406 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
9407 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
9411 SDValue DataLo = buildSMovImm32(DAG, DL,
9412 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
9413 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
9415 const SDValue Ops[] = {
9416 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
9418 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
9420 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
9422 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
9424 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
9427 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
9430 //===----------------------------------------------------------------------===//
9431 // SI Inline Assembly Support
9432 //===----------------------------------------------------------------------===//
9434 std::pair<unsigned, const TargetRegisterClass *>
9435 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9436 StringRef Constraint,
9438 const TargetRegisterClass *RC = nullptr;
9439 if (Constraint.size() == 1) {
9440 switch (Constraint[0]) {
9442 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9445 switch (VT.getSizeInBits()) {
9447 return std::make_pair(0U, nullptr);
9450 RC = &AMDGPU::SReg_32_XM0RegClass;
9453 RC = &AMDGPU::SGPR_64RegClass;
9456 RC = &AMDGPU::SReg_128RegClass;
9459 RC = &AMDGPU::SReg_256RegClass;
9462 RC = &AMDGPU::SReg_512RegClass;
9467 switch (VT.getSizeInBits()) {
9469 return std::make_pair(0U, nullptr);
9472 RC = &AMDGPU::VGPR_32RegClass;
9475 RC = &AMDGPU::VReg_64RegClass;
9478 RC = &AMDGPU::VReg_96RegClass;
9481 RC = &AMDGPU::VReg_128RegClass;
9484 RC = &AMDGPU::VReg_256RegClass;
9487 RC = &AMDGPU::VReg_512RegClass;
9492 // We actually support i128, i16 and f16 as inline parameters
9493 // even if they are not reported as legal
9494 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
9495 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
9496 return std::make_pair(0U, RC);
9499 if (Constraint.size() > 1) {
9500 if (Constraint[1] == 'v') {
9501 RC = &AMDGPU::VGPR_32RegClass;
9502 } else if (Constraint[1] == 's') {
9503 RC = &AMDGPU::SGPR_32RegClass;
9508 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
9509 if (!Failed && Idx < RC->getNumRegs())
9510 return std::make_pair(RC->getRegister(Idx), RC);
9513 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9516 SITargetLowering::ConstraintType
9517 SITargetLowering::getConstraintType(StringRef Constraint) const {
9518 if (Constraint.size() == 1) {
9519 switch (Constraint[0]) {
9523 return C_RegisterClass;
9526 return TargetLowering::getConstraintType(Constraint);
9529 // Figure out which registers should be reserved for stack access. Only after
9530 // the function is legalized do we know all of the non-spill stack objects or if
9531 // calls are present.
9532 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
9533 MachineRegisterInfo &MRI = MF.getRegInfo();
9534 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9535 const MachineFrameInfo &MFI = MF.getFrameInfo();
9536 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
9538 if (Info->isEntryFunction()) {
9539 // Callable functions have fixed registers used for stack access.
9540 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
9543 // We have to assume the SP is needed in case there are calls in the function
9544 // during lowering. Calls are only detected after the function is
9545 // lowered. We're about to reserve registers, so don't bother using it if we
9546 // aren't really going to use it.
9547 bool NeedSP = !Info->isEntryFunction() ||
9548 MFI.hasVarSizedObjects() ||
9552 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
9553 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
9555 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
9556 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
9557 Info->getStackPtrOffsetReg()));
9558 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
9561 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
9562 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
9563 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
9564 Info->getScratchWaveOffsetReg());
9566 Info->limitOccupancy(MF);
9568 TargetLoweringBase::finalizeLowering(MF);
9571 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
9573 const APInt &DemandedElts,
9574 const SelectionDAG &DAG,
9575 unsigned Depth) const {
9576 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
9579 if (getSubtarget()->enableHugePrivateBuffer())
9582 // Technically it may be possible to have a dispatch with a single workitem
9583 // that uses the full private memory size, but that's not really useful. We
9584 // can't use vaddr in MUBUF instructions if we don't know the address
9585 // calculation won't overflow, so assume the sign bit is never set.
9586 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);
9589 LLVM_ATTRIBUTE_UNUSED
9590 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
9591 assert(N->getOpcode() == ISD::CopyFromReg);
9593 // Follow the chain until we find an INLINEASM node.
9594 N = N->getOperand(0).getNode();
9595 if (N->getOpcode() == ISD::INLINEASM)
9597 } while (N->getOpcode() == ISD::CopyFromReg);
9601 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
9602 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
9604 switch (N->getOpcode()) {
9605 case ISD::CopyFromReg:
9607 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
9608 const MachineFunction * MF = FLI->MF;
9609 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
9610 const MachineRegisterInfo &MRI = MF->getRegInfo();
9611 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
9612 unsigned Reg = R->getReg();
9613 if (TRI.isPhysicalRegister(Reg))
9614 return !TRI.isSGPRReg(MRI, Reg);
9616 if (MRI.isLiveIn(Reg)) {
9617 // workitem.id.x workitem.id.y workitem.id.z
9618 // Any VGPR formal argument is also considered divergent
9619 if (!TRI.isSGPRReg(MRI, Reg))
9621 // Formal arguments of non-entry functions
9622 // are conservatively considered divergent
9623 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
9627 const Value *V = FLI->getValueFromVirtualReg(Reg);
9629 return KDA->isDivergent(V);
9630 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
9631 return !TRI.isSGPRReg(MRI, Reg);
9635 const LoadSDNode *L = cast<LoadSDNode>(N);
9636 unsigned AS = L->getAddressSpace();
9637 // A flat load may access private memory.
9638 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
9640 case ISD::CALLSEQ_END:
9643 case ISD::INTRINSIC_WO_CHAIN:
9647 return AMDGPU::isIntrinsicSourceOfDivergence(
9648 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
9649 case ISD::INTRINSIC_W_CHAIN:
9650 return AMDGPU::isIntrinsicSourceOfDivergence(
9651 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
9652 // In some cases intrinsics that are a source of divergence have been
9653 // lowered to AMDGPUISD so we also need to check those too.
9654 case AMDGPUISD::INTERP_MOV:
9655 case AMDGPUISD::INTERP_P1:
9656 case AMDGPUISD::INTERP_P2:
9662 bool SITargetLowering::denormalsEnabledForType(EVT VT) const {
9663 switch (VT.getScalarType().getSimpleVT().SimpleTy) {
9665 return Subtarget->hasFP32Denormals();
9667 return Subtarget->hasFP64Denormals();
9669 return Subtarget->hasFP16Denormals();
9675 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
9676 const SelectionDAG &DAG,
9678 unsigned Depth) const {
9679 if (Op.getOpcode() == AMDGPUISD::CLAMP) {
9680 if (Subtarget->enableDX10Clamp())
9681 return true; // Clamped to 0.
9682 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
9685 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,