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 //===----------------------------------------------------------------------===//
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);
160 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
161 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
162 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
163 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
164 setOperationAction(ISD::STORE, MVT::i1, Custom);
166 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
167 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
168 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
169 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
170 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
171 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
172 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
173 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
174 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
175 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
177 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
178 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
180 setOperationAction(ISD::SELECT, MVT::i1, Promote);
181 setOperationAction(ISD::SELECT, MVT::i64, Custom);
182 setOperationAction(ISD::SELECT, MVT::f64, Promote);
183 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
185 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
186 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
187 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
188 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
189 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
191 setOperationAction(ISD::SETCC, MVT::i1, Promote);
192 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
193 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
194 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
196 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
197 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
201 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
208 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
209 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
210 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
211 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
213 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
214 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
215 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
217 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
218 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
219 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
220 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
222 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
223 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
224 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
225 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
226 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
227 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
229 setOperationAction(ISD::UADDO, MVT::i32, Legal);
230 setOperationAction(ISD::USUBO, MVT::i32, Legal);
232 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
233 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
236 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
237 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
240 // We only support LOAD/STORE and vector manipulation ops for vectors
241 // with > 4 elements.
242 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
243 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16 }) {
244 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
248 case ISD::BUILD_VECTOR:
250 case ISD::EXTRACT_VECTOR_ELT:
251 case ISD::INSERT_VECTOR_ELT:
252 case ISD::INSERT_SUBVECTOR:
253 case ISD::EXTRACT_SUBVECTOR:
254 case ISD::SCALAR_TO_VECTOR:
256 case ISD::CONCAT_VECTORS:
257 setOperationAction(Op, VT, Custom);
260 setOperationAction(Op, VT, Expand);
266 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
268 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
269 // is expanded to avoid having two separate loops in case the index is a VGPR.
271 // Most operations are naturally 32-bit vector operations. We only support
272 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
273 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
274 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
275 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
277 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
278 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
280 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
281 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
283 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
284 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
287 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
288 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
289 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
290 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
292 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
293 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
295 // Avoid stack access for these.
296 // TODO: Generalize to more vector types.
297 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
298 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
299 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
300 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
302 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
303 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
304 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
305 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
306 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
308 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
309 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
310 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
312 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
313 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
314 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
315 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
317 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
318 // and output demarshalling
319 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
320 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
322 // We can't return success/failure, only the old value,
323 // let LLVM add the comparison
324 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
325 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
327 if (Subtarget->hasFlatAddressSpace()) {
328 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
329 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
332 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
333 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
335 // On SI this is s_memtime and s_memrealtime on VI.
336 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
337 setOperationAction(ISD::TRAP, MVT::Other, Custom);
338 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
340 if (Subtarget->has16BitInsts()) {
341 setOperationAction(ISD::FLOG, MVT::f16, Custom);
342 setOperationAction(ISD::FLOG10, MVT::f16, Custom);
345 // v_mad_f32 does not support denormals according to some sources.
346 if (!Subtarget->hasFP32Denormals())
347 setOperationAction(ISD::FMAD, MVT::f32, Legal);
349 if (!Subtarget->hasBFI()) {
350 // fcopysign can be done in a single instruction with BFI.
351 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
352 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
355 if (!Subtarget->hasBCNT(32))
356 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
358 if (!Subtarget->hasBCNT(64))
359 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
361 if (Subtarget->hasFFBH())
362 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
364 if (Subtarget->hasFFBL())
365 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
367 // We only really have 32-bit BFE instructions (and 16-bit on VI).
369 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
370 // effort to match them now. We want this to be false for i64 cases when the
371 // extraction isn't restricted to the upper or lower half. Ideally we would
372 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
373 // span the midpoint are probably relatively rare, so don't worry about them
375 if (Subtarget->hasBFE())
376 setHasExtractBitsInsn(true);
378 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
379 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
381 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
382 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
383 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
384 setOperationAction(ISD::FRINT, MVT::f64, Legal);
386 setOperationAction(ISD::FCEIL, MVT::f64, Custom);
387 setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
388 setOperationAction(ISD::FRINT, MVT::f64, Custom);
389 setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
392 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
394 setOperationAction(ISD::FSIN, MVT::f32, Custom);
395 setOperationAction(ISD::FCOS, MVT::f32, Custom);
396 setOperationAction(ISD::FDIV, MVT::f32, Custom);
397 setOperationAction(ISD::FDIV, MVT::f64, Custom);
399 if (Subtarget->has16BitInsts()) {
400 setOperationAction(ISD::Constant, MVT::i16, Legal);
402 setOperationAction(ISD::SMIN, MVT::i16, Legal);
403 setOperationAction(ISD::SMAX, MVT::i16, Legal);
405 setOperationAction(ISD::UMIN, MVT::i16, Legal);
406 setOperationAction(ISD::UMAX, MVT::i16, Legal);
408 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
409 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
411 setOperationAction(ISD::ROTR, MVT::i16, Promote);
412 setOperationAction(ISD::ROTL, MVT::i16, Promote);
414 setOperationAction(ISD::SDIV, MVT::i16, Promote);
415 setOperationAction(ISD::UDIV, MVT::i16, Promote);
416 setOperationAction(ISD::SREM, MVT::i16, Promote);
417 setOperationAction(ISD::UREM, MVT::i16, Promote);
419 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
420 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
422 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
423 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
424 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
425 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
426 setOperationAction(ISD::CTPOP, MVT::i16, Promote);
428 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
430 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
432 setOperationAction(ISD::LOAD, MVT::i16, Custom);
434 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
436 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
437 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
438 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
439 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
441 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
442 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
443 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
444 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
446 // F16 - Constant Actions.
447 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
449 // F16 - Load/Store Actions.
450 setOperationAction(ISD::LOAD, MVT::f16, Promote);
451 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
452 setOperationAction(ISD::STORE, MVT::f16, Promote);
453 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
455 // F16 - VOP1 Actions.
456 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
457 setOperationAction(ISD::FCOS, MVT::f16, Promote);
458 setOperationAction(ISD::FSIN, MVT::f16, Promote);
459 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
460 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
461 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
462 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
463 setOperationAction(ISD::FROUND, MVT::f16, Custom);
465 // F16 - VOP2 Actions.
466 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
467 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
468 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
469 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
470 setOperationAction(ISD::FDIV, MVT::f16, Custom);
472 // F16 - VOP3 Actions.
473 setOperationAction(ISD::FMA, MVT::f16, Legal);
474 if (!Subtarget->hasFP16Denormals())
475 setOperationAction(ISD::FMAD, MVT::f16, Legal);
477 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
478 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
482 case ISD::BUILD_VECTOR:
484 case ISD::EXTRACT_VECTOR_ELT:
485 case ISD::INSERT_VECTOR_ELT:
486 case ISD::INSERT_SUBVECTOR:
487 case ISD::EXTRACT_SUBVECTOR:
488 case ISD::SCALAR_TO_VECTOR:
490 case ISD::CONCAT_VECTORS:
491 setOperationAction(Op, VT, Custom);
494 setOperationAction(Op, VT, Expand);
500 // XXX - Do these do anything? Vector constants turn into build_vector.
501 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
502 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
504 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
505 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
507 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
508 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
509 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
510 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
512 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
513 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
514 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
515 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
517 setOperationAction(ISD::AND, MVT::v2i16, Promote);
518 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
519 setOperationAction(ISD::OR, MVT::v2i16, Promote);
520 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
521 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
522 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
524 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
525 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
526 setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
527 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
529 setOperationAction(ISD::STORE, MVT::v4i16, Promote);
530 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
531 setOperationAction(ISD::STORE, MVT::v4f16, Promote);
532 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
534 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
535 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
536 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
537 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
539 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
540 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
541 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
543 if (!Subtarget->hasVOP3PInsts()) {
544 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
545 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
548 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
549 // This isn't really legal, but this avoids the legalizer unrolling it (and
550 // allows matching fneg (fabs x) patterns)
551 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
554 if (Subtarget->hasVOP3PInsts()) {
555 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
556 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
557 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
558 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
559 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
560 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
561 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
562 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
563 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
564 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
566 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
567 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
568 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
569 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
570 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
571 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
573 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
574 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
576 setOperationAction(ISD::SHL, MVT::v4i16, Custom);
577 setOperationAction(ISD::SRA, MVT::v4i16, Custom);
578 setOperationAction(ISD::SRL, MVT::v4i16, Custom);
579 setOperationAction(ISD::ADD, MVT::v4i16, Custom);
580 setOperationAction(ISD::SUB, MVT::v4i16, Custom);
581 setOperationAction(ISD::MUL, MVT::v4i16, Custom);
583 setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
584 setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
585 setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
586 setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
588 setOperationAction(ISD::FADD, MVT::v4f16, Custom);
589 setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
590 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
591 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
593 setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
594 setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
597 setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
598 setOperationAction(ISD::FABS, MVT::v4f16, Custom);
600 if (Subtarget->has16BitInsts()) {
601 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
602 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
603 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
604 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
606 // Legalization hack.
607 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
608 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
610 setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
611 setOperationAction(ISD::FABS, MVT::v2f16, Custom);
614 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
615 setOperationAction(ISD::SELECT, VT, Custom);
618 setTargetDAGCombine(ISD::ADD);
619 setTargetDAGCombine(ISD::ADDCARRY);
620 setTargetDAGCombine(ISD::SUB);
621 setTargetDAGCombine(ISD::SUBCARRY);
622 setTargetDAGCombine(ISD::FADD);
623 setTargetDAGCombine(ISD::FSUB);
624 setTargetDAGCombine(ISD::FMINNUM);
625 setTargetDAGCombine(ISD::FMAXNUM);
626 setTargetDAGCombine(ISD::FMA);
627 setTargetDAGCombine(ISD::SMIN);
628 setTargetDAGCombine(ISD::SMAX);
629 setTargetDAGCombine(ISD::UMIN);
630 setTargetDAGCombine(ISD::UMAX);
631 setTargetDAGCombine(ISD::SETCC);
632 setTargetDAGCombine(ISD::AND);
633 setTargetDAGCombine(ISD::OR);
634 setTargetDAGCombine(ISD::XOR);
635 setTargetDAGCombine(ISD::SINT_TO_FP);
636 setTargetDAGCombine(ISD::UINT_TO_FP);
637 setTargetDAGCombine(ISD::FCANONICALIZE);
638 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
639 setTargetDAGCombine(ISD::ZERO_EXTEND);
640 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
641 setTargetDAGCombine(ISD::BUILD_VECTOR);
643 // All memory operations. Some folding on the pointer operand is done to help
644 // matching the constant offsets in the addressing modes.
645 setTargetDAGCombine(ISD::LOAD);
646 setTargetDAGCombine(ISD::STORE);
647 setTargetDAGCombine(ISD::ATOMIC_LOAD);
648 setTargetDAGCombine(ISD::ATOMIC_STORE);
649 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
650 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
651 setTargetDAGCombine(ISD::ATOMIC_SWAP);
652 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
653 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
654 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
655 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
656 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
657 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
658 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
659 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
660 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
661 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
663 setSchedulingPreference(Sched::RegPressure);
665 // SI at least has hardware support for floating point exceptions, but no way
666 // of using or handling them is implemented. They are also optional in OpenCL
668 setHasFloatingPointExceptions(Subtarget->hasFPExceptions());
671 const GCNSubtarget *SITargetLowering::getSubtarget() const {
675 //===----------------------------------------------------------------------===//
676 // TargetLowering queries
677 //===----------------------------------------------------------------------===//
679 // v_mad_mix* support a conversion from f16 to f32.
681 // There is only one special case when denormals are enabled we don't currently,
682 // where this is OK to use.
683 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
684 EVT DestVT, EVT SrcVT) const {
685 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
686 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
687 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
688 SrcVT.getScalarType() == MVT::f16;
691 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
692 // SI has some legal vector types, but no legal vector operations. Say no
693 // shuffles are legal in order to prefer scalarizing some vector operations.
697 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
700 // TODO: Consider splitting all arguments into 32-bit pieces.
701 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
702 EVT ScalarVT = VT.getScalarType();
703 unsigned Size = ScalarVT.getSizeInBits();
705 return ScalarVT.getSimpleVT();
711 Subtarget->has16BitInsts() &&
712 isPowerOf2_32(VT.getVectorNumElements()))
713 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
716 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
719 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
722 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
723 unsigned NumElts = VT.getVectorNumElements();
724 EVT ScalarVT = VT.getScalarType();
725 unsigned Size = ScalarVT.getSizeInBits();
733 // FIXME: Fails to break down as we want with v3.
734 if (Size == 16 && Subtarget->has16BitInsts() && isPowerOf2_32(NumElts))
735 return VT.getVectorNumElements() / 2;
738 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
741 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
742 LLVMContext &Context, CallingConv::ID CC,
743 EVT VT, EVT &IntermediateVT,
744 unsigned &NumIntermediates, MVT &RegisterVT) const {
745 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
746 unsigned NumElts = VT.getVectorNumElements();
747 EVT ScalarVT = VT.getScalarType();
748 unsigned Size = ScalarVT.getSizeInBits();
750 RegisterVT = ScalarVT.getSimpleVT();
751 IntermediateVT = RegisterVT;
752 NumIntermediates = NumElts;
753 return NumIntermediates;
757 RegisterVT = MVT::i32;
758 IntermediateVT = RegisterVT;
759 NumIntermediates = 2 * NumElts;
760 return NumIntermediates;
763 // FIXME: We should fix the ABI to be the same on targets without 16-bit
764 // support, but unless we can properly handle 3-vectors, it will be still be
766 if (Size == 16 && Subtarget->has16BitInsts() && isPowerOf2_32(NumElts)) {
767 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
768 IntermediateVT = RegisterVT;
769 NumIntermediates = NumElts / 2;
770 return NumIntermediates;
774 return TargetLowering::getVectorTypeBreakdownForCallingConv(
775 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
778 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
781 unsigned IntrID) const {
782 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
783 AMDGPU::lookupRsrcIntrinsic(IntrID)) {
784 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
785 (Intrinsic::ID)IntrID);
786 if (Attr.hasFnAttribute(Attribute::ReadNone))
789 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
791 if (RsrcIntr->IsImage) {
792 Info.ptrVal = MFI->getImagePSV(
793 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
794 CI.getArgOperand(RsrcIntr->RsrcArg));
797 Info.ptrVal = MFI->getBufferPSV(
798 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
799 CI.getArgOperand(RsrcIntr->RsrcArg));
802 Info.flags = MachineMemOperand::MODereferenceable;
803 if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
804 Info.opc = ISD::INTRINSIC_W_CHAIN;
805 Info.memVT = MVT::getVT(CI.getType());
806 Info.flags |= MachineMemOperand::MOLoad;
807 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
808 Info.opc = ISD::INTRINSIC_VOID;
809 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
810 Info.flags |= MachineMemOperand::MOStore;
813 Info.opc = ISD::INTRINSIC_W_CHAIN;
814 Info.memVT = MVT::getVT(CI.getType());
815 Info.flags = MachineMemOperand::MOLoad |
816 MachineMemOperand::MOStore |
817 MachineMemOperand::MODereferenceable;
819 // XXX - Should this be volatile without known ordering?
820 Info.flags |= MachineMemOperand::MOVolatile;
826 case Intrinsic::amdgcn_atomic_inc:
827 case Intrinsic::amdgcn_atomic_dec:
828 case Intrinsic::amdgcn_ds_fadd:
829 case Intrinsic::amdgcn_ds_fmin:
830 case Intrinsic::amdgcn_ds_fmax: {
831 Info.opc = ISD::INTRINSIC_W_CHAIN;
832 Info.memVT = MVT::getVT(CI.getType());
833 Info.ptrVal = CI.getOperand(0);
835 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
837 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
838 if (!Vol || !Vol->isZero())
839 Info.flags |= MachineMemOperand::MOVolatile;
849 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
850 SmallVectorImpl<Value*> &Ops,
851 Type *&AccessTy) const {
852 switch (II->getIntrinsicID()) {
853 case Intrinsic::amdgcn_atomic_inc:
854 case Intrinsic::amdgcn_atomic_dec:
855 case Intrinsic::amdgcn_ds_fadd:
856 case Intrinsic::amdgcn_ds_fmin:
857 case Intrinsic::amdgcn_ds_fmax: {
858 Value *Ptr = II->getArgOperand(0);
859 AccessTy = II->getType();
868 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
869 if (!Subtarget->hasFlatInstOffsets()) {
870 // Flat instructions do not have offsets, and only have the register
872 return AM.BaseOffs == 0 && AM.Scale == 0;
875 // GFX9 added a 13-bit signed offset. When using regular flat instructions,
876 // the sign bit is ignored and is treated as a 12-bit unsigned offset.
879 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
882 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
883 if (Subtarget->hasFlatGlobalInsts())
884 return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
886 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
887 // Assume the we will use FLAT for all global memory accesses
889 // FIXME: This assumption is currently wrong. On VI we still use
890 // MUBUF instructions for the r + i addressing mode. As currently
891 // implemented, the MUBUF instructions only work on buffer < 4GB.
892 // It may be possible to support > 4GB buffers with MUBUF instructions,
893 // by setting the stride value in the resource descriptor which would
894 // increase the size limit to (stride * 4GB). However, this is risky,
895 // because it has never been validated.
896 return isLegalFlatAddressingMode(AM);
899 return isLegalMUBUFAddressingMode(AM);
902 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
903 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
904 // additionally can do r + r + i with addr64. 32-bit has more addressing
905 // mode options. Depending on the resource constant, it can also do
906 // (i64 r0) + (i32 r1) * (i14 i).
908 // Private arrays end up using a scratch buffer most of the time, so also
909 // assume those use MUBUF instructions. Scratch loads / stores are currently
910 // implemented as mubuf instructions with offen bit set, so slightly
911 // different than the normal addr64.
912 if (!isUInt<12>(AM.BaseOffs))
915 // FIXME: Since we can split immediate into soffset and immediate offset,
916 // would it make sense to allow any immediate?
919 case 0: // r + i or just i, depending on HasBaseReg.
922 return true; // We have r + r or r + i.
929 // Allow 2 * r as r + r
930 // Or 2 * r + i is allowed as r + r + i.
932 default: // Don't allow n * r
937 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
938 const AddrMode &AM, Type *Ty,
939 unsigned AS, Instruction *I) const {
940 // No global is ever allowed as a base.
944 if (AS == AMDGPUASI.GLOBAL_ADDRESS)
945 return isLegalGlobalAddressingMode(AM);
947 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
948 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
949 // If the offset isn't a multiple of 4, it probably isn't going to be
950 // correctly aligned.
951 // FIXME: Can we get the real alignment here?
952 if (AM.BaseOffs % 4 != 0)
953 return isLegalMUBUFAddressingMode(AM);
955 // There are no SMRD extloads, so if we have to do a small type access we
956 // will use a MUBUF load.
957 // FIXME?: We also need to do this if unaligned, but we don't know the
959 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
960 return isLegalGlobalAddressingMode(AM);
962 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
963 // SMRD instructions have an 8-bit, dword offset on SI.
964 if (!isUInt<8>(AM.BaseOffs / 4))
966 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
967 // On CI+, this can also be a 32-bit literal constant offset. If it fits
968 // in 8-bits, it can use a smaller encoding.
969 if (!isUInt<32>(AM.BaseOffs / 4))
971 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
972 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
973 if (!isUInt<20>(AM.BaseOffs))
976 llvm_unreachable("unhandled generation");
978 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
981 if (AM.Scale == 1 && AM.HasBaseReg)
986 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
987 return isLegalMUBUFAddressingMode(AM);
988 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
989 AS == AMDGPUASI.REGION_ADDRESS) {
990 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
992 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
993 // an 8-bit dword offset but we don't know the alignment here.
994 if (!isUInt<16>(AM.BaseOffs))
997 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1000 if (AM.Scale == 1 && AM.HasBaseReg)
1004 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
1005 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
1006 // For an unknown address space, this usually means that this is for some
1007 // reason being used for pure arithmetic, and not based on some addressing
1008 // computation. We don't have instructions that compute pointers with any
1009 // addressing modes, so treat them as having no offset like flat
1011 return isLegalFlatAddressingMode(AM);
1013 llvm_unreachable("unhandled address space");
1017 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1018 const SelectionDAG &DAG) const {
1019 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
1020 return (MemVT.getSizeInBits() <= 4 * 32);
1021 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
1022 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1023 return (MemVT.getSizeInBits() <= MaxPrivateBits);
1024 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
1025 return (MemVT.getSizeInBits() <= 2 * 32);
1030 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1033 bool *IsFast) const {
1037 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1038 // which isn't a simple VT.
1039 // Until MVT is extended to handle this, simply check for the size and
1040 // rely on the condition below: allow accesses if the size is a multiple of 4.
1041 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1042 VT.getStoreSize() > 16)) {
1046 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
1047 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
1048 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1049 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1050 // with adjacent offsets.
1051 bool AlignedBy4 = (Align % 4 == 0);
1053 *IsFast = AlignedBy4;
1058 // FIXME: We have to be conservative here and assume that flat operations
1059 // will access scratch. If we had access to the IR function, then we
1060 // could determine if any private memory was used in the function.
1061 if (!Subtarget->hasUnalignedScratchAccess() &&
1062 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
1063 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
1067 if (Subtarget->hasUnalignedBufferAccess()) {
1068 // If we have an uniform constant load, it still requires using a slow
1069 // buffer instruction if unaligned.
1071 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS ||
1072 AddrSpace == AMDGPUASI.CONSTANT_ADDRESS_32BIT) ?
1073 (Align % 4 == 0) : true;
1079 // Smaller than dword value must be aligned.
1080 if (VT.bitsLT(MVT::i32))
1083 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1084 // byte-address are ignored, thus forcing Dword alignment.
1085 // This applies to private, global, and constant memory.
1089 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1092 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
1093 unsigned SrcAlign, bool IsMemset,
1096 MachineFunction &MF) const {
1097 // FIXME: Should account for address space here.
1099 // The default fallback uses the private pointer size as a guess for a type to
1100 // use. Make sure we switch these to 64-bit accesses.
1102 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1105 if (Size >= 8 && DstAlign >= 4)
1112 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
1113 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
1114 AS == AMDGPUASI.FLAT_ADDRESS ||
1115 AS == AMDGPUASI.CONSTANT_ADDRESS ||
1116 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT;
1119 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1120 unsigned DestAS) const {
1121 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
1122 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
1125 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1126 const MemSDNode *MemNode = cast<MemSDNode>(N);
1127 const Value *Ptr = MemNode->getMemOperand()->getValue();
1128 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1129 return I && I->getMetadata("amdgpu.noclobber");
1132 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
1133 unsigned DestAS) const {
1134 // Flat -> private/local is a simple truncate.
1135 // Flat -> global is no-op
1136 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
1139 return isNoopAddrSpaceCast(SrcAS, DestAS);
1142 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1143 const MemSDNode *MemNode = cast<MemSDNode>(N);
1145 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1148 TargetLoweringBase::LegalizeTypeAction
1149 SITargetLowering::getPreferredVectorAction(EVT VT) const {
1150 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1151 return TypeSplitVector;
1153 return TargetLoweringBase::getPreferredVectorAction(VT);
1156 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1158 // FIXME: Could be smarter if called for vector constants.
1162 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1163 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1168 // These operations are done with 32-bit instructions anyway.
1173 // TODO: Extensions?
1180 // SimplifySetCC uses this function to determine whether or not it should
1181 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1182 if (VT == MVT::i1 && Op == ISD::SETCC)
1185 return TargetLowering::isTypeDesirableForOp(Op, VT);
1188 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1191 uint64_t Offset) const {
1192 const DataLayout &DL = DAG.getDataLayout();
1193 MachineFunction &MF = DAG.getMachineFunction();
1194 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1196 const ArgDescriptor *InputPtrReg;
1197 const TargetRegisterClass *RC;
1199 std::tie(InputPtrReg, RC)
1200 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1202 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1203 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
1204 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1205 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1207 return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1210 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1211 const SDLoc &SL) const {
1212 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1214 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1217 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1218 const SDLoc &SL, SDValue Val,
1220 const ISD::InputArg *Arg) const {
1221 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1223 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1224 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1227 if (MemVT.isFloatingPoint())
1228 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1230 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1232 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1237 SDValue SITargetLowering::lowerKernargMemParameter(
1238 SelectionDAG &DAG, EVT VT, EVT MemVT,
1239 const SDLoc &SL, SDValue Chain,
1240 uint64_t Offset, unsigned Align, bool Signed,
1241 const ISD::InputArg *Arg) const {
1242 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1243 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
1244 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1246 // Try to avoid using an extload by loading earlier than the argument address,
1247 // and extracting the relevant bits. The load should hopefully be merged with
1248 // the previous argument.
1249 if (MemVT.getStoreSize() < 4 && Align < 4) {
1250 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1251 int64_t AlignDownOffset = alignDown(Offset, 4);
1252 int64_t OffsetDiff = Offset - AlignDownOffset;
1254 EVT IntVT = MemVT.changeTypeToInteger();
1256 // TODO: If we passed in the base kernel offset we could have a better
1257 // alignment than 4, but we don't really need it.
1258 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1259 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1260 MachineMemOperand::MODereferenceable |
1261 MachineMemOperand::MOInvariant);
1263 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1264 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1266 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1267 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1268 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1271 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1274 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1275 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1276 MachineMemOperand::MODereferenceable |
1277 MachineMemOperand::MOInvariant);
1279 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1280 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1283 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1284 const SDLoc &SL, SDValue Chain,
1285 const ISD::InputArg &Arg) const {
1286 MachineFunction &MF = DAG.getMachineFunction();
1287 MachineFrameInfo &MFI = MF.getFrameInfo();
1289 if (Arg.Flags.isByVal()) {
1290 unsigned Size = Arg.Flags.getByValSize();
1291 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1292 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1295 unsigned ArgOffset = VA.getLocMemOffset();
1296 unsigned ArgSize = VA.getValVT().getStoreSize();
1298 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1300 // Create load nodes to retrieve arguments from the stack.
1301 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1304 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1305 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1306 MVT MemVT = VA.getValVT();
1308 switch (VA.getLocInfo()) {
1311 case CCValAssign::BCvt:
1312 MemVT = VA.getLocVT();
1314 case CCValAssign::SExt:
1315 ExtType = ISD::SEXTLOAD;
1317 case CCValAssign::ZExt:
1318 ExtType = ISD::ZEXTLOAD;
1320 case CCValAssign::AExt:
1321 ExtType = ISD::EXTLOAD;
1325 ArgValue = DAG.getExtLoad(
1326 ExtType, SL, VA.getLocVT(), Chain, FIN,
1327 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1332 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1333 const SIMachineFunctionInfo &MFI,
1335 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1336 const ArgDescriptor *Reg;
1337 const TargetRegisterClass *RC;
1339 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1340 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1343 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1344 CallingConv::ID CallConv,
1345 ArrayRef<ISD::InputArg> Ins,
1347 FunctionType *FType,
1348 SIMachineFunctionInfo *Info) {
1349 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1350 const ISD::InputArg *Arg = &Ins[I];
1352 assert(!Arg->VT.isVector() && "vector type argument should have been split");
1354 // First check if it's a PS input addr.
1355 if (CallConv == CallingConv::AMDGPU_PS &&
1356 !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) {
1358 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1360 // Inconveniently only the first part of the split is marked as isSplit,
1361 // so skip to the end. We only want to increment PSInputNum once for the
1362 // entire split argument.
1363 if (Arg->Flags.isSplit()) {
1364 while (!Arg->Flags.isSplitEnd()) {
1365 assert(!Arg->VT.isVector() &&
1366 "unexpected vector split in ps argument type");
1368 Splits.push_back(*Arg);
1374 // We can safely skip PS inputs.
1375 Skipped.set(Arg->getOrigArgIndex());
1380 Info->markPSInputAllocated(PSInputNum);
1382 Info->markPSInputEnabled(PSInputNum);
1387 Splits.push_back(*Arg);
1391 // Allocate special inputs passed in VGPRs.
1392 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1393 MachineFunction &MF,
1394 const SIRegisterInfo &TRI,
1395 SIMachineFunctionInfo &Info) {
1396 if (Info.hasWorkItemIDX()) {
1397 unsigned Reg = AMDGPU::VGPR0;
1398 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1400 CCInfo.AllocateReg(Reg);
1401 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1404 if (Info.hasWorkItemIDY()) {
1405 unsigned Reg = AMDGPU::VGPR1;
1406 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1408 CCInfo.AllocateReg(Reg);
1409 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1412 if (Info.hasWorkItemIDZ()) {
1413 unsigned Reg = AMDGPU::VGPR2;
1414 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1416 CCInfo.AllocateReg(Reg);
1417 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1421 // Try to allocate a VGPR at the end of the argument list, or if no argument
1422 // VGPRs are left allocating a stack slot.
1423 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1424 ArrayRef<MCPhysReg> ArgVGPRs
1425 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1426 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1427 if (RegIdx == ArgVGPRs.size()) {
1428 // Spill to stack required.
1429 int64_t Offset = CCInfo.AllocateStack(4, 4);
1431 return ArgDescriptor::createStack(Offset);
1434 unsigned Reg = ArgVGPRs[RegIdx];
1435 Reg = CCInfo.AllocateReg(Reg);
1436 assert(Reg != AMDGPU::NoRegister);
1438 MachineFunction &MF = CCInfo.getMachineFunction();
1439 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1440 return ArgDescriptor::createRegister(Reg);
1443 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1444 const TargetRegisterClass *RC,
1445 unsigned NumArgRegs) {
1446 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1447 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1448 if (RegIdx == ArgSGPRs.size())
1449 report_fatal_error("ran out of SGPRs for arguments");
1451 unsigned Reg = ArgSGPRs[RegIdx];
1452 Reg = CCInfo.AllocateReg(Reg);
1453 assert(Reg != AMDGPU::NoRegister);
1455 MachineFunction &MF = CCInfo.getMachineFunction();
1456 MF.addLiveIn(Reg, RC);
1457 return ArgDescriptor::createRegister(Reg);
1460 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1461 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1464 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1465 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1468 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1469 MachineFunction &MF,
1470 const SIRegisterInfo &TRI,
1471 SIMachineFunctionInfo &Info) {
1472 if (Info.hasWorkItemIDX())
1473 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1475 if (Info.hasWorkItemIDY())
1476 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1478 if (Info.hasWorkItemIDZ())
1479 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1482 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1483 MachineFunction &MF,
1484 const SIRegisterInfo &TRI,
1485 SIMachineFunctionInfo &Info) {
1486 auto &ArgInfo = Info.getArgInfo();
1488 // TODO: Unify handling with private memory pointers.
1490 if (Info.hasDispatchPtr())
1491 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1493 if (Info.hasQueuePtr())
1494 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1496 if (Info.hasKernargSegmentPtr())
1497 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1499 if (Info.hasDispatchID())
1500 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1502 // flat_scratch_init is not applicable for non-kernel functions.
1504 if (Info.hasWorkGroupIDX())
1505 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1507 if (Info.hasWorkGroupIDY())
1508 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1510 if (Info.hasWorkGroupIDZ())
1511 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1513 if (Info.hasImplicitArgPtr())
1514 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1517 // Allocate special inputs passed in user SGPRs.
1518 static void allocateHSAUserSGPRs(CCState &CCInfo,
1519 MachineFunction &MF,
1520 const SIRegisterInfo &TRI,
1521 SIMachineFunctionInfo &Info) {
1522 if (Info.hasImplicitBufferPtr()) {
1523 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1524 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1525 CCInfo.AllocateReg(ImplicitBufferPtrReg);
1528 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1529 if (Info.hasPrivateSegmentBuffer()) {
1530 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1531 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1532 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1535 if (Info.hasDispatchPtr()) {
1536 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1537 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1538 CCInfo.AllocateReg(DispatchPtrReg);
1541 if (Info.hasQueuePtr()) {
1542 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1543 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1544 CCInfo.AllocateReg(QueuePtrReg);
1547 if (Info.hasKernargSegmentPtr()) {
1548 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1549 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1550 CCInfo.AllocateReg(InputPtrReg);
1553 if (Info.hasDispatchID()) {
1554 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1555 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1556 CCInfo.AllocateReg(DispatchIDReg);
1559 if (Info.hasFlatScratchInit()) {
1560 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1561 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1562 CCInfo.AllocateReg(FlatScratchInitReg);
1565 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1566 // these from the dispatch pointer.
1569 // Allocate special input registers that are initialized per-wave.
1570 static void allocateSystemSGPRs(CCState &CCInfo,
1571 MachineFunction &MF,
1572 SIMachineFunctionInfo &Info,
1573 CallingConv::ID CallConv,
1575 if (Info.hasWorkGroupIDX()) {
1576 unsigned Reg = Info.addWorkGroupIDX();
1577 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1578 CCInfo.AllocateReg(Reg);
1581 if (Info.hasWorkGroupIDY()) {
1582 unsigned Reg = Info.addWorkGroupIDY();
1583 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1584 CCInfo.AllocateReg(Reg);
1587 if (Info.hasWorkGroupIDZ()) {
1588 unsigned Reg = Info.addWorkGroupIDZ();
1589 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1590 CCInfo.AllocateReg(Reg);
1593 if (Info.hasWorkGroupInfo()) {
1594 unsigned Reg = Info.addWorkGroupInfo();
1595 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1596 CCInfo.AllocateReg(Reg);
1599 if (Info.hasPrivateSegmentWaveByteOffset()) {
1600 // Scratch wave offset passed in system SGPR.
1601 unsigned PrivateSegmentWaveByteOffsetReg;
1604 PrivateSegmentWaveByteOffsetReg =
1605 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1607 // This is true if the scratch wave byte offset doesn't have a fixed
1609 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1610 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1611 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1614 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1616 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1617 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1621 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1622 MachineFunction &MF,
1623 const SIRegisterInfo &TRI,
1624 SIMachineFunctionInfo &Info) {
1625 // Now that we've figured out where the scratch register inputs are, see if
1626 // should reserve the arguments and use them directly.
1627 MachineFrameInfo &MFI = MF.getFrameInfo();
1628 bool HasStackObjects = MFI.hasStackObjects();
1630 // Record that we know we have non-spill stack objects so we don't need to
1631 // check all stack objects later.
1632 if (HasStackObjects)
1633 Info.setHasNonSpillStackObjects(true);
1635 // Everything live out of a block is spilled with fast regalloc, so it's
1636 // almost certain that spilling will be required.
1637 if (TM.getOptLevel() == CodeGenOpt::None)
1638 HasStackObjects = true;
1640 // For now assume stack access is needed in any callee functions, so we need
1641 // the scratch registers to pass in.
1642 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1644 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1645 if (ST.isAmdCodeObjectV2(MF.getFunction())) {
1646 if (RequiresStackAccess) {
1647 // If we have stack objects, we unquestionably need the private buffer
1648 // resource. For the Code Object V2 ABI, this will be the first 4 user
1649 // SGPR inputs. We can reserve those and use them directly.
1651 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1652 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1653 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1655 if (MFI.hasCalls()) {
1656 // If we have calls, we need to keep the frame register in a register
1657 // that won't be clobbered by a call, so ensure it is copied somewhere.
1659 // This is not a problem for the scratch wave offset, because the same
1660 // registers are reserved in all functions.
1662 // FIXME: Nothing is really ensuring this is a call preserved register,
1663 // it's just selected from the end so it happens to be.
1664 unsigned ReservedOffsetReg
1665 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1666 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1668 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1669 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1670 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1673 unsigned ReservedBufferReg
1674 = TRI.reservedPrivateSegmentBufferReg(MF);
1675 unsigned ReservedOffsetReg
1676 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1678 // We tentatively reserve the last registers (skipping the last two
1679 // which may contain VCC). After register allocation, we'll replace
1680 // these with the ones immediately after those which were really
1681 // allocated. In the prologue copies will be inserted from the argument
1682 // to these reserved registers.
1683 Info.setScratchRSrcReg(ReservedBufferReg);
1684 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1687 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1689 // Without HSA, relocations are used for the scratch pointer and the
1690 // buffer resource setup is always inserted in the prologue. Scratch wave
1691 // offset is still in an input SGPR.
1692 Info.setScratchRSrcReg(ReservedBufferReg);
1694 if (HasStackObjects && !MFI.hasCalls()) {
1695 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1696 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1697 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1699 unsigned ReservedOffsetReg
1700 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1701 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1706 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1707 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1708 return !Info->isEntryFunction();
1711 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1715 void SITargetLowering::insertCopiesSplitCSR(
1716 MachineBasicBlock *Entry,
1717 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1718 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1720 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1724 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1725 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1726 MachineBasicBlock::iterator MBBI = Entry->begin();
1727 for (const MCPhysReg *I = IStart; *I; ++I) {
1728 const TargetRegisterClass *RC = nullptr;
1729 if (AMDGPU::SReg_64RegClass.contains(*I))
1730 RC = &AMDGPU::SGPR_64RegClass;
1731 else if (AMDGPU::SReg_32RegClass.contains(*I))
1732 RC = &AMDGPU::SGPR_32RegClass;
1734 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1736 unsigned NewVR = MRI->createVirtualRegister(RC);
1737 // Create copy from CSR to a virtual register.
1738 Entry->addLiveIn(*I);
1739 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1742 // Insert the copy-back instructions right before the terminator.
1743 for (auto *Exit : Exits)
1744 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1745 TII->get(TargetOpcode::COPY), *I)
1750 SDValue SITargetLowering::LowerFormalArguments(
1751 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1752 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1753 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1754 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1756 MachineFunction &MF = DAG.getMachineFunction();
1757 const Function &Fn = MF.getFunction();
1758 FunctionType *FType = MF.getFunction().getFunctionType();
1759 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1760 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1762 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1763 DiagnosticInfoUnsupported NoGraphicsHSA(
1764 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1765 DAG.getContext()->diagnose(NoGraphicsHSA);
1766 return DAG.getEntryNode();
1769 // Create stack objects that are used for emitting debugger prologue if
1770 // "amdgpu-debugger-emit-prologue" attribute was specified.
1771 if (ST.debuggerEmitPrologue())
1772 createDebuggerPrologueStackObjects(MF);
1774 SmallVector<ISD::InputArg, 16> Splits;
1775 SmallVector<CCValAssign, 16> ArgLocs;
1776 BitVector Skipped(Ins.size());
1777 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1780 bool IsShader = AMDGPU::isShader(CallConv);
1781 bool IsKernel = AMDGPU::isKernel(CallConv);
1782 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1785 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1786 // this when allocating argument fixed offsets.
1787 CCInfo.AllocateStack(4, 4);
1791 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1793 // At least one interpolation mode must be enabled or else the GPU will
1796 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1797 // set PSInputAddr, the user wants to enable some bits after the compilation
1798 // based on run-time states. Since we can't know what the final PSInputEna
1799 // will look like, so we shouldn't do anything here and the user should take
1800 // responsibility for the correct programming.
1802 // Otherwise, the following restrictions apply:
1803 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1804 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1806 if (CallConv == CallingConv::AMDGPU_PS) {
1807 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1808 ((Info->getPSInputAddr() & 0xF) == 0 &&
1809 Info->isPSInputAllocated(11))) {
1810 CCInfo.AllocateReg(AMDGPU::VGPR0);
1811 CCInfo.AllocateReg(AMDGPU::VGPR1);
1812 Info->markPSInputAllocated(0);
1813 Info->markPSInputEnabled(0);
1815 if (Subtarget->isAmdPalOS()) {
1816 // For isAmdPalOS, the user does not enable some bits after compilation
1817 // based on run-time states; the register values being generated here are
1818 // the final ones set in hardware. Therefore we need to apply the
1819 // workaround to PSInputAddr and PSInputEnable together. (The case where
1820 // a bit is set in PSInputAddr but not PSInputEnable is where the
1821 // frontend set up an input arg for a particular interpolation mode, but
1822 // nothing uses that input arg. Really we should have an earlier pass
1823 // that removes such an arg.)
1824 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1825 if ((PsInputBits & 0x7F) == 0 ||
1826 ((PsInputBits & 0xF) == 0 &&
1827 (PsInputBits >> 11 & 1)))
1828 Info->markPSInputEnabled(
1829 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1833 assert(!Info->hasDispatchPtr() &&
1834 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1835 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1836 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1837 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1838 !Info->hasWorkItemIDZ());
1839 } else if (IsKernel) {
1840 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1842 Splits.append(Ins.begin(), Ins.end());
1846 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1847 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1851 analyzeFormalArgumentsCompute(CCInfo, Ins);
1853 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1854 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1857 SmallVector<SDValue, 16> Chains;
1859 // FIXME: This is the minimum kernel argument alignment. We should improve
1860 // this to the maximum alignment of the arguments.
1862 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
1864 const unsigned KernelArgBaseAlign = 16;
1866 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1867 const ISD::InputArg &Arg = Ins[i];
1868 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
1869 InVals.push_back(DAG.getUNDEF(Arg.VT));
1873 CCValAssign &VA = ArgLocs[ArgIdx++];
1874 MVT VT = VA.getLocVT();
1876 if (IsEntryFunc && VA.isMemLoc()) {
1878 EVT MemVT = VA.getLocVT();
1880 const uint64_t Offset = VA.getLocMemOffset();
1881 unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
1883 SDValue Arg = lowerKernargMemParameter(
1884 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
1885 Chains.push_back(Arg.getValue(1));
1888 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1889 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
1890 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1891 // On SI local pointers are just offsets into LDS, so they are always
1892 // less than 16-bits. On CI and newer they could potentially be
1893 // real pointers, so we can't guarantee their size.
1894 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1895 DAG.getValueType(MVT::i16));
1898 InVals.push_back(Arg);
1900 } else if (!IsEntryFunc && VA.isMemLoc()) {
1901 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1902 InVals.push_back(Val);
1903 if (!Arg.Flags.isByVal())
1904 Chains.push_back(Val.getValue(1));
1908 assert(VA.isRegLoc() && "Parameter must be in a register!");
1910 unsigned Reg = VA.getLocReg();
1911 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1912 EVT ValVT = VA.getValVT();
1914 Reg = MF.addLiveIn(Reg, RC);
1915 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1917 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1918 // The return object should be reasonably addressable.
1920 // FIXME: This helps when the return is a real sret. If it is a
1921 // automatically inserted sret (i.e. CanLowerReturn returns false), an
1922 // extra copy is inserted in SelectionDAGBuilder which obscures this.
1923 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1924 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1925 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1928 // If this is an 8 or 16-bit value, it is really passed promoted
1929 // to 32 bits. Insert an assert[sz]ext to capture this, then
1930 // truncate to the right size.
1931 switch (VA.getLocInfo()) {
1932 case CCValAssign::Full:
1934 case CCValAssign::BCvt:
1935 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1937 case CCValAssign::SExt:
1938 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1939 DAG.getValueType(ValVT));
1940 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1942 case CCValAssign::ZExt:
1943 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1944 DAG.getValueType(ValVT));
1945 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1947 case CCValAssign::AExt:
1948 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1951 llvm_unreachable("Unknown loc info!");
1954 if (IsShader && Arg.VT.isVector()) {
1955 // Build a vector from the registers
1956 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1957 unsigned NumElements = ParamType->getVectorNumElements();
1959 SmallVector<SDValue, 4> Regs;
1960 Regs.push_back(Val);
1961 for (unsigned j = 1; j != NumElements; ++j) {
1962 Reg = ArgLocs[ArgIdx++].getLocReg();
1963 Reg = MF.addLiveIn(Reg, RC);
1965 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1966 Regs.push_back(Copy);
1969 // Fill up the missing vector elements
1970 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1971 Regs.append(NumElements, DAG.getUNDEF(VT));
1973 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1977 InVals.push_back(Val);
1981 // Special inputs come after user arguments.
1982 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1985 // Start adding system SGPRs.
1987 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1989 CCInfo.AllocateReg(Info->getScratchRSrcReg());
1990 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1991 CCInfo.AllocateReg(Info->getFrameOffsetReg());
1992 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
1995 auto &ArgUsageInfo =
1996 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1997 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
1999 unsigned StackArgSize = CCInfo.getNextStackOffset();
2000 Info->setBytesInStackArgArea(StackArgSize);
2002 return Chains.empty() ? Chain :
2003 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2006 // TODO: If return values can't fit in registers, we should return as many as
2007 // possible in registers before passing on stack.
2008 bool SITargetLowering::CanLowerReturn(
2009 CallingConv::ID CallConv,
2010 MachineFunction &MF, bool IsVarArg,
2011 const SmallVectorImpl<ISD::OutputArg> &Outs,
2012 LLVMContext &Context) const {
2013 // Replacing returns with sret/stack usage doesn't make sense for shaders.
2014 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2015 // for shaders. Vector types should be explicitly handled by CC.
2016 if (AMDGPU::isEntryFunctionCC(CallConv))
2019 SmallVector<CCValAssign, 16> RVLocs;
2020 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2021 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2025 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2027 const SmallVectorImpl<ISD::OutputArg> &Outs,
2028 const SmallVectorImpl<SDValue> &OutVals,
2029 const SDLoc &DL, SelectionDAG &DAG) const {
2030 MachineFunction &MF = DAG.getMachineFunction();
2031 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2033 if (AMDGPU::isKernel(CallConv)) {
2034 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2038 bool IsShader = AMDGPU::isShader(CallConv);
2040 Info->setIfReturnsVoid(Outs.size() == 0);
2041 bool IsWaveEnd = Info->returnsVoid() && IsShader;
2043 SmallVector<ISD::OutputArg, 48> Splits;
2044 SmallVector<SDValue, 48> SplitVals;
2046 // Split vectors into their elements.
2047 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
2048 const ISD::OutputArg &Out = Outs[i];
2050 if (IsShader && Out.VT.isVector()) {
2051 MVT VT = Out.VT.getVectorElementType();
2052 ISD::OutputArg NewOut = Out;
2053 NewOut.Flags.setSplit();
2056 // We want the original number of vector elements here, e.g.
2057 // three or five, not four or eight.
2058 unsigned NumElements = Out.ArgVT.getVectorNumElements();
2060 for (unsigned j = 0; j != NumElements; ++j) {
2061 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
2062 DAG.getConstant(j, DL, MVT::i32));
2063 SplitVals.push_back(Elem);
2064 Splits.push_back(NewOut);
2065 NewOut.PartOffset += NewOut.VT.getStoreSize();
2068 SplitVals.push_back(OutVals[i]);
2069 Splits.push_back(Out);
2073 // CCValAssign - represent the assignment of the return value to a location.
2074 SmallVector<CCValAssign, 48> RVLocs;
2076 // CCState - Info about the registers and stack slots.
2077 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2080 // Analyze outgoing return values.
2081 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
2084 SmallVector<SDValue, 48> RetOps;
2085 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2087 // Add return address for callable functions.
2088 if (!Info->isEntryFunction()) {
2089 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2090 SDValue ReturnAddrReg = CreateLiveInRegister(
2091 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2093 // FIXME: Should be able to use a vreg here, but need a way to prevent it
2094 // from being allcoated to a CSR.
2096 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2099 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2100 Flag = Chain.getValue(1);
2102 RetOps.push_back(PhysReturnAddrReg);
2105 // Copy the result values into the output registers.
2106 for (unsigned i = 0, realRVLocIdx = 0;
2108 ++i, ++realRVLocIdx) {
2109 CCValAssign &VA = RVLocs[i];
2110 assert(VA.isRegLoc() && "Can only return in registers!");
2111 // TODO: Partially return in registers if return values don't fit.
2113 SDValue Arg = SplitVals[realRVLocIdx];
2115 // Copied from other backends.
2116 switch (VA.getLocInfo()) {
2117 case CCValAssign::Full:
2119 case CCValAssign::BCvt:
2120 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2122 case CCValAssign::SExt:
2123 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2125 case CCValAssign::ZExt:
2126 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2128 case CCValAssign::AExt:
2129 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2132 llvm_unreachable("Unknown loc info!");
2135 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2136 Flag = Chain.getValue(1);
2137 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2140 // FIXME: Does sret work properly?
2141 if (!Info->isEntryFunction()) {
2142 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2143 const MCPhysReg *I =
2144 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2147 if (AMDGPU::SReg_64RegClass.contains(*I))
2148 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2149 else if (AMDGPU::SReg_32RegClass.contains(*I))
2150 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2152 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2157 // Update chain and glue.
2160 RetOps.push_back(Flag);
2162 unsigned Opc = AMDGPUISD::ENDPGM;
2164 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2165 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2168 SDValue SITargetLowering::LowerCallResult(
2169 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2170 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2171 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2172 SDValue ThisVal) const {
2173 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2175 // Assign locations to each value returned by this call.
2176 SmallVector<CCValAssign, 16> RVLocs;
2177 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2179 CCInfo.AnalyzeCallResult(Ins, RetCC);
2181 // Copy all of the result registers out of their specified physreg.
2182 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2183 CCValAssign VA = RVLocs[i];
2186 if (VA.isRegLoc()) {
2187 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2188 Chain = Val.getValue(1);
2189 InFlag = Val.getValue(2);
2190 } else if (VA.isMemLoc()) {
2191 report_fatal_error("TODO: return values in memory");
2193 llvm_unreachable("unknown argument location type");
2195 switch (VA.getLocInfo()) {
2196 case CCValAssign::Full:
2198 case CCValAssign::BCvt:
2199 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2201 case CCValAssign::ZExt:
2202 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2203 DAG.getValueType(VA.getValVT()));
2204 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2206 case CCValAssign::SExt:
2207 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2208 DAG.getValueType(VA.getValVT()));
2209 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2211 case CCValAssign::AExt:
2212 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2215 llvm_unreachable("Unknown loc info!");
2218 InVals.push_back(Val);
2224 // Add code to pass special inputs required depending on used features separate
2225 // from the explicit user arguments present in the IR.
2226 void SITargetLowering::passSpecialInputs(
2227 CallLoweringInfo &CLI,
2228 const SIMachineFunctionInfo &Info,
2229 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2230 SmallVectorImpl<SDValue> &MemOpChains,
2232 SDValue StackPtr) const {
2233 // If we don't have a call site, this was a call inserted by
2234 // legalization. These can never use special inputs.
2238 const Function *CalleeFunc = CLI.CS.getCalledFunction();
2241 SelectionDAG &DAG = CLI.DAG;
2242 const SDLoc &DL = CLI.DL;
2244 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2246 auto &ArgUsageInfo =
2247 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2248 const AMDGPUFunctionArgInfo &CalleeArgInfo
2249 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2251 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2253 // TODO: Unify with private memory register handling. This is complicated by
2254 // the fact that at least in kernels, the input argument is not necessarily
2255 // in the same location as the input.
2256 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2257 AMDGPUFunctionArgInfo::DISPATCH_PTR,
2258 AMDGPUFunctionArgInfo::QUEUE_PTR,
2259 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2260 AMDGPUFunctionArgInfo::DISPATCH_ID,
2261 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2262 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2263 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2264 AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2265 AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2266 AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2267 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2270 for (auto InputID : InputRegs) {
2271 const ArgDescriptor *OutgoingArg;
2272 const TargetRegisterClass *ArgRC;
2274 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2278 const ArgDescriptor *IncomingArg;
2279 const TargetRegisterClass *IncomingArgRC;
2280 std::tie(IncomingArg, IncomingArgRC)
2281 = CallerArgInfo.getPreloadedValue(InputID);
2282 assert(IncomingArgRC == ArgRC);
2284 // All special arguments are ints for now.
2285 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2289 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2291 // The implicit arg ptr is special because it doesn't have a corresponding
2292 // input for kernels, and is computed from the kernarg segment pointer.
2293 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2294 InputReg = getImplicitArgPtr(DAG, DL);
2297 if (OutgoingArg->isRegister()) {
2298 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2300 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr,
2302 OutgoingArg->getStackOffset());
2303 MemOpChains.push_back(ArgStore);
2308 static bool canGuaranteeTCO(CallingConv::ID CC) {
2309 return CC == CallingConv::Fast;
2312 /// Return true if we might ever do TCO for calls with this calling convention.
2313 static bool mayTailCallThisCC(CallingConv::ID CC) {
2315 case CallingConv::C:
2318 return canGuaranteeTCO(CC);
2322 bool SITargetLowering::isEligibleForTailCallOptimization(
2323 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2324 const SmallVectorImpl<ISD::OutputArg> &Outs,
2325 const SmallVectorImpl<SDValue> &OutVals,
2326 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2327 if (!mayTailCallThisCC(CalleeCC))
2330 MachineFunction &MF = DAG.getMachineFunction();
2331 const Function &CallerF = MF.getFunction();
2332 CallingConv::ID CallerCC = CallerF.getCallingConv();
2333 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2334 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2336 // Kernels aren't callable, and don't have a live in return address so it
2337 // doesn't make sense to do a tail call with entry functions.
2338 if (!CallerPreserved)
2341 bool CCMatch = CallerCC == CalleeCC;
2343 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2344 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2349 // TODO: Can we handle var args?
2353 for (const Argument &Arg : CallerF.args()) {
2354 if (Arg.hasByValAttr())
2358 LLVMContext &Ctx = *DAG.getContext();
2360 // Check that the call results are passed in the same way.
2361 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2362 CCAssignFnForCall(CalleeCC, IsVarArg),
2363 CCAssignFnForCall(CallerCC, IsVarArg)))
2366 // The callee has to preserve all registers the caller needs to preserve.
2368 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2369 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2373 // Nothing more to check if the callee is taking no arguments.
2377 SmallVector<CCValAssign, 16> ArgLocs;
2378 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2380 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2382 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2383 // If the stack arguments for this call do not fit into our own save area then
2384 // the call cannot be made tail.
2385 // TODO: Is this really necessary?
2386 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2389 const MachineRegisterInfo &MRI = MF.getRegInfo();
2390 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2393 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2394 if (!CI->isTailCall())
2397 const Function *ParentFn = CI->getParent()->getParent();
2398 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2401 auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2402 return (Attr.getValueAsString() != "true");
2405 // The wave scratch offset register is used as the global base pointer.
2406 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2407 SmallVectorImpl<SDValue> &InVals) const {
2408 SelectionDAG &DAG = CLI.DAG;
2409 const SDLoc &DL = CLI.DL;
2410 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2411 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2412 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2413 SDValue Chain = CLI.Chain;
2414 SDValue Callee = CLI.Callee;
2415 bool &IsTailCall = CLI.IsTailCall;
2416 CallingConv::ID CallConv = CLI.CallConv;
2417 bool IsVarArg = CLI.IsVarArg;
2418 bool IsSibCall = false;
2419 bool IsThisReturn = false;
2420 MachineFunction &MF = DAG.getMachineFunction();
2423 return lowerUnhandledCall(CLI, InVals,
2424 "unsupported call to variadic function ");
2427 if (!CLI.CS.getCalledFunction()) {
2428 return lowerUnhandledCall(CLI, InVals,
2429 "unsupported indirect call to function ");
2432 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2433 return lowerUnhandledCall(CLI, InVals,
2434 "unsupported required tail call to function ");
2437 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2438 // Note the issue is with the CC of the calling function, not of the call
2440 return lowerUnhandledCall(CLI, InVals,
2441 "unsupported call from graphics shader of function ");
2444 // The first 4 bytes are reserved for the callee's emergency stack slot.
2445 const unsigned CalleeUsableStackOffset = 4;
2448 IsTailCall = isEligibleForTailCallOptimization(
2449 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2450 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2451 report_fatal_error("failed to perform tail call elimination on a call "
2452 "site marked musttail");
2455 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2457 // A sibling call is one where we're under the usual C ABI and not planning
2458 // to change that but can still do a tail call:
2459 if (!TailCallOpt && IsTailCall)
2466 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) {
2467 // FIXME: Remove this hack for function pointer types after removing
2468 // support of old address space mapping. In the new address space
2469 // mapping the pointer in default address space is 64 bit, therefore
2470 // does not need this hack.
2471 if (Callee.getValueType() == MVT::i32) {
2472 const GlobalValue *GV = GA->getGlobal();
2473 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false,
2474 GA->getTargetFlags());
2477 assert(Callee.getValueType() == MVT::i64);
2479 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2481 // Analyze operands of the call, assigning locations to each operand.
2482 SmallVector<CCValAssign, 16> ArgLocs;
2483 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2484 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2485 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2487 // Get a count of how many bytes are to be pushed on the stack.
2488 unsigned NumBytes = CCInfo.getNextStackOffset();
2491 // Since we're not changing the ABI to make this a tail call, the memory
2492 // operands are already available in the caller's incoming argument space.
2496 // FPDiff is the byte offset of the call's argument area from the callee's.
2497 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2498 // by this amount for a tail call. In a sibling call it must be 0 because the
2499 // caller will deallocate the entire stack and the callee still expects its
2500 // arguments to begin at SP+0. Completely unused for non-tail calls.
2502 MachineFrameInfo &MFI = MF.getFrameInfo();
2503 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2505 SDValue CallerSavedFP;
2507 // Adjust the stack pointer for the new arguments...
2508 // These operations are automatically eliminated by the prolog/epilog pass
2510 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2512 unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2514 // In the HSA case, this should be an identity copy.
2515 SDValue ScratchRSrcReg
2516 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2517 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2519 // TODO: Don't hardcode these registers and get from the callee function.
2520 SDValue ScratchWaveOffsetReg
2521 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2522 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2524 if (!Info->isEntryFunction()) {
2525 // Avoid clobbering this function's FP value. In the current convention
2526 // callee will overwrite this, so do save/restore around the call site.
2527 CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2528 Info->getFrameOffsetReg(), MVT::i32);
2532 // Stack pointer relative accesses are done by changing the offset SGPR. This
2533 // is just the VGPR offset component.
2534 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32);
2536 SmallVector<SDValue, 8> MemOpChains;
2537 MVT PtrVT = MVT::i32;
2539 // Walk the register/memloc assignments, inserting copies/loads.
2540 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2541 ++i, ++realArgIdx) {
2542 CCValAssign &VA = ArgLocs[i];
2543 SDValue Arg = OutVals[realArgIdx];
2545 // Promote the value if needed.
2546 switch (VA.getLocInfo()) {
2547 case CCValAssign::Full:
2549 case CCValAssign::BCvt:
2550 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2552 case CCValAssign::ZExt:
2553 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2555 case CCValAssign::SExt:
2556 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2558 case CCValAssign::AExt:
2559 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2561 case CCValAssign::FPExt:
2562 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2565 llvm_unreachable("Unknown loc info!");
2568 if (VA.isRegLoc()) {
2569 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2571 assert(VA.isMemLoc());
2574 MachinePointerInfo DstInfo;
2576 unsigned LocMemOffset = VA.getLocMemOffset();
2577 int32_t Offset = LocMemOffset;
2579 SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset);
2582 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2583 unsigned OpSize = Flags.isByVal() ?
2584 Flags.getByValSize() : VA.getValVT().getStoreSize();
2586 Offset = Offset + FPDiff;
2587 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2589 DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT),
2591 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2593 // Make sure any stack arguments overlapping with where we're storing
2594 // are loaded before this eventual operation. Otherwise they'll be
2597 // FIXME: Why is this really necessary? This seems to just result in a
2598 // lot of code to copy the stack and write them back to the same
2599 // locations, which are supposed to be immutable?
2600 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2603 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2606 if (Outs[i].Flags.isByVal()) {
2608 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2609 SDValue Cpy = DAG.getMemcpy(
2610 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2611 /*isVol = */ false, /*AlwaysInline = */ true,
2612 /*isTailCall = */ false, DstInfo,
2613 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2614 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS))));
2616 MemOpChains.push_back(Cpy);
2618 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
2619 MemOpChains.push_back(Store);
2624 // Copy special input registers after user input arguments.
2625 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr);
2627 if (!MemOpChains.empty())
2628 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2630 // Build a sequence of copy-to-reg nodes chained together with token chain
2631 // and flag operands which copy the outgoing args into the appropriate regs.
2633 for (auto &RegToPass : RegsToPass) {
2634 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2635 RegToPass.second, InFlag);
2636 InFlag = Chain.getValue(1);
2640 SDValue PhysReturnAddrReg;
2642 // Since the return is being combined with the call, we need to pass on the
2645 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2646 SDValue ReturnAddrReg = CreateLiveInRegister(
2647 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2649 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2651 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2652 InFlag = Chain.getValue(1);
2655 // We don't usually want to end the call-sequence here because we would tidy
2656 // the frame up *after* the call, however in the ABI-changing tail-call case
2657 // we've carefully laid out the parameters so that when sp is reset they'll be
2658 // in the correct location.
2659 if (IsTailCall && !IsSibCall) {
2660 Chain = DAG.getCALLSEQ_END(Chain,
2661 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2662 DAG.getTargetConstant(0, DL, MVT::i32),
2664 InFlag = Chain.getValue(1);
2667 std::vector<SDValue> Ops;
2668 Ops.push_back(Chain);
2669 Ops.push_back(Callee);
2672 // Each tail call may have to adjust the stack by a different amount, so
2673 // this information must travel along with the operation for eventual
2674 // consumption by emitEpilogue.
2675 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2677 Ops.push_back(PhysReturnAddrReg);
2680 // Add argument registers to the end of the list so that they are known live
2682 for (auto &RegToPass : RegsToPass) {
2683 Ops.push_back(DAG.getRegister(RegToPass.first,
2684 RegToPass.second.getValueType()));
2687 // Add a register mask operand representing the call-preserved registers.
2689 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2690 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2691 assert(Mask && "Missing call preserved mask for calling convention");
2692 Ops.push_back(DAG.getRegisterMask(Mask));
2694 if (InFlag.getNode())
2695 Ops.push_back(InFlag);
2697 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2699 // If we're doing a tall call, use a TC_RETURN here rather than an
2700 // actual call instruction.
2702 MFI.setHasTailCall();
2703 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2706 // Returns a chain and a flag for retval copy to use.
2707 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2708 Chain = Call.getValue(0);
2709 InFlag = Call.getValue(1);
2711 if (CallerSavedFP) {
2712 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2713 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2714 InFlag = Chain.getValue(1);
2717 uint64_t CalleePopBytes = NumBytes;
2718 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2719 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2722 InFlag = Chain.getValue(1);
2724 // Handle result values, copying them out of physregs into vregs that we
2726 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2727 InVals, IsThisReturn,
2728 IsThisReturn ? OutVals[0] : SDValue());
2731 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2732 SelectionDAG &DAG) const {
2733 unsigned Reg = StringSwitch<unsigned>(RegName)
2734 .Case("m0", AMDGPU::M0)
2735 .Case("exec", AMDGPU::EXEC)
2736 .Case("exec_lo", AMDGPU::EXEC_LO)
2737 .Case("exec_hi", AMDGPU::EXEC_HI)
2738 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2739 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2740 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2741 .Default(AMDGPU::NoRegister);
2743 if (Reg == AMDGPU::NoRegister) {
2744 report_fatal_error(Twine("invalid register name \""
2745 + StringRef(RegName) + "\"."));
2749 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2750 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2751 report_fatal_error(Twine("invalid register \""
2752 + StringRef(RegName) + "\" for subtarget."));
2757 case AMDGPU::EXEC_LO:
2758 case AMDGPU::EXEC_HI:
2759 case AMDGPU::FLAT_SCR_LO:
2760 case AMDGPU::FLAT_SCR_HI:
2761 if (VT.getSizeInBits() == 32)
2765 case AMDGPU::FLAT_SCR:
2766 if (VT.getSizeInBits() == 64)
2770 llvm_unreachable("missing register type checking");
2773 report_fatal_error(Twine("invalid type for register \""
2774 + StringRef(RegName) + "\"."));
2777 // If kill is not the last instruction, split the block so kill is always a
2778 // proper terminator.
2779 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2780 MachineBasicBlock *BB) const {
2781 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2783 MachineBasicBlock::iterator SplitPoint(&MI);
2786 if (SplitPoint == BB->end()) {
2787 // Don't bother with a new block.
2788 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2792 MachineFunction *MF = BB->getParent();
2793 MachineBasicBlock *SplitBB
2794 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2796 MF->insert(++MachineFunction::iterator(BB), SplitBB);
2797 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2799 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2800 BB->addSuccessor(SplitBB);
2802 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2806 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2807 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2808 // will only do one iteration. In the worst case, this will loop 64 times.
2810 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2811 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2812 const SIInstrInfo *TII,
2813 MachineRegisterInfo &MRI,
2814 MachineBasicBlock &OrigBB,
2815 MachineBasicBlock &LoopBB,
2817 const MachineOperand &IdxReg,
2821 unsigned InitSaveExecReg,
2824 bool IsIndirectSrc) {
2825 MachineBasicBlock::iterator I = LoopBB.begin();
2827 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2828 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2829 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2830 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2832 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2838 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2839 .addReg(InitSaveExecReg)
2844 // Read the next variant <- also loop target.
2845 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2846 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2848 // Compare the just read M0 value to all possible Idx values.
2849 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2850 .addReg(CurrentIdxReg)
2851 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2853 // Update EXEC, save the original EXEC value to VCC.
2854 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2855 .addReg(CondReg, RegState::Kill);
2857 MRI.setSimpleHint(NewExec, CondReg);
2859 if (UseGPRIdxMode) {
2862 IdxReg = CurrentIdxReg;
2864 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2865 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2866 .addReg(CurrentIdxReg, RegState::Kill)
2869 unsigned IdxMode = IsIndirectSrc ?
2870 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2871 MachineInstr *SetOn =
2872 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2873 .addReg(IdxReg, RegState::Kill)
2875 SetOn->getOperand(3).setIsUndef();
2877 // Move index from VCC into M0
2879 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2880 .addReg(CurrentIdxReg, RegState::Kill);
2882 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2883 .addReg(CurrentIdxReg, RegState::Kill)
2888 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2889 MachineInstr *InsertPt =
2890 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2891 .addReg(AMDGPU::EXEC)
2894 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2897 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2898 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2901 return InsertPt->getIterator();
2904 // This has slightly sub-optimal regalloc when the source vector is killed by
2905 // the read. The register allocator does not understand that the kill is
2906 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2907 // subregister from it, using 1 more VGPR than necessary. This was saved when
2908 // this was expanded after register allocation.
2909 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2910 MachineBasicBlock &MBB,
2912 unsigned InitResultReg,
2916 bool IsIndirectSrc) {
2917 MachineFunction *MF = MBB.getParent();
2918 MachineRegisterInfo &MRI = MF->getRegInfo();
2919 const DebugLoc &DL = MI.getDebugLoc();
2920 MachineBasicBlock::iterator I(&MI);
2922 unsigned DstReg = MI.getOperand(0).getReg();
2923 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2924 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2926 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2928 // Save the EXEC mask
2929 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2930 .addReg(AMDGPU::EXEC);
2932 // To insert the loop we need to split the block. Move everything after this
2933 // point to a new block, and insert a new empty block between the two.
2934 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2935 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2936 MachineFunction::iterator MBBI(MBB);
2939 MF->insert(MBBI, LoopBB);
2940 MF->insert(MBBI, RemainderBB);
2942 LoopBB->addSuccessor(LoopBB);
2943 LoopBB->addSuccessor(RemainderBB);
2945 // Move the rest of the block into a new block.
2946 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2947 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2949 MBB.addSuccessor(LoopBB);
2951 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2953 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2954 InitResultReg, DstReg, PhiReg, TmpExec,
2955 Offset, UseGPRIdxMode, IsIndirectSrc);
2957 MachineBasicBlock::iterator First = RemainderBB->begin();
2958 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2964 // Returns subreg index, offset
2965 static std::pair<unsigned, int>
2966 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2967 const TargetRegisterClass *SuperRC,
2970 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2972 // Skip out of bounds offsets, or else we would end up using an undefined
2974 if (Offset >= NumElts || Offset < 0)
2975 return std::make_pair(AMDGPU::sub0, Offset);
2977 return std::make_pair(AMDGPU::sub0 + Offset, 0);
2980 // Return true if the index is an SGPR and was set.
2981 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
2982 MachineRegisterInfo &MRI,
2986 bool IsIndirectSrc) {
2987 MachineBasicBlock *MBB = MI.getParent();
2988 const DebugLoc &DL = MI.getDebugLoc();
2989 MachineBasicBlock::iterator I(&MI);
2991 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2992 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2994 assert(Idx->getReg() != AMDGPU::NoRegister);
2996 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2999 if (UseGPRIdxMode) {
3000 unsigned IdxMode = IsIndirectSrc ?
3001 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
3003 MachineInstr *SetOn =
3004 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3008 SetOn->getOperand(3).setIsUndef();
3010 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3011 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3014 MachineInstr *SetOn =
3015 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3016 .addReg(Tmp, RegState::Kill)
3019 SetOn->getOperand(3).setIsUndef();
3026 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3029 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3037 // Control flow needs to be inserted if indexing with a VGPR.
3038 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3039 MachineBasicBlock &MBB,
3040 const GCNSubtarget &ST) {
3041 const SIInstrInfo *TII = ST.getInstrInfo();
3042 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3043 MachineFunction *MF = MBB.getParent();
3044 MachineRegisterInfo &MRI = MF->getRegInfo();
3046 unsigned Dst = MI.getOperand(0).getReg();
3047 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3048 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3050 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3053 std::tie(SubReg, Offset)
3054 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3056 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3058 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3059 MachineBasicBlock::iterator I(&MI);
3060 const DebugLoc &DL = MI.getDebugLoc();
3062 if (UseGPRIdxMode) {
3063 // TODO: Look at the uses to avoid the copy. This may require rescheduling
3064 // to avoid interfering with other uses, so probably requires a new
3065 // optimization pass.
3066 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3067 .addReg(SrcReg, RegState::Undef, SubReg)
3068 .addReg(SrcReg, RegState::Implicit)
3069 .addReg(AMDGPU::M0, RegState::Implicit);
3070 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3072 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3073 .addReg(SrcReg, RegState::Undef, SubReg)
3074 .addReg(SrcReg, RegState::Implicit);
3077 MI.eraseFromParent();
3082 const DebugLoc &DL = MI.getDebugLoc();
3083 MachineBasicBlock::iterator I(&MI);
3085 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3086 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3088 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3090 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3091 Offset, UseGPRIdxMode, true);
3092 MachineBasicBlock *LoopBB = InsPt->getParent();
3094 if (UseGPRIdxMode) {
3095 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3096 .addReg(SrcReg, RegState::Undef, SubReg)
3097 .addReg(SrcReg, RegState::Implicit)
3098 .addReg(AMDGPU::M0, RegState::Implicit);
3099 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3101 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3102 .addReg(SrcReg, RegState::Undef, SubReg)
3103 .addReg(SrcReg, RegState::Implicit);
3106 MI.eraseFromParent();
3111 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3112 const TargetRegisterClass *VecRC) {
3113 switch (TRI.getRegSizeInBits(*VecRC)) {
3115 return AMDGPU::V_MOVRELD_B32_V1;
3117 return AMDGPU::V_MOVRELD_B32_V2;
3118 case 128: // 16 bytes
3119 return AMDGPU::V_MOVRELD_B32_V4;
3120 case 256: // 32 bytes
3121 return AMDGPU::V_MOVRELD_B32_V8;
3122 case 512: // 64 bytes
3123 return AMDGPU::V_MOVRELD_B32_V16;
3125 llvm_unreachable("unsupported size for MOVRELD pseudos");
3129 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3130 MachineBasicBlock &MBB,
3131 const GCNSubtarget &ST) {
3132 const SIInstrInfo *TII = ST.getInstrInfo();
3133 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3134 MachineFunction *MF = MBB.getParent();
3135 MachineRegisterInfo &MRI = MF->getRegInfo();
3137 unsigned Dst = MI.getOperand(0).getReg();
3138 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3139 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3140 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3141 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3142 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3144 // This can be an immediate, but will be folded later.
3145 assert(Val->getReg());
3148 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3151 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3153 if (Idx->getReg() == AMDGPU::NoRegister) {
3154 MachineBasicBlock::iterator I(&MI);
3155 const DebugLoc &DL = MI.getDebugLoc();
3157 assert(Offset == 0);
3159 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3164 MI.eraseFromParent();
3168 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3169 MachineBasicBlock::iterator I(&MI);
3170 const DebugLoc &DL = MI.getDebugLoc();
3172 if (UseGPRIdxMode) {
3173 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3174 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3176 .addReg(Dst, RegState::ImplicitDefine)
3177 .addReg(SrcVec->getReg(), RegState::Implicit)
3178 .addReg(AMDGPU::M0, RegState::Implicit);
3180 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3182 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3184 BuildMI(MBB, I, DL, MovRelDesc)
3185 .addReg(Dst, RegState::Define)
3186 .addReg(SrcVec->getReg())
3188 .addImm(SubReg - AMDGPU::sub0);
3191 MI.eraseFromParent();
3196 MRI.clearKillFlags(Val->getReg());
3198 const DebugLoc &DL = MI.getDebugLoc();
3200 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3202 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3203 Offset, UseGPRIdxMode, false);
3204 MachineBasicBlock *LoopBB = InsPt->getParent();
3206 if (UseGPRIdxMode) {
3207 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3208 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3210 .addReg(Dst, RegState::ImplicitDefine)
3211 .addReg(PhiReg, RegState::Implicit)
3212 .addReg(AMDGPU::M0, RegState::Implicit);
3213 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3215 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3217 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3218 .addReg(Dst, RegState::Define)
3221 .addImm(SubReg - AMDGPU::sub0);
3224 MI.eraseFromParent();
3229 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3230 MachineInstr &MI, MachineBasicBlock *BB) const {
3232 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3233 MachineFunction *MF = BB->getParent();
3234 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3236 if (TII->isMIMG(MI)) {
3237 if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3238 report_fatal_error("missing mem operand from MIMG instruction");
3240 // Add a memoperand for mimg instructions so that they aren't assumed to
3241 // be ordered memory instuctions.
3246 switch (MI.getOpcode()) {
3247 case AMDGPU::S_ADD_U64_PSEUDO:
3248 case AMDGPU::S_SUB_U64_PSEUDO: {
3249 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3250 const DebugLoc &DL = MI.getDebugLoc();
3252 MachineOperand &Dest = MI.getOperand(0);
3253 MachineOperand &Src0 = MI.getOperand(1);
3254 MachineOperand &Src1 = MI.getOperand(2);
3256 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3257 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3259 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3260 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3261 &AMDGPU::SReg_32_XM0RegClass);
3262 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3263 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3264 &AMDGPU::SReg_32_XM0RegClass);
3266 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3267 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3268 &AMDGPU::SReg_32_XM0RegClass);
3269 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3270 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3271 &AMDGPU::SReg_32_XM0RegClass);
3273 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3275 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3276 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3277 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3280 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3283 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3285 .addImm(AMDGPU::sub0)
3287 .addImm(AMDGPU::sub1);
3288 MI.eraseFromParent();
3291 case AMDGPU::SI_INIT_M0: {
3292 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3293 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3294 .add(MI.getOperand(0));
3295 MI.eraseFromParent();
3298 case AMDGPU::SI_INIT_EXEC:
3299 // This should be before all vector instructions.
3300 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3302 .addImm(MI.getOperand(0).getImm());
3303 MI.eraseFromParent();
3306 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3307 // Extract the thread count from an SGPR input and set EXEC accordingly.
3308 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3310 // S_BFE_U32 count, input, {shift, 7}
3311 // S_BFM_B64 exec, count, 0
3312 // S_CMP_EQ_U32 count, 64
3313 // S_CMOV_B64 exec, -1
3314 MachineInstr *FirstMI = &*BB->begin();
3315 MachineRegisterInfo &MRI = MF->getRegInfo();
3316 unsigned InputReg = MI.getOperand(0).getReg();
3317 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3320 // Move the COPY of the input reg to the beginning, so that we can use it.
3321 for (auto I = BB->begin(); I != &MI; I++) {
3322 if (I->getOpcode() != TargetOpcode::COPY ||
3323 I->getOperand(0).getReg() != InputReg)
3327 FirstMI = &*++BB->begin();
3329 I->removeFromParent();
3330 BB->insert(FirstMI, &*I);
3338 // This should be before all vector instructions.
3339 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3341 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3342 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3346 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3347 .addReg(CountReg, RegState::Kill)
3349 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3352 MI.eraseFromParent();
3356 case AMDGPU::GET_GROUPSTATICSIZE: {
3357 DebugLoc DL = MI.getDebugLoc();
3358 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3359 .add(MI.getOperand(0))
3360 .addImm(MFI->getLDSSize());
3361 MI.eraseFromParent();
3364 case AMDGPU::SI_INDIRECT_SRC_V1:
3365 case AMDGPU::SI_INDIRECT_SRC_V2:
3366 case AMDGPU::SI_INDIRECT_SRC_V4:
3367 case AMDGPU::SI_INDIRECT_SRC_V8:
3368 case AMDGPU::SI_INDIRECT_SRC_V16:
3369 return emitIndirectSrc(MI, *BB, *getSubtarget());
3370 case AMDGPU::SI_INDIRECT_DST_V1:
3371 case AMDGPU::SI_INDIRECT_DST_V2:
3372 case AMDGPU::SI_INDIRECT_DST_V4:
3373 case AMDGPU::SI_INDIRECT_DST_V8:
3374 case AMDGPU::SI_INDIRECT_DST_V16:
3375 return emitIndirectDst(MI, *BB, *getSubtarget());
3376 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3377 case AMDGPU::SI_KILL_I1_PSEUDO:
3378 return splitKillBlock(MI, BB);
3379 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3380 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3382 unsigned Dst = MI.getOperand(0).getReg();
3383 unsigned Src0 = MI.getOperand(1).getReg();
3384 unsigned Src1 = MI.getOperand(2).getReg();
3385 const DebugLoc &DL = MI.getDebugLoc();
3386 unsigned SrcCond = MI.getOperand(3).getReg();
3388 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3389 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3390 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3392 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3394 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3395 .addReg(Src0, 0, AMDGPU::sub0)
3396 .addReg(Src1, 0, AMDGPU::sub0)
3397 .addReg(SrcCondCopy);
3398 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3399 .addReg(Src0, 0, AMDGPU::sub1)
3400 .addReg(Src1, 0, AMDGPU::sub1)
3401 .addReg(SrcCondCopy);
3403 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3405 .addImm(AMDGPU::sub0)
3407 .addImm(AMDGPU::sub1);
3408 MI.eraseFromParent();
3411 case AMDGPU::SI_BR_UNDEF: {
3412 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3413 const DebugLoc &DL = MI.getDebugLoc();
3414 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3415 .add(MI.getOperand(0));
3416 Br->getOperand(1).setIsUndef(true); // read undef SCC
3417 MI.eraseFromParent();
3420 case AMDGPU::ADJCALLSTACKUP:
3421 case AMDGPU::ADJCALLSTACKDOWN: {
3422 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3423 MachineInstrBuilder MIB(*MF, &MI);
3425 // Add an implicit use of the frame offset reg to prevent the restore copy
3426 // inserted after the call from being reorderd after stack operations in the
3427 // the caller's frame.
3428 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3429 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3430 .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3433 case AMDGPU::SI_CALL_ISEL:
3434 case AMDGPU::SI_TCRETURN_ISEL: {
3435 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3436 const DebugLoc &DL = MI.getDebugLoc();
3437 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3439 MachineRegisterInfo &MRI = MF->getRegInfo();
3440 unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3441 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3442 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3444 const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3446 MachineInstrBuilder MIB;
3447 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3448 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3449 .add(MI.getOperand(0))
3450 .addGlobalAddress(G);
3452 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3453 .add(MI.getOperand(0))
3454 .addGlobalAddress(G);
3456 // There is an additional imm operand for tcreturn, but it should be in the
3457 // right place already.
3460 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3461 MIB.add(MI.getOperand(I));
3463 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3464 MI.eraseFromParent();
3468 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3472 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3473 return isTypeLegal(VT.getScalarType());
3476 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3477 // This currently forces unfolding various combinations of fsub into fma with
3478 // free fneg'd operands. As long as we have fast FMA (controlled by
3479 // isFMAFasterThanFMulAndFAdd), we should perform these.
3481 // When fma is quarter rate, for f64 where add / sub are at best half rate,
3482 // most of these combines appear to be cycle neutral but save on instruction
3483 // count / code size.
3487 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3489 if (!VT.isVector()) {
3492 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3495 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3496 // TODO: Should i16 be used always if legal? For now it would force VALU
3498 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3501 // Answering this is somewhat tricky and depends on the specific device which
3502 // have different rates for fma or all f64 operations.
3504 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3505 // regardless of which device (although the number of cycles differs between
3506 // devices), so it is always profitable for f64.
3508 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3509 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3510 // which we can always do even without fused FP ops since it returns the same
3511 // result as the separate operations and since it is always full
3512 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3513 // however does not support denormals, so we do report fma as faster if we have
3514 // a fast fma device and require denormals.
3516 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3517 VT = VT.getScalarType();
3519 switch (VT.getSimpleVT().SimpleTy) {
3521 // This is as fast on some subtargets. However, we always have full rate f32
3522 // mad available which returns the same result as the separate operations
3523 // which we should prefer over fma. We can't use this if we want to support
3524 // denormals, so only report this in these cases.
3525 if (Subtarget->hasFP32Denormals())
3526 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3528 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3529 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3534 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3542 //===----------------------------------------------------------------------===//
3543 // Custom DAG Lowering Operations
3544 //===----------------------------------------------------------------------===//
3546 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3547 // wider vector type is legal.
3548 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3549 SelectionDAG &DAG) const {
3550 unsigned Opc = Op.getOpcode();
3551 EVT VT = Op.getValueType();
3552 assert(VT == MVT::v4f16);
3555 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3558 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3560 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3563 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3566 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3567 // wider vector type is legal.
3568 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3569 SelectionDAG &DAG) const {
3570 unsigned Opc = Op.getOpcode();
3571 EVT VT = Op.getValueType();
3572 assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3575 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3577 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3581 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3583 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3586 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3589 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3590 switch (Op.getOpcode()) {
3591 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3592 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3594 SDValue Result = LowerLOAD(Op, DAG);
3595 assert((!Result.getNode() ||
3596 Result.getNode()->getNumValues() == 2) &&
3597 "Load should return a value and a chain");
3603 return LowerTrig(Op, DAG);
3604 case ISD::SELECT: return LowerSELECT(Op, DAG);
3605 case ISD::FDIV: return LowerFDIV(Op, DAG);
3606 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3607 case ISD::STORE: return LowerSTORE(Op, DAG);
3608 case ISD::GlobalAddress: {
3609 MachineFunction &MF = DAG.getMachineFunction();
3610 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3611 return LowerGlobalAddress(MFI, Op, DAG);
3613 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3614 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3615 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3616 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3617 case ISD::INSERT_VECTOR_ELT:
3618 return lowerINSERT_VECTOR_ELT(Op, DAG);
3619 case ISD::EXTRACT_VECTOR_ELT:
3620 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3621 case ISD::BUILD_VECTOR:
3622 return lowerBUILD_VECTOR(Op, DAG);
3624 return lowerFP_ROUND(Op, DAG);
3626 return lowerTRAP(Op, DAG);
3627 case ISD::DEBUGTRAP:
3628 return lowerDEBUGTRAP(Op, DAG);
3631 return splitUnaryVectorOp(Op, DAG);
3646 return splitBinaryVectorOp(Op, DAG);
3651 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
3653 SelectionDAG &DAG, bool Unpacked) {
3654 if (!LoadVT.isVector())
3657 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3658 // Truncate to v2i16/v4i16.
3659 EVT IntLoadVT = LoadVT.changeTypeToInteger();
3661 // Workaround legalizer not scalarizing truncate after vector op
3662 // legalization byt not creating intermediate vector trunc.
3663 SmallVector<SDValue, 4> Elts;
3664 DAG.ExtractVectorElements(Result, Elts);
3665 for (SDValue &Elt : Elts)
3666 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3668 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3670 // Bitcast to original type (v2f16/v4f16).
3671 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3674 // Cast back to the original packed type.
3675 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3678 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
3681 bool IsIntrinsic) const {
3683 SmallVector<SDValue, 10> Ops;
3684 Ops.reserve(M->getNumOperands());
3686 Ops.push_back(M->getOperand(0));
3688 Ops.push_back(DAG.getConstant(Opcode, DL, MVT::i32));
3690 // Skip 1, as it is the intrinsic ID.
3691 for (unsigned I = 2, E = M->getNumOperands(); I != E; ++I)
3692 Ops.push_back(M->getOperand(I));
3694 bool Unpacked = Subtarget->hasUnpackedD16VMem();
3695 EVT LoadVT = M->getValueType(0);
3697 EVT EquivLoadVT = LoadVT;
3698 if (Unpacked && LoadVT.isVector()) {
3699 EquivLoadVT = LoadVT.isVector() ?
3700 EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3701 LoadVT.getVectorNumElements()) : LoadVT;
3704 // Change from v4f16/v2f16 to EquivLoadVT.
3705 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3708 = DAG.getMemIntrinsicNode(
3709 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
3710 VTList, Ops, M->getMemoryVT(),
3711 M->getMemOperand());
3712 if (!Unpacked) // Just adjusted the opcode.
3715 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
3717 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
3720 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3721 SmallVectorImpl<SDValue> &Results,
3722 SelectionDAG &DAG) const {
3723 switch (N->getOpcode()) {
3724 case ISD::INSERT_VECTOR_ELT: {
3725 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3726 Results.push_back(Res);
3729 case ISD::EXTRACT_VECTOR_ELT: {
3730 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3731 Results.push_back(Res);
3734 case ISD::INTRINSIC_WO_CHAIN: {
3735 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3737 case Intrinsic::amdgcn_cvt_pkrtz: {
3738 SDValue Src0 = N->getOperand(1);
3739 SDValue Src1 = N->getOperand(2);
3741 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3743 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3746 case Intrinsic::amdgcn_cvt_pknorm_i16:
3747 case Intrinsic::amdgcn_cvt_pknorm_u16:
3748 case Intrinsic::amdgcn_cvt_pk_i16:
3749 case Intrinsic::amdgcn_cvt_pk_u16: {
3750 SDValue Src0 = N->getOperand(1);
3751 SDValue Src1 = N->getOperand(2);
3755 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3756 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
3757 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3758 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
3759 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3760 Opcode = AMDGPUISD::CVT_PK_I16_I32;
3762 Opcode = AMDGPUISD::CVT_PK_U16_U32;
3764 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
3765 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
3771 case ISD::INTRINSIC_W_CHAIN: {
3772 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
3773 Results.push_back(Res);
3774 Results.push_back(Res.getValue(1));
3782 EVT VT = N->getValueType(0);
3783 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3784 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3785 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3787 EVT SelectVT = NewVT;
3788 if (NewVT.bitsLT(MVT::i32)) {
3789 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3790 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3791 SelectVT = MVT::i32;
3794 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3795 N->getOperand(0), LHS, RHS);
3797 if (NewVT != SelectVT)
3798 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3799 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3803 if (N->getValueType(0) != MVT::v2f16)
3807 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3809 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
3811 DAG.getConstant(0x80008000, SL, MVT::i32));
3812 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3816 if (N->getValueType(0) != MVT::v2f16)
3820 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3822 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
3824 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
3825 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3833 /// Helper function for LowerBRCOND
3834 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3836 SDNode *Parent = Value.getNode();
3837 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3840 if (I.getUse().get() != Value)
3843 if (I->getOpcode() == Opcode)
3849 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3850 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3851 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3852 case Intrinsic::amdgcn_if:
3853 return AMDGPUISD::IF;
3854 case Intrinsic::amdgcn_else:
3855 return AMDGPUISD::ELSE;
3856 case Intrinsic::amdgcn_loop:
3857 return AMDGPUISD::LOOP;
3858 case Intrinsic::amdgcn_end_cf:
3859 llvm_unreachable("should not occur");
3865 // break, if_break, else_break are all only used as inputs to loop, not
3866 // directly as branch conditions.
3870 void SITargetLowering::createDebuggerPrologueStackObjects(
3871 MachineFunction &MF) const {
3872 // Create stack objects that are used for emitting debugger prologue.
3874 // Debugger prologue writes work group IDs and work item IDs to scratch memory
3875 // at fixed location in the following format:
3876 // offset 0: work group ID x
3877 // offset 4: work group ID y
3878 // offset 8: work group ID z
3879 // offset 16: work item ID x
3880 // offset 20: work item ID y
3881 // offset 24: work item ID z
3882 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3885 // For each dimension:
3886 for (unsigned i = 0; i < 3; ++i) {
3887 // Create fixed stack object for work group ID.
3888 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
3889 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
3890 // Create fixed stack object for work item ID.
3891 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
3892 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
3896 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
3897 const Triple &TT = getTargetMachine().getTargetTriple();
3898 return (GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
3899 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
3900 AMDGPU::shouldEmitConstantsToTextSection(TT);
3903 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
3904 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
3905 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
3906 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
3907 !shouldEmitFixup(GV) &&
3908 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3911 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
3912 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
3915 /// This transforms the control flow intrinsics to get the branch destination as
3916 /// last parameter, also switches branch target with BR if the need arise
3917 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
3918 SelectionDAG &DAG) const {
3921 SDNode *Intr = BRCOND.getOperand(1).getNode();
3922 SDValue Target = BRCOND.getOperand(2);
3923 SDNode *BR = nullptr;
3924 SDNode *SetCC = nullptr;
3926 if (Intr->getOpcode() == ISD::SETCC) {
3927 // As long as we negate the condition everything is fine
3929 Intr = SetCC->getOperand(0).getNode();
3932 // Get the target from BR if we don't negate the condition
3933 BR = findUser(BRCOND, ISD::BR);
3934 Target = BR->getOperand(1);
3937 // FIXME: This changes the types of the intrinsics instead of introducing new
3938 // nodes with the correct types.
3939 // e.g. llvm.amdgcn.loop
3941 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
3942 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
3944 unsigned CFNode = isCFIntrinsic(Intr);
3946 // This is a uniform branch so we don't need to legalize.
3950 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
3951 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
3954 (SetCC->getConstantOperandVal(1) == 1 &&
3955 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
3958 // operands of the new intrinsic call
3959 SmallVector<SDValue, 4> Ops;
3961 Ops.push_back(BRCOND.getOperand(0));
3963 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
3964 Ops.push_back(Target);
3966 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
3968 // build the new intrinsic call
3969 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
3974 BRCOND.getOperand(0)
3977 Result = DAG.getMergeValues(Ops, DL).getNode();
3981 // Give the branch instruction our target
3984 BRCOND.getOperand(2)
3986 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
3987 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
3988 BR = NewBR.getNode();
3991 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
3993 // Copy the intrinsic results to registers
3994 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
3995 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
3999 Chain = DAG.getCopyToReg(
4001 CopyToReg->getOperand(1),
4002 SDValue(Result, i - 1),
4005 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4008 // Remove the old intrinsic from the chain
4009 DAG.ReplaceAllUsesOfValueWith(
4010 SDValue(Intr, Intr->getNumValues() - 1),
4011 Intr->getOperand(0));
4016 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4020 return Op.getValueType().bitsLE(VT) ?
4021 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4022 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4025 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4026 assert(Op.getValueType() == MVT::f16 &&
4027 "Do not know how to custom lower FP_ROUND for non-f16 type");
4029 SDValue Src = Op.getOperand(0);
4030 EVT SrcVT = Src.getValueType();
4031 if (SrcVT != MVT::f64)
4036 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4037 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4038 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4041 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4043 SDValue Chain = Op.getOperand(0);
4045 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4046 !Subtarget->isTrapHandlerEnabled())
4047 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4049 MachineFunction &MF = DAG.getMachineFunction();
4050 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4051 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4052 assert(UserSGPR != AMDGPU::NoRegister);
4053 SDValue QueuePtr = CreateLiveInRegister(
4054 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4055 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4056 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4057 QueuePtr, SDValue());
4060 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4064 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4067 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4069 SDValue Chain = Op.getOperand(0);
4070 MachineFunction &MF = DAG.getMachineFunction();
4072 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4073 !Subtarget->isTrapHandlerEnabled()) {
4074 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4075 "debugtrap handler not supported",
4078 LLVMContext &Ctx = MF.getFunction().getContext();
4079 Ctx.diagnose(NoTrap);
4085 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4087 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4090 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4091 SelectionDAG &DAG) const {
4092 // FIXME: Use inline constants (src_{shared, private}_base) instead.
4093 if (Subtarget->hasApertureRegs()) {
4094 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
4095 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4096 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4097 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
4098 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4099 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4101 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4102 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4103 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4105 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4106 SDValue ApertureReg = SDValue(
4107 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4108 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4109 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4112 MachineFunction &MF = DAG.getMachineFunction();
4113 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4114 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4115 assert(UserSGPR != AMDGPU::NoRegister);
4117 SDValue QueuePtr = CreateLiveInRegister(
4118 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4120 // Offset into amd_queue_t for group_segment_aperture_base_hi /
4121 // private_segment_aperture_base_hi.
4122 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
4124 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4126 // TODO: Use custom target PseudoSourceValue.
4127 // TODO: We should use the value from the IR intrinsic call, but it might not
4128 // be available and how do we get it?
4129 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4130 AMDGPUASI.CONSTANT_ADDRESS));
4132 MachinePointerInfo PtrInfo(V, StructOffset);
4133 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4134 MinAlign(64, StructOffset),
4135 MachineMemOperand::MODereferenceable |
4136 MachineMemOperand::MOInvariant);
4139 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4140 SelectionDAG &DAG) const {
4142 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4144 SDValue Src = ASC->getOperand(0);
4145 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4147 const AMDGPUTargetMachine &TM =
4148 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4150 // flat -> local/private
4151 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4152 unsigned DestAS = ASC->getDestAddressSpace();
4154 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
4155 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
4156 unsigned NullVal = TM.getNullPointerValue(DestAS);
4157 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4158 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4159 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4161 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4162 NonNull, Ptr, SegmentNullPtr);
4166 // local/private -> flat
4167 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4168 unsigned SrcAS = ASC->getSrcAddressSpace();
4170 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
4171 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
4172 unsigned NullVal = TM.getNullPointerValue(SrcAS);
4173 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4176 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4178 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4180 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4182 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4183 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4188 // global <-> flat are no-ops and never emitted.
4190 const MachineFunction &MF = DAG.getMachineFunction();
4191 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4192 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4193 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4195 return DAG.getUNDEF(ASC->getValueType(0));
4198 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4199 SelectionDAG &DAG) const {
4200 SDValue Vec = Op.getOperand(0);
4201 SDValue InsVal = Op.getOperand(1);
4202 SDValue Idx = Op.getOperand(2);
4203 EVT VecVT = Vec.getValueType();
4204 EVT EltVT = VecVT.getVectorElementType();
4205 unsigned VecSize = VecVT.getSizeInBits();
4206 unsigned EltSize = EltVT.getSizeInBits();
4209 assert(VecSize <= 64);
4211 unsigned NumElts = VecVT.getVectorNumElements();
4213 auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4215 if (NumElts == 4 && EltSize == 16 && KIdx) {
4216 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4218 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4219 DAG.getConstant(0, SL, MVT::i32));
4220 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4221 DAG.getConstant(1, SL, MVT::i32));
4223 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4224 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4226 unsigned Idx = KIdx->getZExtValue();
4227 bool InsertLo = Idx < 2;
4228 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4229 InsertLo ? LoVec : HiVec,
4230 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4231 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4233 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4235 SDValue Concat = InsertLo ?
4236 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4237 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4239 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4242 if (isa<ConstantSDNode>(Idx))
4245 MVT IntVT = MVT::getIntegerVT(VecSize);
4247 // Avoid stack access for dynamic indexing.
4248 SDValue Val = InsVal;
4249 if (InsVal.getValueType() == MVT::f16)
4250 Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal);
4252 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4253 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Val);
4255 assert(isPowerOf2_32(EltSize));
4256 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4258 // Convert vector index to bit-index.
4259 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4261 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4262 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4263 DAG.getConstant(0xffff, SL, IntVT),
4266 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4267 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4268 DAG.getNOT(SL, BFM, IntVT), BCVec);
4270 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4271 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4274 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4275 SelectionDAG &DAG) const {
4278 EVT ResultVT = Op.getValueType();
4279 SDValue Vec = Op.getOperand(0);
4280 SDValue Idx = Op.getOperand(1);
4281 EVT VecVT = Vec.getValueType();
4282 unsigned VecSize = VecVT.getSizeInBits();
4283 EVT EltVT = VecVT.getVectorElementType();
4284 assert(VecSize <= 64);
4286 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4288 // Make sure we do any optimizations that will make it easier to fold
4289 // source modifiers before obscuring it with bit operations.
4291 // XXX - Why doesn't this get called when vector_shuffle is expanded?
4292 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4295 unsigned EltSize = EltVT.getSizeInBits();
4296 assert(isPowerOf2_32(EltSize));
4298 MVT IntVT = MVT::getIntegerVT(VecSize);
4299 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4301 // Convert vector index to bit-index (* EltSize)
4302 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4304 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4305 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4307 if (ResultVT == MVT::f16) {
4308 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4309 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4312 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4315 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4316 SelectionDAG &DAG) const {
4318 EVT VT = Op.getValueType();
4320 if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4321 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4323 // Turn into pair of packed build_vectors.
4324 // TODO: Special case for constants that can be materialized with s_mov_b64.
4325 SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4326 { Op.getOperand(0), Op.getOperand(1) });
4327 SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4328 { Op.getOperand(2), Op.getOperand(3) });
4330 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4331 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4333 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4334 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4337 assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4339 SDValue Lo = Op.getOperand(0);
4340 SDValue Hi = Op.getOperand(1);
4342 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4343 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4345 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4346 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4348 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4349 DAG.getConstant(16, SL, MVT::i32));
4351 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4353 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4357 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4358 // We can fold offsets for anything that doesn't require a GOT relocation.
4359 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
4360 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4361 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4362 !shouldEmitGOTReloc(GA->getGlobal());
4366 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4367 const SDLoc &DL, unsigned Offset, EVT PtrVT,
4368 unsigned GAFlags = SIInstrInfo::MO_NONE) {
4369 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4370 // lowered to the following code sequence:
4372 // For constant address space:
4373 // s_getpc_b64 s[0:1]
4374 // s_add_u32 s0, s0, $symbol
4375 // s_addc_u32 s1, s1, 0
4377 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4378 // a fixup or relocation is emitted to replace $symbol with a literal
4379 // constant, which is a pc-relative offset from the encoding of the $symbol
4380 // operand to the global variable.
4382 // For global address space:
4383 // s_getpc_b64 s[0:1]
4384 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4385 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4387 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4388 // fixups or relocations are emitted to replace $symbol@*@lo and
4389 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4390 // which is a 64-bit pc-relative offset from the encoding of the $symbol
4391 // operand to the global variable.
4393 // What we want here is an offset from the value returned by s_getpc
4394 // (which is the address of the s_add_u32 instruction) to the global
4395 // variable, but since the encoding of $symbol starts 4 bytes after the start
4396 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4397 // small. This requires us to add 4 to the global variable offset in order to
4398 // compute the correct address.
4399 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4401 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4402 GAFlags == SIInstrInfo::MO_NONE ?
4403 GAFlags : GAFlags + 1);
4404 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4407 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4409 SelectionDAG &DAG) const {
4410 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4411 const GlobalValue *GV = GSD->getGlobal();
4413 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
4414 GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
4415 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS &&
4416 // FIXME: It isn't correct to rely on the type of the pointer. This should
4417 // be removed when address space 0 is 64-bit.
4418 !GV->getType()->getElementType()->isFunctionTy())
4419 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4422 EVT PtrVT = Op.getValueType();
4424 if (shouldEmitFixup(GV))
4425 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4426 else if (shouldEmitPCReloc(GV))
4427 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4428 SIInstrInfo::MO_REL32);
4430 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4431 SIInstrInfo::MO_GOTPCREL32);
4433 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4434 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
4435 const DataLayout &DataLayout = DAG.getDataLayout();
4436 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4437 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
4438 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
4440 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4441 MachineMemOperand::MODereferenceable |
4442 MachineMemOperand::MOInvariant);
4445 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4446 const SDLoc &DL, SDValue V) const {
4447 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4448 // the destination register.
4450 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4451 // so we will end up with redundant moves to m0.
4453 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4455 // A Null SDValue creates a glue result.
4456 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4458 return SDValue(M0, 0);
4461 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4464 unsigned Offset) const {
4466 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4467 DAG.getEntryNode(), Offset, 4, false);
4468 // The local size values will have the hi 16-bits as zero.
4469 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4470 DAG.getValueType(VT));
4473 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4475 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4476 "non-hsa intrinsic with hsa target",
4478 DAG.getContext()->diagnose(BadIntrin);
4479 return DAG.getUNDEF(VT);
4482 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4484 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4485 "intrinsic not supported on subtarget",
4487 DAG.getContext()->diagnose(BadIntrin);
4488 return DAG.getUNDEF(VT);
4491 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
4492 ArrayRef<SDValue> Elts) {
4493 assert(!Elts.empty());
4497 if (Elts.size() == 1) {
4500 } else if (Elts.size() == 2) {
4503 } else if (Elts.size() <= 4) {
4506 } else if (Elts.size() <= 8) {
4510 assert(Elts.size() <= 16);
4515 SmallVector<SDValue, 16> VecElts(NumElts);
4516 for (unsigned i = 0; i < Elts.size(); ++i) {
4517 SDValue Elt = Elts[i];
4518 if (Elt.getValueType() != MVT::f32)
4519 Elt = DAG.getBitcast(MVT::f32, Elt);
4522 for (unsigned i = Elts.size(); i < NumElts; ++i)
4523 VecElts[i] = DAG.getUNDEF(MVT::f32);
4527 return DAG.getBuildVector(Type, DL, VecElts);
4530 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
4531 SDValue *GLC, SDValue *SLC) {
4532 auto CachePolicyConst = dyn_cast<ConstantSDNode>(CachePolicy.getNode());
4533 if (!CachePolicyConst)
4536 uint64_t Value = CachePolicyConst->getZExtValue();
4537 SDLoc DL(CachePolicy);
4539 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4540 Value &= ~(uint64_t)0x1;
4543 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4544 Value &= ~(uint64_t)0x2;
4550 SDValue SITargetLowering::lowerImage(SDValue Op,
4551 const AMDGPU::ImageDimIntrinsicInfo *Intr,
4552 SelectionDAG &DAG) const {
4554 MachineFunction &MF = DAG.getMachineFunction();
4555 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4556 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
4557 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
4558 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
4559 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
4560 unsigned IntrOpcode = Intr->BaseOpcode;
4562 SmallVector<EVT, 2> ResultTypes(Op->value_begin(), Op->value_end());
4566 unsigned AddrIdx; // Index of first address argument
4569 if (BaseOpcode->Atomic) {
4570 VData = Op.getOperand(2);
4572 bool Is64Bit = VData.getValueType() == MVT::i64;
4573 if (BaseOpcode->AtomicX2) {
4574 SDValue VData2 = Op.getOperand(3);
4575 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
4578 VData = DAG.getBitcast(MVT::v4i32, VData);
4580 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
4581 DMask = Is64Bit ? 0xf : 0x3;
4582 NumVDataDwords = Is64Bit ? 4 : 2;
4585 DMask = Is64Bit ? 0x3 : 0x1;
4586 NumVDataDwords = Is64Bit ? 2 : 1;
4592 if (BaseOpcode->Store) {
4593 VData = Op.getOperand(2);
4595 MVT StoreVT = VData.getSimpleValueType();
4596 if (StoreVT.getScalarType() == MVT::f16) {
4597 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4598 !BaseOpcode->HasD16)
4599 return Op; // D16 is unsupported for this instruction
4602 VData = handleD16VData(VData, DAG);
4605 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
4608 MVT LoadVT = Op.getSimpleValueType();
4609 if (LoadVT.getScalarType() == MVT::f16) {
4610 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4611 !BaseOpcode->HasD16)
4612 return Op; // D16 is unsupported for this instruction
4615 if (LoadVT.isVector() && Subtarget->hasUnpackedD16VMem())
4616 ResultTypes[0] = (LoadVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32;
4619 NumVDataDwords = (ResultTypes[0].getSizeInBits() + 31) / 32;
4620 DMaskIdx = isa<MemSDNode>(Op) ? 2 : 1;
4623 auto DMaskConst = dyn_cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
4627 AddrIdx = DMaskIdx + 1;
4628 DMask = DMaskConst->getZExtValue();
4629 if (!DMask && !BaseOpcode->Store) {
4630 // Eliminate no-op loads. Stores with dmask == 0 are *not* no-op: they
4631 // store the channels' default values.
4632 SDValue Undef = DAG.getUNDEF(Op.getValueType());
4633 if (isa<MemSDNode>(Op))
4634 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
4639 unsigned NumVAddrs = BaseOpcode->NumExtraArgs +
4640 (BaseOpcode->Gradients ? DimInfo->NumGradients : 0) +
4641 (BaseOpcode->Coordinates ? DimInfo->NumCoords : 0) +
4642 (BaseOpcode->LodOrClampOrMip ? 1 : 0);
4643 SmallVector<SDValue, 4> VAddrs;
4644 for (unsigned i = 0; i < NumVAddrs; ++i)
4645 VAddrs.push_back(Op.getOperand(AddrIdx + i));
4647 // Optimize _L to _LZ when _L is zero
4648 if (LZMappingInfo) {
4649 if (auto ConstantLod =
4650 dyn_cast<ConstantFPSDNode>(VAddrs[NumVAddrs-1].getNode())) {
4651 if (ConstantLod->isZero() || ConstantLod->isNegative()) {
4652 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l
4653 VAddrs.pop_back(); // remove 'lod'
4658 SDValue VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
4660 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
4661 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
4662 unsigned CtrlIdx; // Index of texfailctrl argument
4664 if (!BaseOpcode->Sampler) {
4666 CtrlIdx = AddrIdx + NumVAddrs + 1;
4669 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
4673 Unorm = UnormConst->getZExtValue() ? True : False;
4674 CtrlIdx = AddrIdx + NumVAddrs + 3;
4677 SDValue TexFail = Op.getOperand(CtrlIdx);
4678 auto TexFailConst = dyn_cast<ConstantSDNode>(TexFail.getNode());
4679 if (!TexFailConst || TexFailConst->getZExtValue() != 0)
4684 if (BaseOpcode->Atomic) {
4685 GLC = True; // TODO no-return optimization
4686 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC))
4689 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC))
4693 SmallVector<SDValue, 14> Ops;
4694 if (BaseOpcode->Store || BaseOpcode->Atomic)
4695 Ops.push_back(VData); // vdata
4696 Ops.push_back(VAddr);
4697 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
4698 if (BaseOpcode->Sampler)
4699 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
4700 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
4701 Ops.push_back(Unorm);
4704 Ops.push_back(False); // r128
4705 Ops.push_back(False); // tfe
4706 Ops.push_back(False); // lwe
4707 Ops.push_back(DimInfo->DA ? True : False);
4708 if (BaseOpcode->HasD16)
4709 Ops.push_back(IsD16 ? True : False);
4710 if (isa<MemSDNode>(Op))
4711 Ops.push_back(Op.getOperand(0)); // chain
4713 int NumVAddrDwords = VAddr.getValueType().getSizeInBits() / 32;
4716 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
4717 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
4718 NumVDataDwords, NumVAddrDwords);
4720 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
4721 NumVDataDwords, NumVAddrDwords);
4722 assert(Opcode != -1);
4724 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
4725 if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
4726 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
4727 *MemRefs = MemOp->getMemOperand();
4728 NewNode->setMemRefs(MemRefs, MemRefs + 1);
4731 if (BaseOpcode->AtomicX2) {
4732 SmallVector<SDValue, 1> Elt;
4733 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
4734 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
4735 } else if (IsD16 && !BaseOpcode->Store) {
4736 MVT LoadVT = Op.getSimpleValueType();
4737 SDValue Adjusted = adjustLoadValueTypeImpl(
4738 SDValue(NewNode, 0), LoadVT, DL, DAG, Subtarget->hasUnpackedD16VMem());
4739 return DAG.getMergeValues({Adjusted, SDValue(NewNode, 1)}, DL);
4742 return SDValue(NewNode, 0);
4745 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4746 SelectionDAG &DAG) const {
4747 MachineFunction &MF = DAG.getMachineFunction();
4748 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
4750 EVT VT = Op.getValueType();
4752 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4754 // TODO: Should this propagate fast-math-flags?
4756 switch (IntrinsicID) {
4757 case Intrinsic::amdgcn_implicit_buffer_ptr: {
4758 if (getSubtarget()->isAmdCodeObjectV2(MF.getFunction()))
4759 return emitNonHSAIntrinsicError(DAG, DL, VT);
4760 return getPreloadedValue(DAG, *MFI, VT,
4761 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
4763 case Intrinsic::amdgcn_dispatch_ptr:
4764 case Intrinsic::amdgcn_queue_ptr: {
4765 if (!Subtarget->isAmdCodeObjectV2(MF.getFunction())) {
4766 DiagnosticInfoUnsupported BadIntrin(
4767 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
4769 DAG.getContext()->diagnose(BadIntrin);
4770 return DAG.getUNDEF(VT);
4773 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
4774 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
4775 return getPreloadedValue(DAG, *MFI, VT, RegID);
4777 case Intrinsic::amdgcn_implicitarg_ptr: {
4778 if (MFI->isEntryFunction())
4779 return getImplicitArgPtr(DAG, DL);
4780 return getPreloadedValue(DAG, *MFI, VT,
4781 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
4783 case Intrinsic::amdgcn_kernarg_segment_ptr: {
4784 return getPreloadedValue(DAG, *MFI, VT,
4785 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
4787 case Intrinsic::amdgcn_dispatch_id: {
4788 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
4790 case Intrinsic::amdgcn_rcp:
4791 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
4792 case Intrinsic::amdgcn_rsq:
4793 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4794 case Intrinsic::amdgcn_rsq_legacy:
4795 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
4796 return emitRemovedIntrinsicError(DAG, DL, VT);
4798 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
4799 case Intrinsic::amdgcn_rcp_legacy:
4800 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
4801 return emitRemovedIntrinsicError(DAG, DL, VT);
4802 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
4803 case Intrinsic::amdgcn_rsq_clamp: {
4804 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
4805 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
4807 Type *Type = VT.getTypeForEVT(*DAG.getContext());
4808 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
4809 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
4811 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4812 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
4813 DAG.getConstantFP(Max, DL, VT));
4814 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
4815 DAG.getConstantFP(Min, DL, VT));
4817 case Intrinsic::r600_read_ngroups_x:
4818 if (Subtarget->isAmdHsaOS())
4819 return emitNonHSAIntrinsicError(DAG, DL, VT);
4821 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4822 SI::KernelInputOffsets::NGROUPS_X, 4, false);
4823 case Intrinsic::r600_read_ngroups_y:
4824 if (Subtarget->isAmdHsaOS())
4825 return emitNonHSAIntrinsicError(DAG, DL, VT);
4827 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4828 SI::KernelInputOffsets::NGROUPS_Y, 4, false);
4829 case Intrinsic::r600_read_ngroups_z:
4830 if (Subtarget->isAmdHsaOS())
4831 return emitNonHSAIntrinsicError(DAG, DL, VT);
4833 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4834 SI::KernelInputOffsets::NGROUPS_Z, 4, false);
4835 case Intrinsic::r600_read_global_size_x:
4836 if (Subtarget->isAmdHsaOS())
4837 return emitNonHSAIntrinsicError(DAG, DL, VT);
4839 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4840 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
4841 case Intrinsic::r600_read_global_size_y:
4842 if (Subtarget->isAmdHsaOS())
4843 return emitNonHSAIntrinsicError(DAG, DL, VT);
4845 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4846 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
4847 case Intrinsic::r600_read_global_size_z:
4848 if (Subtarget->isAmdHsaOS())
4849 return emitNonHSAIntrinsicError(DAG, DL, VT);
4851 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4852 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
4853 case Intrinsic::r600_read_local_size_x:
4854 if (Subtarget->isAmdHsaOS())
4855 return emitNonHSAIntrinsicError(DAG, DL, VT);
4857 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4858 SI::KernelInputOffsets::LOCAL_SIZE_X);
4859 case Intrinsic::r600_read_local_size_y:
4860 if (Subtarget->isAmdHsaOS())
4861 return emitNonHSAIntrinsicError(DAG, DL, VT);
4863 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4864 SI::KernelInputOffsets::LOCAL_SIZE_Y);
4865 case Intrinsic::r600_read_local_size_z:
4866 if (Subtarget->isAmdHsaOS())
4867 return emitNonHSAIntrinsicError(DAG, DL, VT);
4869 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4870 SI::KernelInputOffsets::LOCAL_SIZE_Z);
4871 case Intrinsic::amdgcn_workgroup_id_x:
4872 case Intrinsic::r600_read_tgid_x:
4873 return getPreloadedValue(DAG, *MFI, VT,
4874 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
4875 case Intrinsic::amdgcn_workgroup_id_y:
4876 case Intrinsic::r600_read_tgid_y:
4877 return getPreloadedValue(DAG, *MFI, VT,
4878 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
4879 case Intrinsic::amdgcn_workgroup_id_z:
4880 case Intrinsic::r600_read_tgid_z:
4881 return getPreloadedValue(DAG, *MFI, VT,
4882 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
4883 case Intrinsic::amdgcn_workitem_id_x: {
4884 case Intrinsic::r600_read_tidig_x:
4885 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4886 SDLoc(DAG.getEntryNode()),
4887 MFI->getArgInfo().WorkItemIDX);
4889 case Intrinsic::amdgcn_workitem_id_y:
4890 case Intrinsic::r600_read_tidig_y:
4891 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4892 SDLoc(DAG.getEntryNode()),
4893 MFI->getArgInfo().WorkItemIDY);
4894 case Intrinsic::amdgcn_workitem_id_z:
4895 case Intrinsic::r600_read_tidig_z:
4896 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4897 SDLoc(DAG.getEntryNode()),
4898 MFI->getArgInfo().WorkItemIDZ);
4899 case AMDGPUIntrinsic::SI_load_const: {
4905 MachineMemOperand *MMO = MF.getMachineMemOperand(
4906 MachinePointerInfo(),
4907 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
4908 MachineMemOperand::MOInvariant,
4909 VT.getStoreSize(), 4);
4910 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
4911 Op->getVTList(), Ops, VT, MMO);
4913 case Intrinsic::amdgcn_fdiv_fast:
4914 return lowerFDIV_FAST(Op, DAG);
4915 case Intrinsic::amdgcn_interp_mov: {
4916 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4917 SDValue Glue = M0.getValue(1);
4918 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
4919 Op.getOperand(2), Op.getOperand(3), Glue);
4921 case Intrinsic::amdgcn_interp_p1: {
4922 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4923 SDValue Glue = M0.getValue(1);
4924 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
4925 Op.getOperand(2), Op.getOperand(3), Glue);
4927 case Intrinsic::amdgcn_interp_p2: {
4928 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
4929 SDValue Glue = SDValue(M0.getNode(), 1);
4930 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
4931 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
4934 case Intrinsic::amdgcn_sin:
4935 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
4937 case Intrinsic::amdgcn_cos:
4938 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
4940 case Intrinsic::amdgcn_log_clamp: {
4941 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
4944 DiagnosticInfoUnsupported BadIntrin(
4945 MF.getFunction(), "intrinsic not supported on subtarget",
4947 DAG.getContext()->diagnose(BadIntrin);
4948 return DAG.getUNDEF(VT);
4950 case Intrinsic::amdgcn_ldexp:
4951 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
4952 Op.getOperand(1), Op.getOperand(2));
4954 case Intrinsic::amdgcn_fract:
4955 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
4957 case Intrinsic::amdgcn_class:
4958 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
4959 Op.getOperand(1), Op.getOperand(2));
4960 case Intrinsic::amdgcn_div_fmas:
4961 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
4962 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
4965 case Intrinsic::amdgcn_div_fixup:
4966 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
4967 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4969 case Intrinsic::amdgcn_trig_preop:
4970 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
4971 Op.getOperand(1), Op.getOperand(2));
4972 case Intrinsic::amdgcn_div_scale: {
4973 // 3rd parameter required to be a constant.
4974 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4976 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
4978 // Translate to the operands expected by the machine instruction. The
4979 // first parameter must be the same as the first instruction.
4980 SDValue Numerator = Op.getOperand(1);
4981 SDValue Denominator = Op.getOperand(2);
4983 // Note this order is opposite of the machine instruction's operations,
4984 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
4985 // intrinsic has the numerator as the first operand to match a normal
4986 // division operation.
4988 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
4990 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
4991 Denominator, Numerator);
4993 case Intrinsic::amdgcn_icmp: {
4994 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4996 return DAG.getUNDEF(VT);
4998 int CondCode = CD->getSExtValue();
4999 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
5000 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
5001 return DAG.getUNDEF(VT);
5003 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
5004 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
5005 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
5006 Op.getOperand(2), DAG.getCondCode(CCOpcode));
5008 case Intrinsic::amdgcn_fcmp: {
5009 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
5011 return DAG.getUNDEF(VT);
5013 int CondCode = CD->getSExtValue();
5014 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
5015 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
5016 return DAG.getUNDEF(VT);
5018 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
5019 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
5020 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
5021 Op.getOperand(2), DAG.getCondCode(CCOpcode));
5023 case Intrinsic::amdgcn_fmed3:
5024 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
5025 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5026 case Intrinsic::amdgcn_fdot2:
5027 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
5028 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5030 case Intrinsic::amdgcn_fmul_legacy:
5031 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
5032 Op.getOperand(1), Op.getOperand(2));
5033 case Intrinsic::amdgcn_sffbh:
5034 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
5035 case Intrinsic::amdgcn_sbfe:
5036 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
5037 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5038 case Intrinsic::amdgcn_ubfe:
5039 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
5040 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5041 case Intrinsic::amdgcn_cvt_pkrtz:
5042 case Intrinsic::amdgcn_cvt_pknorm_i16:
5043 case Intrinsic::amdgcn_cvt_pknorm_u16:
5044 case Intrinsic::amdgcn_cvt_pk_i16:
5045 case Intrinsic::amdgcn_cvt_pk_u16: {
5046 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
5047 EVT VT = Op.getValueType();
5050 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
5051 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
5052 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
5053 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5054 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
5055 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5056 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
5057 Opcode = AMDGPUISD::CVT_PK_I16_I32;
5059 Opcode = AMDGPUISD::CVT_PK_U16_U32;
5061 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
5062 Op.getOperand(1), Op.getOperand(2));
5063 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
5065 case Intrinsic::amdgcn_wqm: {
5066 SDValue Src = Op.getOperand(1);
5067 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
5070 case Intrinsic::amdgcn_wwm: {
5071 SDValue Src = Op.getOperand(1);
5072 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
5075 case Intrinsic::amdgcn_fmad_ftz:
5076 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
5077 Op.getOperand(2), Op.getOperand(3));
5079 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5080 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5081 return lowerImage(Op, ImageDimIntr, DAG);
5087 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
5088 SelectionDAG &DAG) const {
5089 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5093 case Intrinsic::amdgcn_atomic_inc:
5094 case Intrinsic::amdgcn_atomic_dec:
5095 case Intrinsic::amdgcn_ds_fadd:
5096 case Intrinsic::amdgcn_ds_fmin:
5097 case Intrinsic::amdgcn_ds_fmax: {
5098 MemSDNode *M = cast<MemSDNode>(Op);
5101 case Intrinsic::amdgcn_atomic_inc:
5102 Opc = AMDGPUISD::ATOMIC_INC;
5104 case Intrinsic::amdgcn_atomic_dec:
5105 Opc = AMDGPUISD::ATOMIC_DEC;
5107 case Intrinsic::amdgcn_ds_fadd:
5108 Opc = AMDGPUISD::ATOMIC_LOAD_FADD;
5110 case Intrinsic::amdgcn_ds_fmin:
5111 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
5113 case Intrinsic::amdgcn_ds_fmax:
5114 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
5117 llvm_unreachable("Unknown intrinsic!");
5120 M->getOperand(0), // Chain
5121 M->getOperand(2), // Ptr
5122 M->getOperand(3) // Value
5125 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
5126 M->getMemoryVT(), M->getMemOperand());
5128 case Intrinsic::amdgcn_buffer_load:
5129 case Intrinsic::amdgcn_buffer_load_format: {
5131 Op.getOperand(0), // Chain
5132 Op.getOperand(2), // rsrc
5133 Op.getOperand(3), // vindex
5134 Op.getOperand(4), // offset
5135 Op.getOperand(5), // glc
5136 Op.getOperand(6) // slc
5139 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
5140 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5141 EVT VT = Op.getValueType();
5142 EVT IntVT = VT.changeTypeToInteger();
5143 auto *M = cast<MemSDNode>(Op);
5144 EVT LoadVT = Op.getValueType();
5145 bool IsD16 = LoadVT.getScalarType() == MVT::f16;
5147 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG);
5149 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5150 M->getMemOperand());
5152 case Intrinsic::amdgcn_tbuffer_load: {
5153 MemSDNode *M = cast<MemSDNode>(Op);
5154 EVT LoadVT = Op.getValueType();
5155 bool IsD16 = LoadVT.getScalarType() == MVT::f16;
5157 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, M, DAG);
5161 Op.getOperand(0), // Chain
5162 Op.getOperand(2), // rsrc
5163 Op.getOperand(3), // vindex
5164 Op.getOperand(4), // voffset
5165 Op.getOperand(5), // soffset
5166 Op.getOperand(6), // offset
5167 Op.getOperand(7), // dfmt
5168 Op.getOperand(8), // nfmt
5169 Op.getOperand(9), // glc
5170 Op.getOperand(10) // slc
5173 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5174 Op->getVTList(), Ops, LoadVT,
5175 M->getMemOperand());
5177 case Intrinsic::amdgcn_buffer_atomic_swap:
5178 case Intrinsic::amdgcn_buffer_atomic_add:
5179 case Intrinsic::amdgcn_buffer_atomic_sub:
5180 case Intrinsic::amdgcn_buffer_atomic_smin:
5181 case Intrinsic::amdgcn_buffer_atomic_umin:
5182 case Intrinsic::amdgcn_buffer_atomic_smax:
5183 case Intrinsic::amdgcn_buffer_atomic_umax:
5184 case Intrinsic::amdgcn_buffer_atomic_and:
5185 case Intrinsic::amdgcn_buffer_atomic_or:
5186 case Intrinsic::amdgcn_buffer_atomic_xor: {
5188 Op.getOperand(0), // Chain
5189 Op.getOperand(2), // vdata
5190 Op.getOperand(3), // rsrc
5191 Op.getOperand(4), // vindex
5192 Op.getOperand(5), // offset
5193 Op.getOperand(6) // slc
5195 EVT VT = Op.getValueType();
5197 auto *M = cast<MemSDNode>(Op);
5198 unsigned Opcode = 0;
5201 case Intrinsic::amdgcn_buffer_atomic_swap:
5202 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
5204 case Intrinsic::amdgcn_buffer_atomic_add:
5205 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
5207 case Intrinsic::amdgcn_buffer_atomic_sub:
5208 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
5210 case Intrinsic::amdgcn_buffer_atomic_smin:
5211 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
5213 case Intrinsic::amdgcn_buffer_atomic_umin:
5214 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
5216 case Intrinsic::amdgcn_buffer_atomic_smax:
5217 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
5219 case Intrinsic::amdgcn_buffer_atomic_umax:
5220 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
5222 case Intrinsic::amdgcn_buffer_atomic_and:
5223 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
5225 case Intrinsic::amdgcn_buffer_atomic_or:
5226 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5228 case Intrinsic::amdgcn_buffer_atomic_xor:
5229 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5232 llvm_unreachable("unhandled atomic opcode");
5235 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5236 M->getMemOperand());
5239 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
5241 Op.getOperand(0), // Chain
5242 Op.getOperand(2), // src
5243 Op.getOperand(3), // cmp
5244 Op.getOperand(4), // rsrc
5245 Op.getOperand(5), // vindex
5246 Op.getOperand(6), // offset
5247 Op.getOperand(7) // slc
5249 EVT VT = Op.getValueType();
5250 auto *M = cast<MemSDNode>(Op);
5252 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
5253 Op->getVTList(), Ops, VT, M->getMemOperand());
5257 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5258 AMDGPU::getImageDimIntrinsicInfo(IntrID))
5259 return lowerImage(Op, ImageDimIntr, DAG);
5265 SDValue SITargetLowering::handleD16VData(SDValue VData,
5266 SelectionDAG &DAG) const {
5267 EVT StoreVT = VData.getValueType();
5269 // No change for f16 and legal vector D16 types.
5270 if (!StoreVT.isVector())
5274 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
5276 if (Subtarget->hasUnpackedD16VMem()) {
5277 // We need to unpack the packed data to store.
5278 EVT IntStoreVT = StoreVT.changeTypeToInteger();
5279 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
5281 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
5282 StoreVT.getVectorNumElements());
5283 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
5284 return DAG.UnrollVectorOp(ZExt.getNode());
5287 assert(isTypeLegal(StoreVT));
5291 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5292 SelectionDAG &DAG) const {
5294 SDValue Chain = Op.getOperand(0);
5295 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5296 MachineFunction &MF = DAG.getMachineFunction();
5298 switch (IntrinsicID) {
5299 case Intrinsic::amdgcn_exp: {
5300 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5301 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5302 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
5303 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
5305 const SDValue Ops[] = {
5307 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5308 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
5309 Op.getOperand(4), // src0
5310 Op.getOperand(5), // src1
5311 Op.getOperand(6), // src2
5312 Op.getOperand(7), // src3
5313 DAG.getTargetConstant(0, DL, MVT::i1), // compr
5314 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5317 unsigned Opc = Done->isNullValue() ?
5318 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5319 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5321 case Intrinsic::amdgcn_exp_compr: {
5322 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5323 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5324 SDValue Src0 = Op.getOperand(4);
5325 SDValue Src1 = Op.getOperand(5);
5326 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
5327 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
5329 SDValue Undef = DAG.getUNDEF(MVT::f32);
5330 const SDValue Ops[] = {
5332 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5333 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
5334 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
5335 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
5338 DAG.getTargetConstant(1, DL, MVT::i1), // compr
5339 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5342 unsigned Opc = Done->isNullValue() ?
5343 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5344 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5346 case Intrinsic::amdgcn_s_sendmsg:
5347 case Intrinsic::amdgcn_s_sendmsghalt: {
5348 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
5349 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
5350 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
5351 SDValue Glue = Chain.getValue(1);
5352 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
5353 Op.getOperand(2), Glue);
5355 case Intrinsic::amdgcn_init_exec: {
5356 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
5359 case Intrinsic::amdgcn_init_exec_from_input: {
5360 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
5361 Op.getOperand(2), Op.getOperand(3));
5363 case AMDGPUIntrinsic::AMDGPU_kill: {
5364 SDValue Src = Op.getOperand(2);
5365 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
5366 if (!K->isNegative())
5369 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
5370 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
5373 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
5374 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
5376 case Intrinsic::amdgcn_s_barrier: {
5377 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
5378 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5379 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
5380 if (WGSize <= ST.getWavefrontSize())
5381 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
5382 Op.getOperand(0)), 0);
5386 case AMDGPUIntrinsic::SI_tbuffer_store: {
5388 // Extract vindex and voffset from vaddr as appropriate
5389 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10));
5390 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11));
5391 SDValue VAddr = Op.getOperand(5);
5393 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
5395 assert(!(OffEn->isOne() && IdxEn->isOne()) &&
5396 "Legacy intrinsic doesn't support both offset and index - use new version");
5398 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero;
5399 SDValue VOffset = OffEn->isOne() ? VAddr : Zero;
5401 // Deal with the vec-3 case
5402 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4));
5403 auto Opcode = NumChannels->getZExtValue() == 3 ?
5404 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT;
5408 Op.getOperand(3), // vdata
5409 Op.getOperand(2), // rsrc
5412 Op.getOperand(6), // soffset
5413 Op.getOperand(7), // inst_offset
5414 Op.getOperand(8), // dfmt
5415 Op.getOperand(9), // nfmt
5416 Op.getOperand(12), // glc
5417 Op.getOperand(13), // slc
5420 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 &&
5421 "Value of tfe other than zero is unsupported");
5423 EVT VT = Op.getOperand(3).getValueType();
5424 MachineMemOperand *MMO = MF.getMachineMemOperand(
5425 MachinePointerInfo(),
5426 MachineMemOperand::MOStore,
5427 VT.getStoreSize(), 4);
5428 return DAG.getMemIntrinsicNode(Opcode, DL,
5429 Op->getVTList(), Ops, VT, MMO);
5432 case Intrinsic::amdgcn_tbuffer_store: {
5433 SDValue VData = Op.getOperand(2);
5434 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5436 VData = handleD16VData(VData, DAG);
5440 Op.getOperand(3), // rsrc
5441 Op.getOperand(4), // vindex
5442 Op.getOperand(5), // voffset
5443 Op.getOperand(6), // soffset
5444 Op.getOperand(7), // offset
5445 Op.getOperand(8), // dfmt
5446 Op.getOperand(9), // nfmt
5447 Op.getOperand(10), // glc
5448 Op.getOperand(11) // slc
5450 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
5451 AMDGPUISD::TBUFFER_STORE_FORMAT;
5452 MemSDNode *M = cast<MemSDNode>(Op);
5453 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5454 M->getMemoryVT(), M->getMemOperand());
5457 case Intrinsic::amdgcn_buffer_store:
5458 case Intrinsic::amdgcn_buffer_store_format: {
5459 SDValue VData = Op.getOperand(2);
5460 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5462 VData = handleD16VData(VData, DAG);
5466 Op.getOperand(3), // rsrc
5467 Op.getOperand(4), // vindex
5468 Op.getOperand(5), // offset
5469 Op.getOperand(6), // glc
5470 Op.getOperand(7) // slc
5472 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
5473 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
5474 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
5475 MemSDNode *M = cast<MemSDNode>(Op);
5476 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5477 M->getMemoryVT(), M->getMemOperand());
5480 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5481 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5482 return lowerImage(Op, ImageDimIntr, DAG);
5489 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
5490 ISD::LoadExtType ExtType, SDValue Op,
5491 const SDLoc &SL, EVT VT) {
5492 if (VT.bitsLT(Op.getValueType()))
5493 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
5497 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
5499 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
5501 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
5502 case ISD::NON_EXTLOAD:
5506 llvm_unreachable("invalid ext type");
5509 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
5510 SelectionDAG &DAG = DCI.DAG;
5511 if (Ld->getAlignment() < 4 || Ld->isDivergent())
5514 // FIXME: Constant loads should all be marked invariant.
5515 unsigned AS = Ld->getAddressSpace();
5516 if (AS != AMDGPUASI.CONSTANT_ADDRESS &&
5517 AS != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
5518 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
5521 // Don't do this early, since it may interfere with adjacent load merging for
5522 // illegal types. We can avoid losing alignment information for exotic types
5524 EVT MemVT = Ld->getMemoryVT();
5525 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
5526 MemVT.getSizeInBits() >= 32)
5531 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
5532 "unexpected vector extload");
5534 // TODO: Drop only high part of range.
5535 SDValue Ptr = Ld->getBasePtr();
5536 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
5537 MVT::i32, SL, Ld->getChain(), Ptr,
5539 Ld->getPointerInfo(), MVT::i32,
5541 Ld->getMemOperand()->getFlags(),
5543 nullptr); // Drop ranges
5545 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
5546 if (MemVT.isFloatingPoint()) {
5547 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
5548 "unexpected fp extload");
5549 TruncVT = MemVT.changeTypeToInteger();
5552 SDValue Cvt = NewLoad;
5553 if (Ld->getExtensionType() == ISD::SEXTLOAD) {
5554 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
5555 DAG.getValueType(TruncVT));
5556 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
5557 Ld->getExtensionType() == ISD::NON_EXTLOAD) {
5558 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
5560 assert(Ld->getExtensionType() == ISD::EXTLOAD);
5563 EVT VT = Ld->getValueType(0);
5564 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
5566 DCI.AddToWorklist(Cvt.getNode());
5568 // We may need to handle exotic cases, such as i16->i64 extloads, so insert
5569 // the appropriate extension from the 32-bit load.
5570 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
5571 DCI.AddToWorklist(Cvt.getNode());
5573 // Handle conversion back to floating point if necessary.
5574 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
5576 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
5579 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5581 LoadSDNode *Load = cast<LoadSDNode>(Op);
5582 ISD::LoadExtType ExtType = Load->getExtensionType();
5583 EVT MemVT = Load->getMemoryVT();
5585 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
5586 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
5589 // FIXME: Copied from PPC
5590 // First, load into 32 bits, then truncate to 1 bit.
5592 SDValue Chain = Load->getChain();
5593 SDValue BasePtr = Load->getBasePtr();
5594 MachineMemOperand *MMO = Load->getMemOperand();
5596 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
5598 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
5599 BasePtr, RealMemVT, MMO);
5602 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
5606 return DAG.getMergeValues(Ops, DL);
5609 if (!MemVT.isVector())
5612 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
5613 "Custom lowering for non-i32 vectors hasn't been implemented.");
5615 unsigned Alignment = Load->getAlignment();
5616 unsigned AS = Load->getAddressSpace();
5617 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
5620 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
5621 return DAG.getMergeValues(Ops, DL);
5624 MachineFunction &MF = DAG.getMachineFunction();
5625 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5626 // If there is a possibilty that flat instruction access scratch memory
5627 // then we need to use the same legalization rules we use for private.
5628 if (AS == AMDGPUASI.FLAT_ADDRESS)
5629 AS = MFI->hasFlatScratchInit() ?
5630 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5632 unsigned NumElements = MemVT.getVectorNumElements();
5634 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5635 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
5636 if (!Op->isDivergent() && Alignment >= 4)
5638 // Non-uniform loads will be selected to MUBUF instructions, so they
5639 // have the same legalization requirements as global and private
5644 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5645 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5646 AS == AMDGPUASI.GLOBAL_ADDRESS) {
5647 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
5648 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
5651 // Non-uniform loads will be selected to MUBUF instructions, so they
5652 // have the same legalization requirements as global and private
5656 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5657 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5658 AS == AMDGPUASI.GLOBAL_ADDRESS ||
5659 AS == AMDGPUASI.FLAT_ADDRESS) {
5660 if (NumElements > 4)
5661 return SplitVectorLoad(Op, DAG);
5662 // v4 loads are supported for private and global memory.
5665 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5666 // Depending on the setting of the private_element_size field in the
5667 // resource descriptor, we can only make private accesses up to a certain
5669 switch (Subtarget->getMaxPrivateElementSize()) {
5671 return scalarizeVectorLoad(Load, DAG);
5673 if (NumElements > 2)
5674 return SplitVectorLoad(Op, DAG);
5677 // Same as global/flat
5678 if (NumElements > 4)
5679 return SplitVectorLoad(Op, DAG);
5682 llvm_unreachable("unsupported private_element_size");
5684 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5685 // Use ds_read_b128 if possible.
5686 if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
5687 MemVT.getStoreSize() == 16)
5690 if (NumElements > 2)
5691 return SplitVectorLoad(Op, DAG);
5696 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5697 EVT VT = Op.getValueType();
5698 assert(VT.getSizeInBits() == 64);
5701 SDValue Cond = Op.getOperand(0);
5703 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
5704 SDValue One = DAG.getConstant(1, DL, MVT::i32);
5706 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
5707 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
5709 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
5710 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
5712 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
5714 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
5715 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
5717 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
5719 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
5720 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
5723 // Catch division cases where we can use shortcuts with rcp and rsq
5725 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
5726 SelectionDAG &DAG) const {
5728 SDValue LHS = Op.getOperand(0);
5729 SDValue RHS = Op.getOperand(1);
5730 EVT VT = Op.getValueType();
5731 const SDNodeFlags Flags = Op->getFlags();
5732 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
5734 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
5737 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
5738 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
5739 if (CLHS->isExactlyValue(1.0)) {
5740 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
5741 // the CI documentation has a worst case error of 1 ulp.
5742 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
5743 // use it as long as we aren't trying to use denormals.
5745 // v_rcp_f16 and v_rsq_f16 DO support denormals.
5747 // 1.0 / sqrt(x) -> rsq(x)
5749 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
5750 // error seems really high at 2^29 ULP.
5751 if (RHS.getOpcode() == ISD::FSQRT)
5752 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
5754 // 1.0 / x -> rcp(x)
5755 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5758 // Same as for 1.0, but expand the sign out of the constant.
5759 if (CLHS->isExactlyValue(-1.0)) {
5760 // -1.0 / x -> rcp (fneg x)
5761 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
5762 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
5768 // Turn into multiply by the reciprocal.
5769 // x / y -> x * (1.0 / y)
5770 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5771 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
5777 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5778 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
5779 if (GlueChain->getNumValues() <= 1) {
5780 return DAG.getNode(Opcode, SL, VT, A, B);
5783 assert(GlueChain->getNumValues() == 3);
5785 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5787 default: llvm_unreachable("no chain equivalent for opcode");
5789 Opcode = AMDGPUISD::FMUL_W_CHAIN;
5793 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
5794 GlueChain.getValue(2));
5797 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5798 EVT VT, SDValue A, SDValue B, SDValue C,
5799 SDValue GlueChain) {
5800 if (GlueChain->getNumValues() <= 1) {
5801 return DAG.getNode(Opcode, SL, VT, A, B, C);
5804 assert(GlueChain->getNumValues() == 3);
5806 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5808 default: llvm_unreachable("no chain equivalent for opcode");
5810 Opcode = AMDGPUISD::FMA_W_CHAIN;
5814 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
5815 GlueChain.getValue(2));
5818 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
5819 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5823 SDValue Src0 = Op.getOperand(0);
5824 SDValue Src1 = Op.getOperand(1);
5826 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5827 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5829 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
5830 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
5832 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
5833 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
5835 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
5838 // Faster 2.5 ULP division that does not support denormals.
5839 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
5841 SDValue LHS = Op.getOperand(1);
5842 SDValue RHS = Op.getOperand(2);
5844 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
5846 const APFloat K0Val(BitsToFloat(0x6f800000));
5847 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
5849 const APFloat K1Val(BitsToFloat(0x2f800000));
5850 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
5852 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5855 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
5857 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
5859 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
5861 // TODO: Should this propagate fast-math-flags?
5862 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
5864 // rcp does not support denormals.
5865 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
5867 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
5869 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
5872 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
5873 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5877 SDValue LHS = Op.getOperand(0);
5878 SDValue RHS = Op.getOperand(1);
5880 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5882 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
5884 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5886 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5889 // Denominator is scaled to not be denormal, so using rcp is ok.
5890 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
5892 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
5895 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
5896 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
5897 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
5899 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
5901 if (!Subtarget->hasFP32Denormals()) {
5902 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
5903 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
5905 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
5907 EnableDenormValue, BitField);
5910 EnableDenorm.getValue(0),
5911 EnableDenorm.getValue(1)
5914 NegDivScale0 = DAG.getMergeValues(Ops, SL);
5917 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
5918 ApproxRcp, One, NegDivScale0);
5920 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
5923 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
5926 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
5927 NumeratorScaled, Mul);
5929 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
5931 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
5932 NumeratorScaled, Fma3);
5934 if (!Subtarget->hasFP32Denormals()) {
5935 const SDValue DisableDenormValue =
5936 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
5937 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
5943 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
5944 DisableDenorm, DAG.getRoot());
5945 DAG.setRoot(OutputChain);
5948 SDValue Scale = NumeratorScaled.getValue(1);
5949 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
5950 Fma4, Fma1, Fma3, Scale);
5952 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
5955 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
5956 if (DAG.getTarget().Options.UnsafeFPMath)
5957 return lowerFastUnsafeFDIV(Op, DAG);
5960 SDValue X = Op.getOperand(0);
5961 SDValue Y = Op.getOperand(1);
5963 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
5965 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
5967 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
5969 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
5971 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
5973 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
5975 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
5977 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
5979 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
5981 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
5982 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
5984 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
5985 NegDivScale0, Mul, DivScale1);
5989 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
5990 // Workaround a hardware bug on SI where the condition output from div_scale
5993 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
5995 // Figure out if the scale to use for div_fmas.
5996 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
5997 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
5998 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
5999 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
6001 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
6002 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
6005 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
6007 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
6009 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
6010 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
6011 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
6013 Scale = DivScale1.getValue(1);
6016 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
6017 Fma4, Fma3, Mul, Scale);
6019 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
6022 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
6023 EVT VT = Op.getValueType();
6026 return LowerFDIV32(Op, DAG);
6029 return LowerFDIV64(Op, DAG);
6032 return LowerFDIV16(Op, DAG);
6034 llvm_unreachable("Unexpected type for fdiv");
6037 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6039 StoreSDNode *Store = cast<StoreSDNode>(Op);
6040 EVT VT = Store->getMemoryVT();
6042 if (VT == MVT::i1) {
6043 return DAG.getTruncStore(Store->getChain(), DL,
6044 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
6045 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
6048 assert(VT.isVector() &&
6049 Store->getValue().getValueType().getScalarType() == MVT::i32);
6051 unsigned AS = Store->getAddressSpace();
6052 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
6053 AS, Store->getAlignment())) {
6054 return expandUnalignedStore(Store, DAG);
6057 MachineFunction &MF = DAG.getMachineFunction();
6058 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
6059 // If there is a possibilty that flat instruction access scratch memory
6060 // then we need to use the same legalization rules we use for private.
6061 if (AS == AMDGPUASI.FLAT_ADDRESS)
6062 AS = MFI->hasFlatScratchInit() ?
6063 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
6065 unsigned NumElements = VT.getVectorNumElements();
6066 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
6067 AS == AMDGPUASI.FLAT_ADDRESS) {
6068 if (NumElements > 4)
6069 return SplitVectorStore(Op, DAG);
6071 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
6072 switch (Subtarget->getMaxPrivateElementSize()) {
6074 return scalarizeVectorStore(Store, DAG);
6076 if (NumElements > 2)
6077 return SplitVectorStore(Op, DAG);
6080 if (NumElements > 4)
6081 return SplitVectorStore(Op, DAG);
6084 llvm_unreachable("unsupported private_element_size");
6086 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
6087 // Use ds_write_b128 if possible.
6088 if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
6089 VT.getStoreSize() == 16)
6092 if (NumElements > 2)
6093 return SplitVectorStore(Op, DAG);
6096 llvm_unreachable("unhandled address space");
6100 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
6102 EVT VT = Op.getValueType();
6103 SDValue Arg = Op.getOperand(0);
6104 // TODO: Should this propagate fast-math-flags?
6105 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
6106 DAG.getNode(ISD::FMUL, DL, VT, Arg,
6107 DAG.getConstantFP(0.5/M_PI, DL,
6110 switch (Op.getOpcode()) {
6112 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
6114 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
6116 llvm_unreachable("Wrong trig opcode");
6120 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
6121 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
6122 assert(AtomicNode->isCompareAndSwap());
6123 unsigned AS = AtomicNode->getAddressSpace();
6125 // No custom lowering required for local address space
6126 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
6129 // Non-local address space requires custom lowering for atomic compare
6130 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
6132 SDValue ChainIn = Op.getOperand(0);
6133 SDValue Addr = Op.getOperand(1);
6134 SDValue Old = Op.getOperand(2);
6135 SDValue New = Op.getOperand(3);
6136 EVT VT = Op.getValueType();
6137 MVT SimpleVT = VT.getSimpleVT();
6138 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
6140 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
6141 SDValue Ops[] = { ChainIn, Addr, NewOld };
6143 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
6144 Ops, VT, AtomicNode->getMemOperand());
6147 //===----------------------------------------------------------------------===//
6148 // Custom DAG optimizations
6149 //===----------------------------------------------------------------------===//
6151 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
6152 DAGCombinerInfo &DCI) const {
6153 EVT VT = N->getValueType(0);
6154 EVT ScalarVT = VT.getScalarType();
6155 if (ScalarVT != MVT::f32)
6158 SelectionDAG &DAG = DCI.DAG;
6161 SDValue Src = N->getOperand(0);
6162 EVT SrcVT = Src.getValueType();
6164 // TODO: We could try to match extracting the higher bytes, which would be
6165 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
6166 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
6167 // about in practice.
6168 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
6169 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
6170 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
6171 DCI.AddToWorklist(Cvt.getNode());
6179 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
6181 // This is a variant of
6182 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
6184 // The normal DAG combiner will do this, but only if the add has one use since
6185 // that would increase the number of instructions.
6187 // This prevents us from seeing a constant offset that can be folded into a
6188 // memory instruction's addressing mode. If we know the resulting add offset of
6189 // a pointer can be folded into an addressing offset, we can replace the pointer
6190 // operand with the add of new constant offset. This eliminates one of the uses,
6191 // and may allow the remaining use to also be simplified.
6193 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
6196 DAGCombinerInfo &DCI) const {
6197 SDValue N0 = N->getOperand(0);
6198 SDValue N1 = N->getOperand(1);
6200 // We only do this to handle cases where it's profitable when there are
6201 // multiple uses of the add, so defer to the standard combine.
6202 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
6206 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
6210 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6214 // If the resulting offset is too large, we can't fold it into the addressing
6216 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
6217 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
6220 AM.HasBaseReg = true;
6221 AM.BaseOffs = Offset.getSExtValue();
6222 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
6225 SelectionDAG &DAG = DCI.DAG;
6227 EVT VT = N->getValueType(0);
6229 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
6230 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
6233 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
6234 (N0.getOpcode() == ISD::OR ||
6235 N0->getFlags().hasNoUnsignedWrap()));
6237 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
6240 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
6241 DAGCombinerInfo &DCI) const {
6242 SDValue Ptr = N->getBasePtr();
6243 SelectionDAG &DAG = DCI.DAG;
6246 // TODO: We could also do this for multiplies.
6247 if (Ptr.getOpcode() == ISD::SHL) {
6248 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
6249 N->getMemoryVT(), DCI);
6251 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
6253 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
6254 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
6261 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
6262 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
6263 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
6264 (Opc == ISD::XOR && Val == 0);
6267 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
6268 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
6269 // integer combine opportunities since most 64-bit operations are decomposed
6270 // this way. TODO: We won't want this for SALU especially if it is an inline
6272 SDValue SITargetLowering::splitBinaryBitConstantOp(
6273 DAGCombinerInfo &DCI,
6275 unsigned Opc, SDValue LHS,
6276 const ConstantSDNode *CRHS) const {
6277 uint64_t Val = CRHS->getZExtValue();
6278 uint32_t ValLo = Lo_32(Val);
6279 uint32_t ValHi = Hi_32(Val);
6280 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6282 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
6283 bitOpWithConstantIsReducible(Opc, ValHi)) ||
6284 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
6285 // If we need to materialize a 64-bit immediate, it will be split up later
6286 // anyway. Avoid creating the harder to understand 64-bit immediate
6288 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
6294 // Returns true if argument is a boolean value which is not serialized into
6295 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
6296 static bool isBoolSGPR(SDValue V) {
6297 if (V.getValueType() != MVT::i1)
6299 switch (V.getOpcode()) {
6305 case AMDGPUISD::FP_CLASS:
6311 // If a constant has all zeroes or all ones within each byte return it.
6312 // Otherwise return 0.
6313 static uint32_t getConstantPermuteMask(uint32_t C) {
6314 // 0xff for any zero byte in the mask
6315 uint32_t ZeroByteMask = 0;
6316 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
6317 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
6318 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
6319 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
6320 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
6321 if ((NonZeroByteMask & C) != NonZeroByteMask)
6322 return 0; // Partial bytes selected.
6326 // Check if a node selects whole bytes from its operand 0 starting at a byte
6327 // boundary while masking the rest. Returns select mask as in the v_perm_b32
6328 // or -1 if not succeeded.
6329 // Note byte select encoding:
6330 // value 0-3 selects corresponding source byte;
6331 // value 0xc selects zero;
6332 // value 0xff selects 0xff.
6333 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
6334 assert(V.getValueSizeInBits() == 32);
6336 if (V.getNumOperands() != 2)
6339 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
6343 uint32_t C = N1->getZExtValue();
6345 switch (V.getOpcode()) {
6349 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
6350 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
6355 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
6356 return (0x03020100 & ~ConstMask) | ConstMask;
6364 return uint32_t((0x030201000c0c0c0cull << C) >> 32);
6370 return uint32_t(0x0c0c0c0c03020100ull >> C);
6376 SDValue SITargetLowering::performAndCombine(SDNode *N,
6377 DAGCombinerInfo &DCI) const {
6378 if (DCI.isBeforeLegalize())
6381 SelectionDAG &DAG = DCI.DAG;
6382 EVT VT = N->getValueType(0);
6383 SDValue LHS = N->getOperand(0);
6384 SDValue RHS = N->getOperand(1);
6387 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6388 if (VT == MVT::i64 && CRHS) {
6390 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
6394 if (CRHS && VT == MVT::i32) {
6395 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
6396 // nb = number of trailing zeroes in mask
6397 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
6398 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
6399 uint64_t Mask = CRHS->getZExtValue();
6400 unsigned Bits = countPopulation(Mask);
6401 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
6402 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
6403 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
6404 unsigned Shift = CShift->getZExtValue();
6405 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
6406 unsigned Offset = NB + Shift;
6407 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
6409 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
6411 DAG.getConstant(Offset, SL, MVT::i32),
6412 DAG.getConstant(Bits, SL, MVT::i32));
6413 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6414 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
6415 DAG.getValueType(NarrowVT));
6416 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
6417 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
6423 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
6424 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
6425 isa<ConstantSDNode>(LHS.getOperand(2))) {
6426 uint32_t Sel = getConstantPermuteMask(Mask);
6430 // Select 0xc for all zero bytes
6431 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
6433 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
6434 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
6438 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
6439 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
6440 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
6441 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6442 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
6444 SDValue X = LHS.getOperand(0);
6445 SDValue Y = RHS.getOperand(0);
6446 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
6449 if (LCC == ISD::SETO) {
6450 if (X != LHS.getOperand(1))
6453 if (RCC == ISD::SETUNE) {
6454 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
6455 if (!C1 || !C1->isInfinity() || C1->isNegative())
6458 const uint32_t Mask = SIInstrFlags::N_NORMAL |
6459 SIInstrFlags::N_SUBNORMAL |
6460 SIInstrFlags::N_ZERO |
6461 SIInstrFlags::P_ZERO |
6462 SIInstrFlags::P_SUBNORMAL |
6463 SIInstrFlags::P_NORMAL;
6465 static_assert(((~(SIInstrFlags::S_NAN |
6466 SIInstrFlags::Q_NAN |
6467 SIInstrFlags::N_INFINITY |
6468 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
6472 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6473 X, DAG.getConstant(Mask, DL, MVT::i32));
6478 if (VT == MVT::i32 &&
6479 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
6480 // and x, (sext cc from i1) => select cc, x, 0
6481 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
6482 std::swap(LHS, RHS);
6483 if (isBoolSGPR(RHS.getOperand(0)))
6484 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
6485 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
6488 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
6489 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6490 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
6491 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
6492 uint32_t LHSMask = getPermuteMask(DAG, LHS);
6493 uint32_t RHSMask = getPermuteMask(DAG, RHS);
6494 if (LHSMask != ~0u && RHSMask != ~0u) {
6495 // Canonicalize the expression in an attempt to have fewer unique masks
6496 // and therefore fewer registers used to hold the masks.
6497 if (LHSMask > RHSMask) {
6498 std::swap(LHSMask, RHSMask);
6499 std::swap(LHS, RHS);
6502 // Select 0xc for each lane used from source operand. Zero has 0xc mask
6503 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
6504 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6505 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6507 // Check of we need to combine values from two sources within a byte.
6508 if (!(LHSUsedLanes & RHSUsedLanes) &&
6509 // If we select high and lower word keep it for SDWA.
6510 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
6511 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
6512 // Each byte in each mask is either selector mask 0-3, or has higher
6513 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
6514 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
6515 // mask which is not 0xff wins. By anding both masks we have a correct
6516 // result except that 0x0c shall be corrected to give 0x0c only.
6517 uint32_t Mask = LHSMask & RHSMask;
6518 for (unsigned I = 0; I < 32; I += 8) {
6519 uint32_t ByteSel = 0xff << I;
6520 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
6521 Mask &= (0x0c << I) & 0xffffffff;
6524 // Add 4 to each active LHS lane. It will not affect any existing 0xff
6526 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
6529 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
6530 LHS.getOperand(0), RHS.getOperand(0),
6531 DAG.getConstant(Sel, DL, MVT::i32));
6539 SDValue SITargetLowering::performOrCombine(SDNode *N,
6540 DAGCombinerInfo &DCI) const {
6541 SelectionDAG &DAG = DCI.DAG;
6542 SDValue LHS = N->getOperand(0);
6543 SDValue RHS = N->getOperand(1);
6545 EVT VT = N->getValueType(0);
6546 if (VT == MVT::i1) {
6547 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
6548 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
6549 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
6550 SDValue Src = LHS.getOperand(0);
6551 if (Src != RHS.getOperand(0))
6554 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6555 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6559 // Only 10 bits are used.
6560 static const uint32_t MaxMask = 0x3ff;
6562 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
6564 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6565 Src, DAG.getConstant(NewMask, DL, MVT::i32));
6571 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
6572 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
6573 LHS.getOpcode() == AMDGPUISD::PERM &&
6574 isa<ConstantSDNode>(LHS.getOperand(2))) {
6575 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
6579 Sel |= LHS.getConstantOperandVal(2);
6581 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
6582 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
6585 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
6586 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6587 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
6588 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
6589 uint32_t LHSMask = getPermuteMask(DAG, LHS);
6590 uint32_t RHSMask = getPermuteMask(DAG, RHS);
6591 if (LHSMask != ~0u && RHSMask != ~0u) {
6592 // Canonicalize the expression in an attempt to have fewer unique masks
6593 // and therefore fewer registers used to hold the masks.
6594 if (LHSMask > RHSMask) {
6595 std::swap(LHSMask, RHSMask);
6596 std::swap(LHS, RHS);
6599 // Select 0xc for each lane used from source operand. Zero has 0xc mask
6600 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
6601 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6602 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6604 // Check of we need to combine values from two sources within a byte.
6605 if (!(LHSUsedLanes & RHSUsedLanes) &&
6606 // If we select high and lower word keep it for SDWA.
6607 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
6608 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
6609 // Kill zero bytes selected by other mask. Zero value is 0xc.
6610 LHSMask &= ~RHSUsedLanes;
6611 RHSMask &= ~LHSUsedLanes;
6612 // Add 4 to each active LHS lane
6613 LHSMask |= LHSUsedLanes & 0x04040404;
6615 uint32_t Sel = LHSMask | RHSMask;
6618 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
6619 LHS.getOperand(0), RHS.getOperand(0),
6620 DAG.getConstant(Sel, DL, MVT::i32));
6628 // TODO: This could be a generic combine with a predicate for extracting the
6629 // high half of an integer being free.
6631 // (or i64:x, (zero_extend i32:y)) ->
6632 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
6633 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
6634 RHS.getOpcode() != ISD::ZERO_EXTEND)
6635 std::swap(LHS, RHS);
6637 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
6638 SDValue ExtSrc = RHS.getOperand(0);
6639 EVT SrcVT = ExtSrc.getValueType();
6640 if (SrcVT == MVT::i32) {
6642 SDValue LowLHS, HiBits;
6643 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
6644 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
6646 DCI.AddToWorklist(LowOr.getNode());
6647 DCI.AddToWorklist(HiBits.getNode());
6649 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
6651 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
6655 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
6658 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
6665 SDValue SITargetLowering::performXorCombine(SDNode *N,
6666 DAGCombinerInfo &DCI) const {
6667 EVT VT = N->getValueType(0);
6671 SDValue LHS = N->getOperand(0);
6672 SDValue RHS = N->getOperand(1);
6674 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6677 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
6684 // Instructions that will be lowered with a final instruction that zeros the
6685 // high result bits.
6686 // XXX - probably only need to list legal operations.
6687 static bool fp16SrcZerosHighBits(unsigned Opc) {
6696 case ISD::FCANONICALIZE:
6698 case ISD::UINT_TO_FP:
6699 case ISD::SINT_TO_FP:
6701 // Fabs is lowered to a bit operation, but it's an and which will clear the
6702 // high bits anyway.
6716 case ISD::FNEARBYINT:
6721 case AMDGPUISD::FRACT:
6722 case AMDGPUISD::CLAMP:
6723 case AMDGPUISD::COS_HW:
6724 case AMDGPUISD::SIN_HW:
6725 case AMDGPUISD::FMIN3:
6726 case AMDGPUISD::FMAX3:
6727 case AMDGPUISD::FMED3:
6728 case AMDGPUISD::FMAD_FTZ:
6729 case AMDGPUISD::RCP:
6730 case AMDGPUISD::RSQ:
6731 case AMDGPUISD::RCP_IFLAG:
6732 case AMDGPUISD::LDEXP:
6735 // fcopysign, select and others may be lowered to 32-bit bit operations
6736 // which don't zero the high bits.
6741 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
6742 DAGCombinerInfo &DCI) const {
6743 if (!Subtarget->has16BitInsts() ||
6744 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6747 EVT VT = N->getValueType(0);
6751 SDValue Src = N->getOperand(0);
6752 if (Src.getValueType() != MVT::i16)
6755 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
6756 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
6757 if (Src.getOpcode() == ISD::BITCAST) {
6758 SDValue BCSrc = Src.getOperand(0);
6759 if (BCSrc.getValueType() == MVT::f16 &&
6760 fp16SrcZerosHighBits(BCSrc.getOpcode()))
6761 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
6767 SDValue SITargetLowering::performClassCombine(SDNode *N,
6768 DAGCombinerInfo &DCI) const {
6769 SelectionDAG &DAG = DCI.DAG;
6770 SDValue Mask = N->getOperand(1);
6772 // fp_class x, 0 -> false
6773 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
6774 if (CMask->isNullValue())
6775 return DAG.getConstant(0, SDLoc(N), MVT::i1);
6778 if (N->getOperand(0).isUndef())
6779 return DAG.getUNDEF(MVT::i1);
6784 SDValue SITargetLowering::performRcpCombine(SDNode *N,
6785 DAGCombinerInfo &DCI) const {
6786 EVT VT = N->getValueType(0);
6787 SDValue N0 = N->getOperand(0);
6792 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
6793 N0.getOpcode() == ISD::SINT_TO_FP)) {
6794 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
6798 return AMDGPUTargetLowering::performRcpCombine(N, DCI);
6801 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
6802 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
6805 return DAG.isKnownNeverNaN(Op);
6808 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op,
6809 const GCNSubtarget *ST, unsigned MaxDepth=5) {
6810 // If source is a result of another standard FP operation it is already in
6813 switch (Op.getOpcode()) {
6817 // These will flush denorms if required.
6827 case ISD::FCANONICALIZE:
6831 return Op.getValueType().getScalarType() != MVT::f16 ||
6832 ST->hasFP16Denormals();
6834 case ISD::FP_EXTEND:
6835 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 ||
6836 ST->hasFP16Denormals();
6838 // It can/will be lowered or combined as a bit operation.
6839 // Need to check their input recursively to handle.
6842 return (MaxDepth > 0) &&
6843 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1);
6848 return Op.getValueType().getScalarType() != MVT::f16;
6850 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms.
6851 // For such targets need to check their input recursively.
6857 if (ST->supportsMinMaxDenormModes() &&
6858 DAG.isKnownNeverNaN(Op.getOperand(0)) &&
6859 DAG.isKnownNeverNaN(Op.getOperand(1)))
6862 return (MaxDepth > 0) &&
6863 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) &&
6864 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1);
6866 case ISD::ConstantFP: {
6867 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF();
6868 return !F.isDenormal() && !(F.isNaN() && F.isSignaling());
6874 // Constant fold canonicalize.
6875 SDValue SITargetLowering::performFCanonicalizeCombine(
6877 DAGCombinerInfo &DCI) const {
6878 SelectionDAG &DAG = DCI.DAG;
6879 SDValue N0 = N->getOperand(0);
6881 // fcanonicalize undef -> qnan
6883 EVT VT = N->getValueType(0);
6884 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
6885 return DAG.getConstantFP(QNaN, SDLoc(N), VT);
6888 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0);
6890 SDValue N0 = N->getOperand(0);
6891 EVT VT = N0.getValueType().getScalarType();
6892 auto ST = getSubtarget();
6894 if (((VT == MVT::f32 && ST->hasFP32Denormals()) ||
6895 (VT == MVT::f64 && ST->hasFP64Denormals()) ||
6896 (VT == MVT::f16 && ST->hasFP16Denormals())) &&
6897 DAG.isKnownNeverNaN(N0))
6900 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
6902 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) &&
6903 isCanonicalized(DAG, N0, ST))
6909 const APFloat &C = CFP->getValueAPF();
6911 // Flush denormals to 0 if not enabled.
6912 if (C.isDenormal()) {
6913 EVT VT = N->getValueType(0);
6914 EVT SVT = VT.getScalarType();
6915 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
6916 return DAG.getConstantFP(0.0, SDLoc(N), VT);
6918 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
6919 return DAG.getConstantFP(0.0, SDLoc(N), VT);
6921 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
6922 return DAG.getConstantFP(0.0, SDLoc(N), VT);
6926 EVT VT = N->getValueType(0);
6927 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
6928 if (C.isSignaling()) {
6929 // Quiet a signaling NaN.
6930 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6933 // Make sure it is the canonical NaN bitpattern.
6935 // TODO: Can we use -1 as the canonical NaN value since it's an inline
6937 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
6938 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6944 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
6947 return AMDGPUISD::FMAX3;
6949 return AMDGPUISD::SMAX3;
6951 return AMDGPUISD::UMAX3;
6953 return AMDGPUISD::FMIN3;
6955 return AMDGPUISD::SMIN3;
6957 return AMDGPUISD::UMIN3;
6959 llvm_unreachable("Not a min/max opcode");
6963 SDValue SITargetLowering::performIntMed3ImmCombine(
6964 SelectionDAG &DAG, const SDLoc &SL,
6965 SDValue Op0, SDValue Op1, bool Signed) const {
6966 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
6970 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
6975 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
6978 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
6982 EVT VT = K0->getValueType(0);
6983 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
6984 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
6985 return DAG.getNode(Med3Opc, SL, VT,
6986 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
6989 // If there isn't a 16-bit med3 operation, convert to 32-bit.
6991 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6993 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
6994 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
6995 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
6997 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
6998 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
7001 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
7002 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
7005 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
7006 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
7013 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
7016 SDValue Op1) const {
7017 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
7021 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
7025 // Ordered >= (although NaN inputs should have folded away by now).
7026 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
7027 if (Cmp == APFloat::cmpGreaterThan)
7030 // TODO: Check IEEE bit enabled?
7031 EVT VT = Op0.getValueType();
7032 if (Subtarget->enableDX10Clamp()) {
7033 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
7034 // hardware fmed3 behavior converting to a min.
7035 // FIXME: Should this be allowing -0.0?
7036 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
7037 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
7040 // med3 for f16 is only available on gfx9+, and not available for v2f16.
7041 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
7042 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
7043 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
7044 // then give the other result, which is different from med3 with a NaN
7046 SDValue Var = Op0.getOperand(0);
7047 if (!isKnownNeverSNan(DAG, Var))
7050 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
7051 Var, SDValue(K0, 0), SDValue(K1, 0));
7057 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
7058 DAGCombinerInfo &DCI) const {
7059 SelectionDAG &DAG = DCI.DAG;
7061 EVT VT = N->getValueType(0);
7062 unsigned Opc = N->getOpcode();
7063 SDValue Op0 = N->getOperand(0);
7064 SDValue Op1 = N->getOperand(1);
7066 // Only do this if the inner op has one use since this will just increases
7067 // register pressure for no benefit.
7070 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
7071 !VT.isVector() && VT != MVT::f64 &&
7072 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
7073 // max(max(a, b), c) -> max3(a, b, c)
7074 // min(min(a, b), c) -> min3(a, b, c)
7075 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
7077 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
7086 // max(a, max(b, c)) -> max3(a, b, c)
7087 // min(a, min(b, c)) -> min3(a, b, c)
7088 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
7090 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
7099 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
7100 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
7101 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
7105 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
7106 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
7110 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
7111 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
7112 (Opc == AMDGPUISD::FMIN_LEGACY &&
7113 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
7114 (VT == MVT::f32 || VT == MVT::f64 ||
7115 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
7116 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
7118 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
7125 static bool isClampZeroToOne(SDValue A, SDValue B) {
7126 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
7127 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
7128 // FIXME: Should this be allowing -0.0?
7129 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
7130 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
7137 // FIXME: Should only worry about snans for version with chain.
7138 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
7139 DAGCombinerInfo &DCI) const {
7140 EVT VT = N->getValueType(0);
7141 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
7142 // NaNs. With a NaN input, the order of the operands may change the result.
7144 SelectionDAG &DAG = DCI.DAG;
7147 SDValue Src0 = N->getOperand(0);
7148 SDValue Src1 = N->getOperand(1);
7149 SDValue Src2 = N->getOperand(2);
7151 if (isClampZeroToOne(Src0, Src1)) {
7152 // const_a, const_b, x -> clamp is safe in all cases including signaling
7154 // FIXME: Should this be allowing -0.0?
7155 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
7158 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
7159 // handling no dx10-clamp?
7160 if (Subtarget->enableDX10Clamp()) {
7161 // If NaNs is clamped to 0, we are free to reorder the inputs.
7163 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
7164 std::swap(Src0, Src1);
7166 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
7167 std::swap(Src1, Src2);
7169 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
7170 std::swap(Src0, Src1);
7172 if (isClampZeroToOne(Src1, Src2))
7173 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
7179 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
7180 DAGCombinerInfo &DCI) const {
7181 SDValue Src0 = N->getOperand(0);
7182 SDValue Src1 = N->getOperand(1);
7183 if (Src0.isUndef() && Src1.isUndef())
7184 return DCI.DAG.getUNDEF(N->getValueType(0));
7188 SDValue SITargetLowering::performExtractVectorEltCombine(
7189 SDNode *N, DAGCombinerInfo &DCI) const {
7190 SDValue Vec = N->getOperand(0);
7191 SelectionDAG &DAG = DCI.DAG;
7193 EVT VecVT = Vec.getValueType();
7194 EVT EltVT = VecVT.getVectorElementType();
7196 if ((Vec.getOpcode() == ISD::FNEG ||
7197 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
7199 EVT EltVT = N->getValueType(0);
7200 SDValue Idx = N->getOperand(1);
7201 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7202 Vec.getOperand(0), Idx);
7203 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
7206 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
7208 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
7209 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
7210 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
7211 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
7213 EVT EltVT = N->getValueType(0);
7214 SDValue Idx = N->getOperand(1);
7215 unsigned Opc = Vec.getOpcode();
7220 // TODO: Support other binary operations.
7229 return DAG.getNode(Opc, SL, EltVT,
7230 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7231 Vec.getOperand(0), Idx),
7232 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7233 Vec.getOperand(1), Idx));
7237 if (!DCI.isBeforeLegalize())
7240 unsigned VecSize = VecVT.getSizeInBits();
7241 unsigned EltSize = EltVT.getSizeInBits();
7243 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
7244 // elements. This exposes more load reduction opportunities by replacing
7245 // multiple small extract_vector_elements with a single 32-bit extract.
7246 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
7247 if (EltSize <= 16 &&
7248 EltVT.isByteSized() &&
7250 VecSize % 32 == 0 &&
7252 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
7254 unsigned BitIndex = Idx->getZExtValue() * EltSize;
7255 unsigned EltIdx = BitIndex / 32;
7256 unsigned LeftoverBitIdx = BitIndex % 32;
7259 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
7260 DCI.AddToWorklist(Cast.getNode());
7262 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
7263 DAG.getConstant(EltIdx, SL, MVT::i32));
7264 DCI.AddToWorklist(Elt.getNode());
7265 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
7266 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
7267 DCI.AddToWorklist(Srl.getNode());
7269 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
7270 DCI.AddToWorklist(Trunc.getNode());
7271 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
7277 static bool convertBuildVectorCastElt(SelectionDAG &DAG,
7278 SDValue &Lo, SDValue &Hi) {
7279 if (Hi.getOpcode() == ISD::BITCAST &&
7280 Hi.getOperand(0).getValueType() == MVT::f16 &&
7281 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) {
7282 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo);
7283 Hi = Hi.getOperand(0);
7290 SDValue SITargetLowering::performBuildVectorCombine(
7291 SDNode *N, DAGCombinerInfo &DCI) const {
7294 if (!isTypeLegal(MVT::v2i16))
7296 SelectionDAG &DAG = DCI.DAG;
7297 EVT VT = N->getValueType(0);
7299 if (VT == MVT::v2i16) {
7300 SDValue Lo = N->getOperand(0);
7301 SDValue Hi = N->getOperand(1);
7303 // v2i16 build_vector (const|undef), (bitcast f16:$x)
7304 // -> bitcast (v2f16 build_vector const|undef, $x
7305 if (convertBuildVectorCastElt(DAG, Lo, Hi)) {
7306 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi });
7307 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
7310 if (convertBuildVectorCastElt(DAG, Hi, Lo)) {
7311 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo });
7312 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
7319 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
7321 const SDNode *N1) const {
7322 EVT VT = N0->getValueType(0);
7324 // Only do this if we are not trying to support denormals. v_mad_f32 does not
7325 // support denormals ever.
7326 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
7327 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
7330 const TargetOptions &Options = DAG.getTarget().Options;
7331 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
7332 (N0->getFlags().hasAllowContract() &&
7333 N1->getFlags().hasAllowContract())) &&
7334 isFMAFasterThanFMulAndFAdd(VT)) {
7341 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
7343 SDValue N0, SDValue N1, SDValue N2,
7345 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
7346 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
7347 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
7348 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
7351 SDValue SITargetLowering::performAddCombine(SDNode *N,
7352 DAGCombinerInfo &DCI) const {
7353 SelectionDAG &DAG = DCI.DAG;
7354 EVT VT = N->getValueType(0);
7356 SDValue LHS = N->getOperand(0);
7357 SDValue RHS = N->getOperand(1);
7359 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
7360 && Subtarget->hasMad64_32() &&
7361 !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
7362 VT.getScalarSizeInBits() <= 64) {
7363 if (LHS.getOpcode() != ISD::MUL)
7364 std::swap(LHS, RHS);
7366 SDValue MulLHS = LHS.getOperand(0);
7367 SDValue MulRHS = LHS.getOperand(1);
7368 SDValue AddRHS = RHS;
7370 // TODO: Maybe restrict if SGPR inputs.
7371 if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
7372 numBitsUnsigned(MulRHS, DAG) <= 32) {
7373 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
7374 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
7375 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
7376 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
7379 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
7380 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
7381 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
7382 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
7383 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
7389 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
7392 // add x, zext (setcc) => addcarry x, 0, setcc
7393 // add x, sext (setcc) => subcarry x, 0, setcc
7394 unsigned Opc = LHS.getOpcode();
7395 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
7396 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
7397 std::swap(RHS, LHS);
7399 Opc = RHS.getOpcode();
7402 case ISD::ZERO_EXTEND:
7403 case ISD::SIGN_EXTEND:
7404 case ISD::ANY_EXTEND: {
7405 auto Cond = RHS.getOperand(0);
7406 if (!isBoolSGPR(Cond))
7408 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
7409 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
7410 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
7411 return DAG.getNode(Opc, SL, VTList, Args);
7413 case ISD::ADDCARRY: {
7414 // add x, (addcarry y, 0, cc) => addcarry x, y, cc
7415 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7416 if (!C || C->getZExtValue() != 0) break;
7417 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
7418 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
7424 SDValue SITargetLowering::performSubCombine(SDNode *N,
7425 DAGCombinerInfo &DCI) const {
7426 SelectionDAG &DAG = DCI.DAG;
7427 EVT VT = N->getValueType(0);
7433 SDValue LHS = N->getOperand(0);
7434 SDValue RHS = N->getOperand(1);
7436 unsigned Opc = LHS.getOpcode();
7437 if (Opc != ISD::SUBCARRY)
7438 std::swap(RHS, LHS);
7440 if (LHS.getOpcode() == ISD::SUBCARRY) {
7441 // sub (subcarry x, 0, cc), y => subcarry x, y, cc
7442 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
7443 if (!C || C->getZExtValue() != 0)
7445 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
7446 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
7451 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
7452 DAGCombinerInfo &DCI) const {
7454 if (N->getValueType(0) != MVT::i32)
7457 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7458 if (!C || C->getZExtValue() != 0)
7461 SelectionDAG &DAG = DCI.DAG;
7462 SDValue LHS = N->getOperand(0);
7464 // addcarry (add x, y), 0, cc => addcarry x, y, cc
7465 // subcarry (sub x, y), 0, cc => subcarry x, y, cc
7466 unsigned LHSOpc = LHS.getOpcode();
7467 unsigned Opc = N->getOpcode();
7468 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
7469 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
7470 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
7471 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
7476 SDValue SITargetLowering::performFAddCombine(SDNode *N,
7477 DAGCombinerInfo &DCI) const {
7478 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7481 SelectionDAG &DAG = DCI.DAG;
7482 EVT VT = N->getValueType(0);
7485 SDValue LHS = N->getOperand(0);
7486 SDValue RHS = N->getOperand(1);
7488 // These should really be instruction patterns, but writing patterns with
7489 // source modiifiers is a pain.
7491 // fadd (fadd (a, a), b) -> mad 2.0, a, b
7492 if (LHS.getOpcode() == ISD::FADD) {
7493 SDValue A = LHS.getOperand(0);
7494 if (A == LHS.getOperand(1)) {
7495 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7497 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7498 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
7503 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
7504 if (RHS.getOpcode() == ISD::FADD) {
7505 SDValue A = RHS.getOperand(0);
7506 if (A == RHS.getOperand(1)) {
7507 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7509 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7510 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
7518 SDValue SITargetLowering::performFSubCombine(SDNode *N,
7519 DAGCombinerInfo &DCI) const {
7520 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7523 SelectionDAG &DAG = DCI.DAG;
7525 EVT VT = N->getValueType(0);
7526 assert(!VT.isVector());
7528 // Try to get the fneg to fold into the source modifier. This undoes generic
7529 // DAG combines and folds them into the mad.
7531 // Only do this if we are not trying to support denormals. v_mad_f32 does
7532 // not support denormals ever.
7533 SDValue LHS = N->getOperand(0);
7534 SDValue RHS = N->getOperand(1);
7535 if (LHS.getOpcode() == ISD::FADD) {
7536 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
7537 SDValue A = LHS.getOperand(0);
7538 if (A == LHS.getOperand(1)) {
7539 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7541 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7542 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7544 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
7549 if (RHS.getOpcode() == ISD::FADD) {
7550 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
7552 SDValue A = RHS.getOperand(0);
7553 if (A == RHS.getOperand(1)) {
7554 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7556 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
7557 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
7565 SDValue SITargetLowering::performFMACombine(SDNode *N,
7566 DAGCombinerInfo &DCI) const {
7567 SelectionDAG &DAG = DCI.DAG;
7568 EVT VT = N->getValueType(0);
7571 if (!Subtarget->hasDLInsts() || VT != MVT::f32)
7574 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
7575 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
7576 SDValue Op1 = N->getOperand(0);
7577 SDValue Op2 = N->getOperand(1);
7578 SDValue FMA = N->getOperand(2);
7580 if (FMA.getOpcode() != ISD::FMA ||
7581 Op1.getOpcode() != ISD::FP_EXTEND ||
7582 Op2.getOpcode() != ISD::FP_EXTEND)
7585 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
7586 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
7587 // is sufficient to allow generaing fdot2.
7588 const TargetOptions &Options = DAG.getTarget().Options;
7589 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
7590 (N->getFlags().hasAllowContract() &&
7591 FMA->getFlags().hasAllowContract())) {
7592 Op1 = Op1.getOperand(0);
7593 Op2 = Op2.getOperand(0);
7594 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7595 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7598 SDValue Vec1 = Op1.getOperand(0);
7599 SDValue Idx1 = Op1.getOperand(1);
7600 SDValue Vec2 = Op2.getOperand(0);
7602 SDValue FMAOp1 = FMA.getOperand(0);
7603 SDValue FMAOp2 = FMA.getOperand(1);
7604 SDValue FMAAcc = FMA.getOperand(2);
7606 if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
7607 FMAOp2.getOpcode() != ISD::FP_EXTEND)
7610 FMAOp1 = FMAOp1.getOperand(0);
7611 FMAOp2 = FMAOp2.getOperand(0);
7612 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7613 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7616 SDValue Vec3 = FMAOp1.getOperand(0);
7617 SDValue Vec4 = FMAOp2.getOperand(0);
7618 SDValue Idx2 = FMAOp1.getOperand(1);
7620 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
7621 // Idx1 and Idx2 cannot be the same.
7625 if (Vec1 == Vec2 || Vec3 == Vec4)
7628 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
7631 if ((Vec1 == Vec3 && Vec2 == Vec4) ||
7632 (Vec1 == Vec4 && Vec2 == Vec3)) {
7633 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
7634 DAG.getTargetConstant(0, SL, MVT::i1));
7640 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
7641 DAGCombinerInfo &DCI) const {
7642 SelectionDAG &DAG = DCI.DAG;
7645 SDValue LHS = N->getOperand(0);
7646 SDValue RHS = N->getOperand(1);
7647 EVT VT = LHS.getValueType();
7648 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
7650 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
7652 CRHS = dyn_cast<ConstantSDNode>(LHS);
7654 std::swap(LHS, RHS);
7655 CC = getSetCCSwappedOperands(CC);
7660 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
7661 isBoolSGPR(LHS.getOperand(0))) {
7662 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
7663 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
7664 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
7665 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
7666 if ((CRHS->isAllOnesValue() &&
7667 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
7668 (CRHS->isNullValue() &&
7669 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
7670 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7671 DAG.getConstant(-1, SL, MVT::i1));
7672 if ((CRHS->isAllOnesValue() &&
7673 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
7674 (CRHS->isNullValue() &&
7675 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
7676 return LHS.getOperand(0);
7679 uint64_t CRHSVal = CRHS->getZExtValue();
7680 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
7681 LHS.getOpcode() == ISD::SELECT &&
7682 isa<ConstantSDNode>(LHS.getOperand(1)) &&
7683 isa<ConstantSDNode>(LHS.getOperand(2)) &&
7684 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
7685 isBoolSGPR(LHS.getOperand(0))) {
7687 // setcc (select cc, CT, CF), CF, eq => xor cc, -1
7688 // setcc (select cc, CT, CF), CF, ne => cc
7689 // setcc (select cc, CT, CF), CT, ne => xor cc, -1
7690 // setcc (select cc, CT, CF), CT, eq => cc
7691 uint64_t CT = LHS.getConstantOperandVal(1);
7692 uint64_t CF = LHS.getConstantOperandVal(2);
7694 if ((CF == CRHSVal && CC == ISD::SETEQ) ||
7695 (CT == CRHSVal && CC == ISD::SETNE))
7696 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7697 DAG.getConstant(-1, SL, MVT::i1));
7698 if ((CF == CRHSVal && CC == ISD::SETNE) ||
7699 (CT == CRHSVal && CC == ISD::SETEQ))
7700 return LHS.getOperand(0);
7704 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
7708 // Match isinf pattern
7709 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
7710 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
7711 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
7715 const APFloat &APF = CRHS->getValueAPF();
7716 if (APF.isInfinity() && !APF.isNegative()) {
7717 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
7718 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
7719 DAG.getConstant(Mask, SL, MVT::i32));
7726 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
7727 DAGCombinerInfo &DCI) const {
7728 SelectionDAG &DAG = DCI.DAG;
7730 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
7732 SDValue Src = N->getOperand(0);
7733 SDValue Srl = N->getOperand(0);
7734 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
7735 Srl = Srl.getOperand(0);
7737 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
7738 if (Srl.getOpcode() == ISD::SRL) {
7739 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
7740 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
7741 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
7743 if (const ConstantSDNode *C =
7744 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
7745 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
7748 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
7749 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
7750 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
7756 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
7759 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
7760 !DCI.isBeforeLegalizeOps());
7761 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7762 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
7763 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
7764 DCI.CommitTargetLoweringOpt(TLO);
7770 SDValue SITargetLowering::performClampCombine(SDNode *N,
7771 DAGCombinerInfo &DCI) const {
7772 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
7776 const APFloat &F = CSrc->getValueAPF();
7777 APFloat Zero = APFloat::getZero(F.getSemantics());
7778 APFloat::cmpResult Cmp0 = F.compare(Zero);
7779 if (Cmp0 == APFloat::cmpLessThan ||
7780 (Cmp0 == APFloat::cmpUnordered && Subtarget->enableDX10Clamp())) {
7781 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
7784 APFloat One(F.getSemantics(), "1.0");
7785 APFloat::cmpResult Cmp1 = F.compare(One);
7786 if (Cmp1 == APFloat::cmpGreaterThan)
7787 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
7789 return SDValue(CSrc, 0);
7793 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
7794 DAGCombinerInfo &DCI) const {
7795 switch (N->getOpcode()) {
7797 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7799 return performAddCombine(N, DCI);
7801 return performSubCombine(N, DCI);
7804 return performAddCarrySubCarryCombine(N, DCI);
7806 return performFAddCombine(N, DCI);
7808 return performFSubCombine(N, DCI);
7810 return performSetCCCombine(N, DCI);
7817 case AMDGPUISD::FMIN_LEGACY:
7818 case AMDGPUISD::FMAX_LEGACY: {
7819 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
7820 getTargetMachine().getOptLevel() > CodeGenOpt::None)
7821 return performMinMaxCombine(N, DCI);
7825 return performFMACombine(N, DCI);
7827 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
7832 case ISD::ATOMIC_LOAD:
7833 case ISD::ATOMIC_STORE:
7834 case ISD::ATOMIC_CMP_SWAP:
7835 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
7836 case ISD::ATOMIC_SWAP:
7837 case ISD::ATOMIC_LOAD_ADD:
7838 case ISD::ATOMIC_LOAD_SUB:
7839 case ISD::ATOMIC_LOAD_AND:
7840 case ISD::ATOMIC_LOAD_OR:
7841 case ISD::ATOMIC_LOAD_XOR:
7842 case ISD::ATOMIC_LOAD_NAND:
7843 case ISD::ATOMIC_LOAD_MIN:
7844 case ISD::ATOMIC_LOAD_MAX:
7845 case ISD::ATOMIC_LOAD_UMIN:
7846 case ISD::ATOMIC_LOAD_UMAX:
7847 case AMDGPUISD::ATOMIC_INC:
7848 case AMDGPUISD::ATOMIC_DEC:
7849 case AMDGPUISD::ATOMIC_LOAD_FADD:
7850 case AMDGPUISD::ATOMIC_LOAD_FMIN:
7851 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
7852 if (DCI.isBeforeLegalize())
7854 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
7856 return performAndCombine(N, DCI);
7858 return performOrCombine(N, DCI);
7860 return performXorCombine(N, DCI);
7861 case ISD::ZERO_EXTEND:
7862 return performZeroExtendCombine(N, DCI);
7863 case AMDGPUISD::FP_CLASS:
7864 return performClassCombine(N, DCI);
7865 case ISD::FCANONICALIZE:
7866 return performFCanonicalizeCombine(N, DCI);
7867 case AMDGPUISD::RCP:
7868 return performRcpCombine(N, DCI);
7869 case AMDGPUISD::FRACT:
7870 case AMDGPUISD::RSQ:
7871 case AMDGPUISD::RCP_LEGACY:
7872 case AMDGPUISD::RSQ_LEGACY:
7873 case AMDGPUISD::RCP_IFLAG:
7874 case AMDGPUISD::RSQ_CLAMP:
7875 case AMDGPUISD::LDEXP: {
7876 SDValue Src = N->getOperand(0);
7881 case ISD::SINT_TO_FP:
7882 case ISD::UINT_TO_FP:
7883 return performUCharToFloatCombine(N, DCI);
7884 case AMDGPUISD::CVT_F32_UBYTE0:
7885 case AMDGPUISD::CVT_F32_UBYTE1:
7886 case AMDGPUISD::CVT_F32_UBYTE2:
7887 case AMDGPUISD::CVT_F32_UBYTE3:
7888 return performCvtF32UByteNCombine(N, DCI);
7889 case AMDGPUISD::FMED3:
7890 return performFMed3Combine(N, DCI);
7891 case AMDGPUISD::CVT_PKRTZ_F16_F32:
7892 return performCvtPkRTZCombine(N, DCI);
7893 case AMDGPUISD::CLAMP:
7894 return performClampCombine(N, DCI);
7895 case ISD::SCALAR_TO_VECTOR: {
7896 SelectionDAG &DAG = DCI.DAG;
7897 EVT VT = N->getValueType(0);
7899 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
7900 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
7902 SDValue Src = N->getOperand(0);
7903 EVT EltVT = Src.getValueType();
7904 if (EltVT == MVT::f16)
7905 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
7907 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
7908 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
7913 case ISD::EXTRACT_VECTOR_ELT:
7914 return performExtractVectorEltCombine(N, DCI);
7915 case ISD::BUILD_VECTOR:
7916 return performBuildVectorCombine(N, DCI);
7918 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7921 /// Helper function for adjustWritemask
7922 static unsigned SubIdx2Lane(unsigned Idx) {
7925 case AMDGPU::sub0: return 0;
7926 case AMDGPU::sub1: return 1;
7927 case AMDGPU::sub2: return 2;
7928 case AMDGPU::sub3: return 3;
7932 /// Adjust the writemask of MIMG instructions
7933 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
7934 SelectionDAG &DAG) const {
7935 unsigned Opcode = Node->getMachineOpcode();
7937 // Subtract 1 because the vdata output is not a MachineSDNode operand.
7938 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
7939 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
7940 return Node; // not implemented for D16
7942 SDNode *Users[4] = { nullptr };
7944 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
7945 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
7946 unsigned NewDmask = 0;
7947 bool HasChain = Node->getNumValues() > 1;
7949 if (OldDmask == 0) {
7950 // These are folded out, but on the chance it happens don't assert.
7954 // Try to figure out the used register components
7955 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
7958 // Don't look at users of the chain.
7959 if (I.getUse().getResNo() != 0)
7962 // Abort if we can't understand the usage
7963 if (!I->isMachineOpcode() ||
7964 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
7967 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
7968 // Note that subregs are packed, i.e. Lane==0 is the first bit set
7969 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
7971 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
7973 // Set which texture component corresponds to the lane.
7975 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
7976 Comp = countTrailingZeros(Dmask);
7977 Dmask &= ~(1 << Comp);
7980 // Abort if we have more than one user per component
7985 NewDmask |= 1 << Comp;
7988 // Abort if there's no change
7989 if (NewDmask == OldDmask)
7992 unsigned BitsSet = countPopulation(NewDmask);
7994 int NewOpcode = AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), BitsSet);
7995 assert(NewOpcode != -1 &&
7996 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
7997 "failed to find equivalent MIMG op");
7999 // Adjust the writemask in the node
8000 SmallVector<SDValue, 12> Ops;
8001 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
8002 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
8003 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
8005 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
8007 MVT ResultVT = BitsSet == 1 ?
8008 SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet);
8009 SDVTList NewVTList = HasChain ?
8010 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
8013 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
8018 NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end());
8019 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
8023 assert(Node->hasNUsesOfValue(1, 0));
8024 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
8025 SDLoc(Node), Users[Lane]->getValueType(0),
8026 SDValue(NewNode, 0));
8027 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
8031 // Update the users of the node with the new indices
8032 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
8033 SDNode *User = Users[i];
8037 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
8038 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
8042 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
8043 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
8044 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
8048 DAG.RemoveDeadNode(Node);
8052 static bool isFrameIndexOp(SDValue Op) {
8053 if (Op.getOpcode() == ISD::AssertZext)
8054 Op = Op.getOperand(0);
8056 return isa<FrameIndexSDNode>(Op);
8059 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
8060 /// with frame index operands.
8061 /// LLVM assumes that inputs are to these instructions are registers.
8062 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
8063 SelectionDAG &DAG) const {
8064 if (Node->getOpcode() == ISD::CopyToReg) {
8065 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
8066 SDValue SrcVal = Node->getOperand(2);
8068 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
8069 // to try understanding copies to physical registers.
8070 if (SrcVal.getValueType() == MVT::i1 &&
8071 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
8073 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
8074 SDValue VReg = DAG.getRegister(
8075 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
8077 SDNode *Glued = Node->getGluedNode();
8079 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
8080 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
8082 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
8083 VReg, ToVReg.getValue(1));
8084 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
8085 DAG.RemoveDeadNode(Node);
8086 return ToResultReg.getNode();
8090 SmallVector<SDValue, 8> Ops;
8091 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
8092 if (!isFrameIndexOp(Node->getOperand(i))) {
8093 Ops.push_back(Node->getOperand(i));
8098 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
8099 Node->getOperand(i).getValueType(),
8100 Node->getOperand(i)), 0));
8103 return DAG.UpdateNodeOperands(Node, Ops);
8106 /// Fold the instructions after selecting them.
8107 /// Returns null if users were already updated.
8108 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
8109 SelectionDAG &DAG) const {
8110 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8111 unsigned Opcode = Node->getMachineOpcode();
8113 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
8114 !TII->isGather4(Opcode)) {
8115 return adjustWritemask(Node, DAG);
8118 if (Opcode == AMDGPU::INSERT_SUBREG ||
8119 Opcode == AMDGPU::REG_SEQUENCE) {
8120 legalizeTargetIndependentNode(Node, DAG);
8125 case AMDGPU::V_DIV_SCALE_F32:
8126 case AMDGPU::V_DIV_SCALE_F64: {
8127 // Satisfy the operand register constraint when one of the inputs is
8128 // undefined. Ordinarily each undef value will have its own implicit_def of
8129 // a vreg, so force these to use a single register.
8130 SDValue Src0 = Node->getOperand(0);
8131 SDValue Src1 = Node->getOperand(1);
8132 SDValue Src2 = Node->getOperand(2);
8134 if ((Src0.isMachineOpcode() &&
8135 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
8136 (Src0 == Src1 || Src0 == Src2))
8139 MVT VT = Src0.getValueType().getSimpleVT();
8140 const TargetRegisterClass *RC = getRegClassFor(VT);
8142 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
8143 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
8145 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
8146 UndefReg, Src0, SDValue());
8148 // src0 must be the same register as src1 or src2, even if the value is
8149 // undefined, so make sure we don't violate this constraint.
8150 if (Src0.isMachineOpcode() &&
8151 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
8152 if (Src1.isMachineOpcode() &&
8153 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
8155 else if (Src2.isMachineOpcode() &&
8156 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
8159 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
8166 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
8167 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
8168 Ops.push_back(Node->getOperand(I));
8170 Ops.push_back(ImpDef.getValue(1));
8171 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
8180 /// Assign the register class depending on the number of
8181 /// bits set in the writemask
8182 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8183 SDNode *Node) const {
8184 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8186 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
8188 if (TII->isVOP3(MI.getOpcode())) {
8189 // Make sure constant bus requirements are respected.
8190 TII->legalizeOperandsVOP3(MRI, MI);
8194 // Replace unused atomics with the no return version.
8195 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
8196 if (NoRetAtomicOp != -1) {
8197 if (!Node->hasAnyUseOfValue(0)) {
8198 MI.setDesc(TII->get(NoRetAtomicOp));
8199 MI.RemoveOperand(0);
8203 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
8204 // instruction, because the return type of these instructions is a vec2 of
8205 // the memory type, so it can be tied to the input operand.
8206 // This means these instructions always have a use, so we need to add a
8207 // special case to check if the atomic has only one extract_subreg use,
8208 // which itself has no uses.
8209 if ((Node->hasNUsesOfValue(1, 0) &&
8210 Node->use_begin()->isMachineOpcode() &&
8211 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
8212 !Node->use_begin()->hasAnyUseOfValue(0))) {
8213 unsigned Def = MI.getOperand(0).getReg();
8215 // Change this into a noret atomic.
8216 MI.setDesc(TII->get(NoRetAtomicOp));
8217 MI.RemoveOperand(0);
8219 // If we only remove the def operand from the atomic instruction, the
8220 // extract_subreg will be left with a use of a vreg without a def.
8221 // So we need to insert an implicit_def to avoid machine verifier
8223 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
8224 TII->get(AMDGPU::IMPLICIT_DEF), Def);
8230 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
8232 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
8233 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
8236 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
8238 SDValue Ptr) const {
8239 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8241 // Build the half of the subregister with the constants before building the
8242 // full 128-bit register. If we are building multiple resource descriptors,
8243 // this will allow CSEing of the 2-component register.
8244 const SDValue Ops0[] = {
8245 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
8246 buildSMovImm32(DAG, DL, 0),
8247 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
8248 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
8249 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
8252 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
8253 MVT::v2i32, Ops0), 0);
8255 // Combine the constants and the pointer.
8256 const SDValue Ops1[] = {
8257 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
8259 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
8261 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
8264 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
8267 /// Return a resource descriptor with the 'Add TID' bit enabled
8268 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
8269 /// of the resource descriptor) to create an offset, which is added to
8270 /// the resource pointer.
8271 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
8272 SDValue Ptr, uint32_t RsrcDword1,
8273 uint64_t RsrcDword2And3) const {
8274 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
8275 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
8277 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
8278 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
8282 SDValue DataLo = buildSMovImm32(DAG, DL,
8283 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
8284 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
8286 const SDValue Ops[] = {
8287 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
8289 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
8291 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
8293 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
8295 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
8298 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
8301 //===----------------------------------------------------------------------===//
8302 // SI Inline Assembly Support
8303 //===----------------------------------------------------------------------===//
8305 std::pair<unsigned, const TargetRegisterClass *>
8306 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
8307 StringRef Constraint,
8309 const TargetRegisterClass *RC = nullptr;
8310 if (Constraint.size() == 1) {
8311 switch (Constraint[0]) {
8313 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8316 switch (VT.getSizeInBits()) {
8318 return std::make_pair(0U, nullptr);
8321 RC = &AMDGPU::SReg_32_XM0RegClass;
8324 RC = &AMDGPU::SGPR_64RegClass;
8327 RC = &AMDGPU::SReg_128RegClass;
8330 RC = &AMDGPU::SReg_256RegClass;
8333 RC = &AMDGPU::SReg_512RegClass;
8338 switch (VT.getSizeInBits()) {
8340 return std::make_pair(0U, nullptr);
8343 RC = &AMDGPU::VGPR_32RegClass;
8346 RC = &AMDGPU::VReg_64RegClass;
8349 RC = &AMDGPU::VReg_96RegClass;
8352 RC = &AMDGPU::VReg_128RegClass;
8355 RC = &AMDGPU::VReg_256RegClass;
8358 RC = &AMDGPU::VReg_512RegClass;
8363 // We actually support i128, i16 and f16 as inline parameters
8364 // even if they are not reported as legal
8365 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
8366 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
8367 return std::make_pair(0U, RC);
8370 if (Constraint.size() > 1) {
8371 if (Constraint[1] == 'v') {
8372 RC = &AMDGPU::VGPR_32RegClass;
8373 } else if (Constraint[1] == 's') {
8374 RC = &AMDGPU::SGPR_32RegClass;
8379 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
8380 if (!Failed && Idx < RC->getNumRegs())
8381 return std::make_pair(RC->getRegister(Idx), RC);
8384 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8387 SITargetLowering::ConstraintType
8388 SITargetLowering::getConstraintType(StringRef Constraint) const {
8389 if (Constraint.size() == 1) {
8390 switch (Constraint[0]) {
8394 return C_RegisterClass;
8397 return TargetLowering::getConstraintType(Constraint);
8400 // Figure out which registers should be reserved for stack access. Only after
8401 // the function is legalized do we know all of the non-spill stack objects or if
8402 // calls are present.
8403 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
8404 MachineRegisterInfo &MRI = MF.getRegInfo();
8405 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8406 const MachineFrameInfo &MFI = MF.getFrameInfo();
8407 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
8409 if (Info->isEntryFunction()) {
8410 // Callable functions have fixed registers used for stack access.
8411 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
8414 // We have to assume the SP is needed in case there are calls in the function
8415 // during lowering. Calls are only detected after the function is
8416 // lowered. We're about to reserve registers, so don't bother using it if we
8417 // aren't really going to use it.
8418 bool NeedSP = !Info->isEntryFunction() ||
8419 MFI.hasVarSizedObjects() ||
8423 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
8424 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
8426 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
8427 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
8428 Info->getStackPtrOffsetReg()));
8429 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
8432 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
8433 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
8434 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
8435 Info->getScratchWaveOffsetReg());
8437 Info->limitOccupancy(MF);
8439 TargetLoweringBase::finalizeLowering(MF);
8442 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
8444 const APInt &DemandedElts,
8445 const SelectionDAG &DAG,
8446 unsigned Depth) const {
8447 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
8450 if (getSubtarget()->enableHugePrivateBuffer())
8453 // Technically it may be possible to have a dispatch with a single workitem
8454 // that uses the full private memory size, but that's not really useful. We
8455 // can't use vaddr in MUBUF instructions if we don't know the address
8456 // calculation won't overflow, so assume the sign bit is never set.
8457 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);
8460 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
8461 FunctionLoweringInfo * FLI, DivergenceAnalysis * DA) const
8463 switch (N->getOpcode()) {
8465 case ISD::CopyFromReg:
8467 const RegisterSDNode *R = nullptr;
8468 if (N->getOpcode() == ISD::Register) {
8469 R = dyn_cast<RegisterSDNode>(N);
8472 R = dyn_cast<RegisterSDNode>(N->getOperand(1));
8476 const MachineFunction * MF = FLI->MF;
8477 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
8478 const MachineRegisterInfo &MRI = MF->getRegInfo();
8479 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
8480 unsigned Reg = R->getReg();
8481 if (TRI.isPhysicalRegister(Reg))
8482 return TRI.isVGPR(MRI, Reg);
8484 if (MRI.isLiveIn(Reg)) {
8485 // workitem.id.x workitem.id.y workitem.id.z
8486 // Any VGPR formal argument is also considered divergent
8487 if (TRI.isVGPR(MRI, Reg))
8489 // Formal arguments of non-entry functions
8490 // are conservatively considered divergent
8491 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
8494 return !DA || DA->isDivergent(FLI->getValueFromVirtualReg(Reg));
8499 const LoadSDNode *L = dyn_cast<LoadSDNode>(N);
8500 if (L->getMemOperand()->getAddrSpace() ==
8501 Subtarget->getAMDGPUAS().PRIVATE_ADDRESS)
8504 case ISD::CALLSEQ_END:
8507 case ISD::INTRINSIC_WO_CHAIN:
8511 return AMDGPU::isIntrinsicSourceOfDivergence(
8512 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
8513 case ISD::INTRINSIC_W_CHAIN:
8514 return AMDGPU::isIntrinsicSourceOfDivergence(
8515 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
8516 // In some cases intrinsics that are a source of divergence have been
8517 // lowered to AMDGPUISD so we also need to check those too.
8518 case AMDGPUISD::INTERP_MOV:
8519 case AMDGPUISD::INTERP_P1:
8520 case AMDGPUISD::INTERP_P2: