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 /// \brief 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 "Utils/AMDGPUBaseInfo.h"
30 #include "llvm/ADT/APFloat.h"
31 #include "llvm/ADT/APInt.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/Twine.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/CallingConvLower.h"
41 #include "llvm/CodeGen/DAGCombine.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/MachineValueType.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/MathExtras.h"
77 #include "llvm/Target/TargetOptions.h"
88 #define DEBUG_TYPE "si-lower"
90 STATISTIC(NumTailCalls, "Number of tail calls");
92 static cl::opt<bool> EnableVGPRIndexMode(
93 "amdgpu-vgpr-index-mode",
94 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
97 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
98 "amdgpu-frame-index-zero-bits",
99 cl::desc("High bits of frame index assumed to be zero"),
103 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
104 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
105 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
106 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
107 return AMDGPU::SGPR0 + Reg;
110 llvm_unreachable("Cannot allocate sgpr");
113 SITargetLowering::SITargetLowering(const TargetMachine &TM,
114 const SISubtarget &STI)
115 : AMDGPUTargetLowering(TM, STI) {
116 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
117 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
119 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
120 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
122 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
123 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
124 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
126 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
127 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
129 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
130 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
132 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
133 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
135 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
136 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
138 if (Subtarget->has16BitInsts()) {
139 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
140 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
143 if (Subtarget->hasVOP3PInsts()) {
144 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
145 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
148 computeRegisterProperties(STI.getRegisterInfo());
150 // We need to custom lower vector stores from local memory
151 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
152 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
153 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
154 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
155 setOperationAction(ISD::LOAD, MVT::i1, Custom);
157 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
158 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
159 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
160 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
161 setOperationAction(ISD::STORE, MVT::i1, Custom);
163 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
164 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
165 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
166 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
167 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
168 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
169 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
170 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
171 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
172 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
174 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
175 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
176 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
178 setOperationAction(ISD::SELECT, MVT::i1, Promote);
179 setOperationAction(ISD::SELECT, MVT::i64, Custom);
180 setOperationAction(ISD::SELECT, MVT::f64, Promote);
181 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
183 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
184 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
185 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
186 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
187 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
189 setOperationAction(ISD::SETCC, MVT::i1, Promote);
190 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
191 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
192 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
194 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
195 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
198 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
201 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
205 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
206 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
208 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
210 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
212 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
213 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
214 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
216 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
217 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
218 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
219 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
220 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
221 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
223 setOperationAction(ISD::UADDO, MVT::i32, Legal);
224 setOperationAction(ISD::USUBO, MVT::i32, Legal);
226 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
227 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
230 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
231 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
234 //setOperationAction(ISD::ADDC, MVT::i64, Expand);
235 //setOperationAction(ISD::SUBC, MVT::i64, Expand);
237 // We only support LOAD/STORE and vector manipulation ops for vectors
238 // with > 4 elements.
239 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
240 MVT::v2i64, MVT::v2f64}) {
241 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
245 case ISD::BUILD_VECTOR:
247 case ISD::EXTRACT_VECTOR_ELT:
248 case ISD::INSERT_VECTOR_ELT:
249 case ISD::INSERT_SUBVECTOR:
250 case ISD::EXTRACT_SUBVECTOR:
251 case ISD::SCALAR_TO_VECTOR:
253 case ISD::CONCAT_VECTORS:
254 setOperationAction(Op, VT, Custom);
257 setOperationAction(Op, VT, Expand);
263 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
264 // is expanded to avoid having two separate loops in case the index is a VGPR.
266 // Most operations are naturally 32-bit vector operations. We only support
267 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
268 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
269 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
270 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
272 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
273 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
275 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
276 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
278 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
279 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
282 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
283 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
284 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
285 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
287 // Avoid stack access for these.
288 // TODO: Generalize to more vector types.
289 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
290 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
291 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
292 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
294 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
295 // and output demarshalling
296 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
297 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
299 // We can't return success/failure, only the old value,
300 // let LLVM add the comparison
301 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
302 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
304 if (getSubtarget()->hasFlatAddressSpace()) {
305 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
306 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
309 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
310 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
312 // On SI this is s_memtime and s_memrealtime on VI.
313 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
314 setOperationAction(ISD::TRAP, MVT::Other, Custom);
315 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
317 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
318 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
320 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
321 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
322 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
323 setOperationAction(ISD::FRINT, MVT::f64, Legal);
326 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
328 setOperationAction(ISD::FSIN, MVT::f32, Custom);
329 setOperationAction(ISD::FCOS, MVT::f32, Custom);
330 setOperationAction(ISD::FDIV, MVT::f32, Custom);
331 setOperationAction(ISD::FDIV, MVT::f64, Custom);
333 if (Subtarget->has16BitInsts()) {
334 setOperationAction(ISD::Constant, MVT::i16, Legal);
336 setOperationAction(ISD::SMIN, MVT::i16, Legal);
337 setOperationAction(ISD::SMAX, MVT::i16, Legal);
339 setOperationAction(ISD::UMIN, MVT::i16, Legal);
340 setOperationAction(ISD::UMAX, MVT::i16, Legal);
342 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
343 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
345 setOperationAction(ISD::ROTR, MVT::i16, Promote);
346 setOperationAction(ISD::ROTL, MVT::i16, Promote);
348 setOperationAction(ISD::SDIV, MVT::i16, Promote);
349 setOperationAction(ISD::UDIV, MVT::i16, Promote);
350 setOperationAction(ISD::SREM, MVT::i16, Promote);
351 setOperationAction(ISD::UREM, MVT::i16, Promote);
353 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
354 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
356 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
357 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
358 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
361 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
363 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
365 setOperationAction(ISD::LOAD, MVT::i16, Custom);
367 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
369 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
370 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
371 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
372 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
374 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
375 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
376 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
377 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
379 // F16 - Constant Actions.
380 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
382 // F16 - Load/Store Actions.
383 setOperationAction(ISD::LOAD, MVT::f16, Promote);
384 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
385 setOperationAction(ISD::STORE, MVT::f16, Promote);
386 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
388 // F16 - VOP1 Actions.
389 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
390 setOperationAction(ISD::FCOS, MVT::f16, Promote);
391 setOperationAction(ISD::FSIN, MVT::f16, Promote);
392 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
393 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
394 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
395 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
396 setOperationAction(ISD::FROUND, MVT::f16, Custom);
398 // F16 - VOP2 Actions.
399 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
400 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
401 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
402 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
403 setOperationAction(ISD::FDIV, MVT::f16, Custom);
405 // F16 - VOP3 Actions.
406 setOperationAction(ISD::FMA, MVT::f16, Legal);
407 if (!Subtarget->hasFP16Denormals())
408 setOperationAction(ISD::FMAD, MVT::f16, Legal);
411 if (Subtarget->hasVOP3PInsts()) {
412 for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
413 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
417 case ISD::BUILD_VECTOR:
419 case ISD::EXTRACT_VECTOR_ELT:
420 case ISD::INSERT_VECTOR_ELT:
421 case ISD::INSERT_SUBVECTOR:
422 case ISD::EXTRACT_SUBVECTOR:
423 case ISD::SCALAR_TO_VECTOR:
425 case ISD::CONCAT_VECTORS:
426 setOperationAction(Op, VT, Custom);
429 setOperationAction(Op, VT, Expand);
435 // XXX - Do these do anything? Vector constants turn into build_vector.
436 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
437 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
439 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
440 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
441 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
442 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
444 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
445 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
446 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
447 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
449 setOperationAction(ISD::AND, MVT::v2i16, Promote);
450 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
451 setOperationAction(ISD::OR, MVT::v2i16, Promote);
452 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
453 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
454 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
455 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
456 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
457 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
458 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
460 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
461 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
462 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
463 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
464 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
465 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
466 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
467 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
468 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
469 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
471 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
472 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
473 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
474 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
475 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
476 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
478 // This isn't really legal, but this avoids the legalizer unrolling it (and
479 // allows matching fneg (fabs x) patterns)
480 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
482 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
483 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
485 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
486 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
487 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
488 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
490 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
491 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
494 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
495 setOperationAction(ISD::SELECT, VT, Custom);
498 setTargetDAGCombine(ISD::ADD);
499 setTargetDAGCombine(ISD::ADDCARRY);
500 setTargetDAGCombine(ISD::SUB);
501 setTargetDAGCombine(ISD::SUBCARRY);
502 setTargetDAGCombine(ISD::FADD);
503 setTargetDAGCombine(ISD::FSUB);
504 setTargetDAGCombine(ISD::FMINNUM);
505 setTargetDAGCombine(ISD::FMAXNUM);
506 setTargetDAGCombine(ISD::SMIN);
507 setTargetDAGCombine(ISD::SMAX);
508 setTargetDAGCombine(ISD::UMIN);
509 setTargetDAGCombine(ISD::UMAX);
510 setTargetDAGCombine(ISD::SETCC);
511 setTargetDAGCombine(ISD::AND);
512 setTargetDAGCombine(ISD::OR);
513 setTargetDAGCombine(ISD::XOR);
514 setTargetDAGCombine(ISD::SINT_TO_FP);
515 setTargetDAGCombine(ISD::UINT_TO_FP);
516 setTargetDAGCombine(ISD::FCANONICALIZE);
517 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
518 setTargetDAGCombine(ISD::ZERO_EXTEND);
519 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
520 setTargetDAGCombine(ISD::BUILD_VECTOR);
522 // All memory operations. Some folding on the pointer operand is done to help
523 // matching the constant offsets in the addressing modes.
524 setTargetDAGCombine(ISD::LOAD);
525 setTargetDAGCombine(ISD::STORE);
526 setTargetDAGCombine(ISD::ATOMIC_LOAD);
527 setTargetDAGCombine(ISD::ATOMIC_STORE);
528 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
529 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
530 setTargetDAGCombine(ISD::ATOMIC_SWAP);
531 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
532 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
533 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
534 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
535 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
536 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
537 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
538 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
539 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
540 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
542 setSchedulingPreference(Sched::RegPressure);
545 const SISubtarget *SITargetLowering::getSubtarget() const {
546 return static_cast<const SISubtarget *>(Subtarget);
549 //===----------------------------------------------------------------------===//
550 // TargetLowering queries
551 //===----------------------------------------------------------------------===//
553 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
554 // SI has some legal vector types, but no legal vector operations. Say no
555 // shuffles are legal in order to prefer scalarizing some vector operations.
559 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
562 unsigned IntrID) const {
564 case Intrinsic::amdgcn_atomic_inc:
565 case Intrinsic::amdgcn_atomic_dec: {
566 Info.opc = ISD::INTRINSIC_W_CHAIN;
567 Info.memVT = MVT::getVT(CI.getType());
568 Info.ptrVal = CI.getOperand(0);
570 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
572 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
573 if (!Vol || !Vol->isZero())
574 Info.flags |= MachineMemOperand::MOVolatile;
580 case Intrinsic::amdgcn_image_load:
581 case Intrinsic::amdgcn_image_load_mip:
584 case Intrinsic::amdgcn_image_sample:
585 case Intrinsic::amdgcn_image_sample_cl:
586 case Intrinsic::amdgcn_image_sample_d:
587 case Intrinsic::amdgcn_image_sample_d_cl:
588 case Intrinsic::amdgcn_image_sample_l:
589 case Intrinsic::amdgcn_image_sample_b:
590 case Intrinsic::amdgcn_image_sample_b_cl:
591 case Intrinsic::amdgcn_image_sample_lz:
592 case Intrinsic::amdgcn_image_sample_cd:
593 case Intrinsic::amdgcn_image_sample_cd_cl:
595 // Sample with comparison.
596 case Intrinsic::amdgcn_image_sample_c:
597 case Intrinsic::amdgcn_image_sample_c_cl:
598 case Intrinsic::amdgcn_image_sample_c_d:
599 case Intrinsic::amdgcn_image_sample_c_d_cl:
600 case Intrinsic::amdgcn_image_sample_c_l:
601 case Intrinsic::amdgcn_image_sample_c_b:
602 case Intrinsic::amdgcn_image_sample_c_b_cl:
603 case Intrinsic::amdgcn_image_sample_c_lz:
604 case Intrinsic::amdgcn_image_sample_c_cd:
605 case Intrinsic::amdgcn_image_sample_c_cd_cl:
607 // Sample with offsets.
608 case Intrinsic::amdgcn_image_sample_o:
609 case Intrinsic::amdgcn_image_sample_cl_o:
610 case Intrinsic::amdgcn_image_sample_d_o:
611 case Intrinsic::amdgcn_image_sample_d_cl_o:
612 case Intrinsic::amdgcn_image_sample_l_o:
613 case Intrinsic::amdgcn_image_sample_b_o:
614 case Intrinsic::amdgcn_image_sample_b_cl_o:
615 case Intrinsic::amdgcn_image_sample_lz_o:
616 case Intrinsic::amdgcn_image_sample_cd_o:
617 case Intrinsic::amdgcn_image_sample_cd_cl_o:
619 // Sample with comparison and offsets.
620 case Intrinsic::amdgcn_image_sample_c_o:
621 case Intrinsic::amdgcn_image_sample_c_cl_o:
622 case Intrinsic::amdgcn_image_sample_c_d_o:
623 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
624 case Intrinsic::amdgcn_image_sample_c_l_o:
625 case Intrinsic::amdgcn_image_sample_c_b_o:
626 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
627 case Intrinsic::amdgcn_image_sample_c_lz_o:
628 case Intrinsic::amdgcn_image_sample_c_cd_o:
629 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
632 case Intrinsic::amdgcn_image_gather4:
633 case Intrinsic::amdgcn_image_gather4_cl:
634 case Intrinsic::amdgcn_image_gather4_l:
635 case Intrinsic::amdgcn_image_gather4_b:
636 case Intrinsic::amdgcn_image_gather4_b_cl:
637 case Intrinsic::amdgcn_image_gather4_lz:
639 // Gather4 with comparison
640 case Intrinsic::amdgcn_image_gather4_c:
641 case Intrinsic::amdgcn_image_gather4_c_cl:
642 case Intrinsic::amdgcn_image_gather4_c_l:
643 case Intrinsic::amdgcn_image_gather4_c_b:
644 case Intrinsic::amdgcn_image_gather4_c_b_cl:
645 case Intrinsic::amdgcn_image_gather4_c_lz:
647 // Gather4 with offsets
648 case Intrinsic::amdgcn_image_gather4_o:
649 case Intrinsic::amdgcn_image_gather4_cl_o:
650 case Intrinsic::amdgcn_image_gather4_l_o:
651 case Intrinsic::amdgcn_image_gather4_b_o:
652 case Intrinsic::amdgcn_image_gather4_b_cl_o:
653 case Intrinsic::amdgcn_image_gather4_lz_o:
655 // Gather4 with comparison and offsets
656 case Intrinsic::amdgcn_image_gather4_c_o:
657 case Intrinsic::amdgcn_image_gather4_c_cl_o:
658 case Intrinsic::amdgcn_image_gather4_c_l_o:
659 case Intrinsic::amdgcn_image_gather4_c_b_o:
660 case Intrinsic::amdgcn_image_gather4_c_b_cl_o:
661 case Intrinsic::amdgcn_image_gather4_c_lz_o: {
662 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
663 Info.opc = ISD::INTRINSIC_W_CHAIN;
664 Info.memVT = MVT::getVT(CI.getType());
665 Info.ptrVal = MFI->getImagePSV(
666 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
667 CI.getArgOperand(1));
669 Info.flags = MachineMemOperand::MOLoad |
670 MachineMemOperand::MODereferenceable;
673 case Intrinsic::amdgcn_image_store:
674 case Intrinsic::amdgcn_image_store_mip: {
675 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
676 Info.opc = ISD::INTRINSIC_VOID;
677 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
678 Info.ptrVal = MFI->getImagePSV(
679 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
680 CI.getArgOperand(2));
681 Info.flags = MachineMemOperand::MOStore |
682 MachineMemOperand::MODereferenceable;
686 case Intrinsic::amdgcn_image_atomic_swap:
687 case Intrinsic::amdgcn_image_atomic_add:
688 case Intrinsic::amdgcn_image_atomic_sub:
689 case Intrinsic::amdgcn_image_atomic_smin:
690 case Intrinsic::amdgcn_image_atomic_umin:
691 case Intrinsic::amdgcn_image_atomic_smax:
692 case Intrinsic::amdgcn_image_atomic_umax:
693 case Intrinsic::amdgcn_image_atomic_and:
694 case Intrinsic::amdgcn_image_atomic_or:
695 case Intrinsic::amdgcn_image_atomic_xor:
696 case Intrinsic::amdgcn_image_atomic_inc:
697 case Intrinsic::amdgcn_image_atomic_dec: {
698 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
699 Info.opc = ISD::INTRINSIC_W_CHAIN;
700 Info.memVT = MVT::getVT(CI.getType());
701 Info.ptrVal = MFI->getImagePSV(
702 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
703 CI.getArgOperand(2));
705 Info.flags = MachineMemOperand::MOLoad |
706 MachineMemOperand::MOStore |
707 MachineMemOperand::MODereferenceable;
709 // XXX - Should this be volatile without known ordering?
710 Info.flags |= MachineMemOperand::MOVolatile;
713 case Intrinsic::amdgcn_image_atomic_cmpswap: {
714 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
715 Info.opc = ISD::INTRINSIC_W_CHAIN;
716 Info.memVT = MVT::getVT(CI.getType());
717 Info.ptrVal = MFI->getImagePSV(
718 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
719 CI.getArgOperand(3));
721 Info.flags = MachineMemOperand::MOLoad |
722 MachineMemOperand::MOStore |
723 MachineMemOperand::MODereferenceable;
725 // XXX - Should this be volatile without known ordering?
726 Info.flags |= MachineMemOperand::MOVolatile;
729 case Intrinsic::amdgcn_tbuffer_load:
730 case Intrinsic::amdgcn_buffer_load:
731 case Intrinsic::amdgcn_buffer_load_format: {
732 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
733 Info.opc = ISD::INTRINSIC_W_CHAIN;
734 Info.ptrVal = MFI->getBufferPSV(
735 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
736 CI.getArgOperand(0));
737 Info.memVT = MVT::getVT(CI.getType());
738 Info.flags = MachineMemOperand::MOLoad |
739 MachineMemOperand::MODereferenceable;
741 // There is a constant offset component, but there are additional register
742 // offsets which could break AA if we set the offset to anything non-0.
745 case Intrinsic::amdgcn_tbuffer_store:
746 case Intrinsic::amdgcn_buffer_store:
747 case Intrinsic::amdgcn_buffer_store_format: {
748 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
749 Info.opc = ISD::INTRINSIC_VOID;
750 Info.ptrVal = MFI->getBufferPSV(
751 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
752 CI.getArgOperand(1));
753 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
754 Info.flags = MachineMemOperand::MOStore |
755 MachineMemOperand::MODereferenceable;
758 case Intrinsic::amdgcn_buffer_atomic_swap:
759 case Intrinsic::amdgcn_buffer_atomic_add:
760 case Intrinsic::amdgcn_buffer_atomic_sub:
761 case Intrinsic::amdgcn_buffer_atomic_smin:
762 case Intrinsic::amdgcn_buffer_atomic_umin:
763 case Intrinsic::amdgcn_buffer_atomic_smax:
764 case Intrinsic::amdgcn_buffer_atomic_umax:
765 case Intrinsic::amdgcn_buffer_atomic_and:
766 case Intrinsic::amdgcn_buffer_atomic_or:
767 case Intrinsic::amdgcn_buffer_atomic_xor: {
768 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
769 Info.opc = ISD::INTRINSIC_W_CHAIN;
770 Info.ptrVal = MFI->getBufferPSV(
771 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
772 CI.getArgOperand(1));
773 Info.memVT = MVT::getVT(CI.getType());
774 Info.flags = MachineMemOperand::MOLoad |
775 MachineMemOperand::MOStore |
776 MachineMemOperand::MODereferenceable |
777 MachineMemOperand::MOVolatile;
780 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
781 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
782 Info.opc = ISD::INTRINSIC_W_CHAIN;
783 Info.ptrVal = MFI->getBufferPSV(
784 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
785 CI.getArgOperand(2));
786 Info.memVT = MVT::getVT(CI.getType());
787 Info.flags = MachineMemOperand::MOLoad |
788 MachineMemOperand::MOStore |
789 MachineMemOperand::MODereferenceable |
790 MachineMemOperand::MOVolatile;
798 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
799 SmallVectorImpl<Value*> &Ops,
800 Type *&AccessTy) const {
801 switch (II->getIntrinsicID()) {
802 case Intrinsic::amdgcn_atomic_inc:
803 case Intrinsic::amdgcn_atomic_dec: {
804 Value *Ptr = II->getArgOperand(0);
805 AccessTy = II->getType();
814 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
815 if (!Subtarget->hasFlatInstOffsets()) {
816 // Flat instructions do not have offsets, and only have the register
818 return AM.BaseOffs == 0 && AM.Scale == 0;
821 // GFX9 added a 13-bit signed offset. When using regular flat instructions,
822 // the sign bit is ignored and is treated as a 12-bit unsigned offset.
825 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
828 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
829 if (Subtarget->hasFlatGlobalInsts())
830 return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
832 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
833 // Assume the we will use FLAT for all global memory accesses
835 // FIXME: This assumption is currently wrong. On VI we still use
836 // MUBUF instructions for the r + i addressing mode. As currently
837 // implemented, the MUBUF instructions only work on buffer < 4GB.
838 // It may be possible to support > 4GB buffers with MUBUF instructions,
839 // by setting the stride value in the resource descriptor which would
840 // increase the size limit to (stride * 4GB). However, this is risky,
841 // because it has never been validated.
842 return isLegalFlatAddressingMode(AM);
845 return isLegalMUBUFAddressingMode(AM);
848 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
849 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
850 // additionally can do r + r + i with addr64. 32-bit has more addressing
851 // mode options. Depending on the resource constant, it can also do
852 // (i64 r0) + (i32 r1) * (i14 i).
854 // Private arrays end up using a scratch buffer most of the time, so also
855 // assume those use MUBUF instructions. Scratch loads / stores are currently
856 // implemented as mubuf instructions with offen bit set, so slightly
857 // different than the normal addr64.
858 if (!isUInt<12>(AM.BaseOffs))
861 // FIXME: Since we can split immediate into soffset and immediate offset,
862 // would it make sense to allow any immediate?
865 case 0: // r + i or just i, depending on HasBaseReg.
868 return true; // We have r + r or r + i.
875 // Allow 2 * r as r + r
876 // Or 2 * r + i is allowed as r + r + i.
878 default: // Don't allow n * r
883 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
884 const AddrMode &AM, Type *Ty,
885 unsigned AS, Instruction *I) const {
886 // No global is ever allowed as a base.
890 if (AS == AMDGPUASI.GLOBAL_ADDRESS)
891 return isLegalGlobalAddressingMode(AM);
893 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
894 // If the offset isn't a multiple of 4, it probably isn't going to be
895 // correctly aligned.
896 // FIXME: Can we get the real alignment here?
897 if (AM.BaseOffs % 4 != 0)
898 return isLegalMUBUFAddressingMode(AM);
900 // There are no SMRD extloads, so if we have to do a small type access we
901 // will use a MUBUF load.
902 // FIXME?: We also need to do this if unaligned, but we don't know the
904 if (DL.getTypeStoreSize(Ty) < 4)
905 return isLegalGlobalAddressingMode(AM);
907 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
908 // SMRD instructions have an 8-bit, dword offset on SI.
909 if (!isUInt<8>(AM.BaseOffs / 4))
911 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
912 // On CI+, this can also be a 32-bit literal constant offset. If it fits
913 // in 8-bits, it can use a smaller encoding.
914 if (!isUInt<32>(AM.BaseOffs / 4))
916 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
917 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
918 if (!isUInt<20>(AM.BaseOffs))
921 llvm_unreachable("unhandled generation");
923 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
926 if (AM.Scale == 1 && AM.HasBaseReg)
931 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
932 return isLegalMUBUFAddressingMode(AM);
933 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
934 AS == AMDGPUASI.REGION_ADDRESS) {
935 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
937 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
938 // an 8-bit dword offset but we don't know the alignment here.
939 if (!isUInt<16>(AM.BaseOffs))
942 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
945 if (AM.Scale == 1 && AM.HasBaseReg)
949 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
950 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
951 // For an unknown address space, this usually means that this is for some
952 // reason being used for pure arithmetic, and not based on some addressing
953 // computation. We don't have instructions that compute pointers with any
954 // addressing modes, so treat them as having no offset like flat
956 return isLegalFlatAddressingMode(AM);
958 llvm_unreachable("unhandled address space");
962 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
963 const SelectionDAG &DAG) const {
964 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
965 return (MemVT.getSizeInBits() <= 4 * 32);
966 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
967 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
968 return (MemVT.getSizeInBits() <= MaxPrivateBits);
969 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
970 return (MemVT.getSizeInBits() <= 2 * 32);
975 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
978 bool *IsFast) const {
982 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
983 // which isn't a simple VT.
984 // Until MVT is extended to handle this, simply check for the size and
985 // rely on the condition below: allow accesses if the size is a multiple of 4.
986 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
987 VT.getStoreSize() > 16)) {
991 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
992 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
993 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
994 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
995 // with adjacent offsets.
996 bool AlignedBy4 = (Align % 4 == 0);
998 *IsFast = AlignedBy4;
1003 // FIXME: We have to be conservative here and assume that flat operations
1004 // will access scratch. If we had access to the IR function, then we
1005 // could determine if any private memory was used in the function.
1006 if (!Subtarget->hasUnalignedScratchAccess() &&
1007 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
1008 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
1012 if (Subtarget->hasUnalignedBufferAccess()) {
1013 // If we have an uniform constant load, it still requires using a slow
1014 // buffer instruction if unaligned.
1016 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ?
1017 (Align % 4 == 0) : true;
1023 // Smaller than dword value must be aligned.
1024 if (VT.bitsLT(MVT::i32))
1027 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1028 // byte-address are ignored, thus forcing Dword alignment.
1029 // This applies to private, global, and constant memory.
1033 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1036 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
1037 unsigned SrcAlign, bool IsMemset,
1040 MachineFunction &MF) const {
1041 // FIXME: Should account for address space here.
1043 // The default fallback uses the private pointer size as a guess for a type to
1044 // use. Make sure we switch these to 64-bit accesses.
1046 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1049 if (Size >= 8 && DstAlign >= 4)
1056 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
1057 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
1058 AS == AMDGPUASI.FLAT_ADDRESS ||
1059 AS == AMDGPUASI.CONSTANT_ADDRESS;
1062 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1063 unsigned DestAS) const {
1064 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
1065 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
1068 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1069 const MemSDNode *MemNode = cast<MemSDNode>(N);
1070 const Value *Ptr = MemNode->getMemOperand()->getValue();
1071 const Instruction *I = dyn_cast<Instruction>(Ptr);
1072 return I && I->getMetadata("amdgpu.noclobber");
1075 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
1076 unsigned DestAS) const {
1077 // Flat -> private/local is a simple truncate.
1078 // Flat -> global is no-op
1079 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
1082 return isNoopAddrSpaceCast(SrcAS, DestAS);
1085 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1086 const MemSDNode *MemNode = cast<MemSDNode>(N);
1088 return AMDGPU::isUniformMMO(MemNode->getMemOperand());
1091 TargetLoweringBase::LegalizeTypeAction
1092 SITargetLowering::getPreferredVectorAction(EVT VT) const {
1093 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1094 return TypeSplitVector;
1096 return TargetLoweringBase::getPreferredVectorAction(VT);
1099 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1101 // FIXME: Could be smarter if called for vector constants.
1105 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1106 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1111 // These operations are done with 32-bit instructions anyway.
1116 // TODO: Extensions?
1123 // SimplifySetCC uses this function to determine whether or not it should
1124 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1125 if (VT == MVT::i1 && Op == ISD::SETCC)
1128 return TargetLowering::isTypeDesirableForOp(Op, VT);
1131 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1134 uint64_t Offset) const {
1135 const DataLayout &DL = DAG.getDataLayout();
1136 MachineFunction &MF = DAG.getMachineFunction();
1137 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1139 const ArgDescriptor *InputPtrReg;
1140 const TargetRegisterClass *RC;
1142 std::tie(InputPtrReg, RC)
1143 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1145 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1146 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
1147 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1148 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1150 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1151 DAG.getConstant(Offset, SL, PtrVT));
1154 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1155 const SDLoc &SL) const {
1156 auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
1157 uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
1158 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1161 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1162 const SDLoc &SL, SDValue Val,
1164 const ISD::InputArg *Arg) const {
1165 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1167 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1168 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1171 if (MemVT.isFloatingPoint())
1172 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1174 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1176 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1181 SDValue SITargetLowering::lowerKernargMemParameter(
1182 SelectionDAG &DAG, EVT VT, EVT MemVT,
1183 const SDLoc &SL, SDValue Chain,
1184 uint64_t Offset, bool Signed,
1185 const ISD::InputArg *Arg) const {
1186 const DataLayout &DL = DAG.getDataLayout();
1187 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1188 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
1189 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1191 unsigned Align = DL.getABITypeAlignment(Ty);
1193 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1194 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1195 MachineMemOperand::MONonTemporal |
1196 MachineMemOperand::MODereferenceable |
1197 MachineMemOperand::MOInvariant);
1199 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1200 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1203 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1204 const SDLoc &SL, SDValue Chain,
1205 const ISD::InputArg &Arg) const {
1206 MachineFunction &MF = DAG.getMachineFunction();
1207 MachineFrameInfo &MFI = MF.getFrameInfo();
1209 if (Arg.Flags.isByVal()) {
1210 unsigned Size = Arg.Flags.getByValSize();
1211 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1212 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1215 unsigned ArgOffset = VA.getLocMemOffset();
1216 unsigned ArgSize = VA.getValVT().getStoreSize();
1218 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1220 // Create load nodes to retrieve arguments from the stack.
1221 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1224 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1225 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1226 MVT MemVT = VA.getValVT();
1228 switch (VA.getLocInfo()) {
1231 case CCValAssign::BCvt:
1232 MemVT = VA.getLocVT();
1234 case CCValAssign::SExt:
1235 ExtType = ISD::SEXTLOAD;
1237 case CCValAssign::ZExt:
1238 ExtType = ISD::ZEXTLOAD;
1240 case CCValAssign::AExt:
1241 ExtType = ISD::EXTLOAD;
1245 ArgValue = DAG.getExtLoad(
1246 ExtType, SL, VA.getLocVT(), Chain, FIN,
1247 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1252 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1253 const SIMachineFunctionInfo &MFI,
1255 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1256 const ArgDescriptor *Reg;
1257 const TargetRegisterClass *RC;
1259 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1260 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1263 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1264 CallingConv::ID CallConv,
1265 ArrayRef<ISD::InputArg> Ins,
1267 FunctionType *FType,
1268 SIMachineFunctionInfo *Info) {
1269 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1270 const ISD::InputArg &Arg = Ins[I];
1272 // First check if it's a PS input addr.
1273 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
1274 !Arg.Flags.isByVal() && PSInputNum <= 15) {
1276 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
1277 // We can safely skip PS inputs.
1283 Info->markPSInputAllocated(PSInputNum);
1285 Info->markPSInputEnabled(PSInputNum);
1290 // Second split vertices into their elements.
1291 if (Arg.VT.isVector()) {
1292 ISD::InputArg NewArg = Arg;
1293 NewArg.Flags.setSplit();
1294 NewArg.VT = Arg.VT.getVectorElementType();
1296 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1297 // three or five element vertex only needs three or five registers,
1298 // NOT four or eight.
1299 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1300 unsigned NumElements = ParamType->getVectorNumElements();
1302 for (unsigned J = 0; J != NumElements; ++J) {
1303 Splits.push_back(NewArg);
1304 NewArg.PartOffset += NewArg.VT.getStoreSize();
1307 Splits.push_back(Arg);
1312 // Allocate special inputs passed in VGPRs.
1313 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1314 MachineFunction &MF,
1315 const SIRegisterInfo &TRI,
1316 SIMachineFunctionInfo &Info) {
1317 if (Info.hasWorkItemIDX()) {
1318 unsigned Reg = AMDGPU::VGPR0;
1319 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1321 CCInfo.AllocateReg(Reg);
1322 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1325 if (Info.hasWorkItemIDY()) {
1326 unsigned Reg = AMDGPU::VGPR1;
1327 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1329 CCInfo.AllocateReg(Reg);
1330 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1333 if (Info.hasWorkItemIDZ()) {
1334 unsigned Reg = AMDGPU::VGPR2;
1335 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1337 CCInfo.AllocateReg(Reg);
1338 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1342 // Try to allocate a VGPR at the end of the argument list, or if no argument
1343 // VGPRs are left allocating a stack slot.
1344 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1345 ArrayRef<MCPhysReg> ArgVGPRs
1346 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1347 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1348 if (RegIdx == ArgVGPRs.size()) {
1349 // Spill to stack required.
1350 int64_t Offset = CCInfo.AllocateStack(4, 4);
1352 return ArgDescriptor::createStack(Offset);
1355 unsigned Reg = ArgVGPRs[RegIdx];
1356 Reg = CCInfo.AllocateReg(Reg);
1357 assert(Reg != AMDGPU::NoRegister);
1359 MachineFunction &MF = CCInfo.getMachineFunction();
1360 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1361 return ArgDescriptor::createRegister(Reg);
1364 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1365 const TargetRegisterClass *RC,
1366 unsigned NumArgRegs) {
1367 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1368 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1369 if (RegIdx == ArgSGPRs.size())
1370 report_fatal_error("ran out of SGPRs for arguments");
1372 unsigned Reg = ArgSGPRs[RegIdx];
1373 Reg = CCInfo.AllocateReg(Reg);
1374 assert(Reg != AMDGPU::NoRegister);
1376 MachineFunction &MF = CCInfo.getMachineFunction();
1377 MF.addLiveIn(Reg, RC);
1378 return ArgDescriptor::createRegister(Reg);
1381 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1382 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1385 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1386 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1389 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1390 MachineFunction &MF,
1391 const SIRegisterInfo &TRI,
1392 SIMachineFunctionInfo &Info) {
1393 if (Info.hasWorkItemIDX())
1394 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1396 if (Info.hasWorkItemIDY())
1397 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1399 if (Info.hasWorkItemIDZ())
1400 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1403 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1404 MachineFunction &MF,
1405 const SIRegisterInfo &TRI,
1406 SIMachineFunctionInfo &Info) {
1407 auto &ArgInfo = Info.getArgInfo();
1409 // TODO: Unify handling with private memory pointers.
1411 if (Info.hasDispatchPtr())
1412 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1414 if (Info.hasQueuePtr())
1415 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1417 if (Info.hasKernargSegmentPtr())
1418 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1420 if (Info.hasDispatchID())
1421 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1423 // flat_scratch_init is not applicable for non-kernel functions.
1425 if (Info.hasWorkGroupIDX())
1426 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1428 if (Info.hasWorkGroupIDY())
1429 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1431 if (Info.hasWorkGroupIDZ())
1432 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1434 if (Info.hasImplicitArgPtr())
1435 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1438 // Allocate special inputs passed in user SGPRs.
1439 static void allocateHSAUserSGPRs(CCState &CCInfo,
1440 MachineFunction &MF,
1441 const SIRegisterInfo &TRI,
1442 SIMachineFunctionInfo &Info) {
1443 if (Info.hasImplicitBufferPtr()) {
1444 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1445 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1446 CCInfo.AllocateReg(ImplicitBufferPtrReg);
1449 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1450 if (Info.hasPrivateSegmentBuffer()) {
1451 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1452 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1453 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1456 if (Info.hasDispatchPtr()) {
1457 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1458 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1459 CCInfo.AllocateReg(DispatchPtrReg);
1462 if (Info.hasQueuePtr()) {
1463 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1464 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1465 CCInfo.AllocateReg(QueuePtrReg);
1468 if (Info.hasKernargSegmentPtr()) {
1469 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1470 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1471 CCInfo.AllocateReg(InputPtrReg);
1474 if (Info.hasDispatchID()) {
1475 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1476 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1477 CCInfo.AllocateReg(DispatchIDReg);
1480 if (Info.hasFlatScratchInit()) {
1481 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1482 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1483 CCInfo.AllocateReg(FlatScratchInitReg);
1486 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1487 // these from the dispatch pointer.
1490 // Allocate special input registers that are initialized per-wave.
1491 static void allocateSystemSGPRs(CCState &CCInfo,
1492 MachineFunction &MF,
1493 SIMachineFunctionInfo &Info,
1494 CallingConv::ID CallConv,
1496 if (Info.hasWorkGroupIDX()) {
1497 unsigned Reg = Info.addWorkGroupIDX();
1498 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1499 CCInfo.AllocateReg(Reg);
1502 if (Info.hasWorkGroupIDY()) {
1503 unsigned Reg = Info.addWorkGroupIDY();
1504 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1505 CCInfo.AllocateReg(Reg);
1508 if (Info.hasWorkGroupIDZ()) {
1509 unsigned Reg = Info.addWorkGroupIDZ();
1510 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1511 CCInfo.AllocateReg(Reg);
1514 if (Info.hasWorkGroupInfo()) {
1515 unsigned Reg = Info.addWorkGroupInfo();
1516 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1517 CCInfo.AllocateReg(Reg);
1520 if (Info.hasPrivateSegmentWaveByteOffset()) {
1521 // Scratch wave offset passed in system SGPR.
1522 unsigned PrivateSegmentWaveByteOffsetReg;
1525 PrivateSegmentWaveByteOffsetReg =
1526 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1528 // This is true if the scratch wave byte offset doesn't have a fixed
1530 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1531 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1532 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1535 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1537 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1538 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1542 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1543 MachineFunction &MF,
1544 const SIRegisterInfo &TRI,
1545 SIMachineFunctionInfo &Info) {
1546 // Now that we've figured out where the scratch register inputs are, see if
1547 // should reserve the arguments and use them directly.
1548 MachineFrameInfo &MFI = MF.getFrameInfo();
1549 bool HasStackObjects = MFI.hasStackObjects();
1551 // Record that we know we have non-spill stack objects so we don't need to
1552 // check all stack objects later.
1553 if (HasStackObjects)
1554 Info.setHasNonSpillStackObjects(true);
1556 // Everything live out of a block is spilled with fast regalloc, so it's
1557 // almost certain that spilling will be required.
1558 if (TM.getOptLevel() == CodeGenOpt::None)
1559 HasStackObjects = true;
1561 // For now assume stack access is needed in any callee functions, so we need
1562 // the scratch registers to pass in.
1563 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1565 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1566 if (ST.isAmdCodeObjectV2(MF)) {
1567 if (RequiresStackAccess) {
1568 // If we have stack objects, we unquestionably need the private buffer
1569 // resource. For the Code Object V2 ABI, this will be the first 4 user
1570 // SGPR inputs. We can reserve those and use them directly.
1572 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1573 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1574 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1576 if (MFI.hasCalls()) {
1577 // If we have calls, we need to keep the frame register in a register
1578 // that won't be clobbered by a call, so ensure it is copied somewhere.
1580 // This is not a problem for the scratch wave offset, because the same
1581 // registers are reserved in all functions.
1583 // FIXME: Nothing is really ensuring this is a call preserved register,
1584 // it's just selected from the end so it happens to be.
1585 unsigned ReservedOffsetReg
1586 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1587 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1589 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1590 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1591 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1594 unsigned ReservedBufferReg
1595 = TRI.reservedPrivateSegmentBufferReg(MF);
1596 unsigned ReservedOffsetReg
1597 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1599 // We tentatively reserve the last registers (skipping the last two
1600 // which may contain VCC). After register allocation, we'll replace
1601 // these with the ones immediately after those which were really
1602 // allocated. In the prologue copies will be inserted from the argument
1603 // to these reserved registers.
1604 Info.setScratchRSrcReg(ReservedBufferReg);
1605 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1608 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1610 // Without HSA, relocations are used for the scratch pointer and the
1611 // buffer resource setup is always inserted in the prologue. Scratch wave
1612 // offset is still in an input SGPR.
1613 Info.setScratchRSrcReg(ReservedBufferReg);
1615 if (HasStackObjects && !MFI.hasCalls()) {
1616 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1617 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1618 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1620 unsigned ReservedOffsetReg
1621 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1622 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1627 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1628 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1629 return !Info->isEntryFunction();
1632 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1636 void SITargetLowering::insertCopiesSplitCSR(
1637 MachineBasicBlock *Entry,
1638 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1639 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1641 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1645 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1646 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1647 MachineBasicBlock::iterator MBBI = Entry->begin();
1648 for (const MCPhysReg *I = IStart; *I; ++I) {
1649 const TargetRegisterClass *RC = nullptr;
1650 if (AMDGPU::SReg_64RegClass.contains(*I))
1651 RC = &AMDGPU::SGPR_64RegClass;
1652 else if (AMDGPU::SReg_32RegClass.contains(*I))
1653 RC = &AMDGPU::SGPR_32RegClass;
1655 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1657 unsigned NewVR = MRI->createVirtualRegister(RC);
1658 // Create copy from CSR to a virtual register.
1659 Entry->addLiveIn(*I);
1660 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1663 // Insert the copy-back instructions right before the terminator.
1664 for (auto *Exit : Exits)
1665 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1666 TII->get(TargetOpcode::COPY), *I)
1671 SDValue SITargetLowering::LowerFormalArguments(
1672 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1673 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1674 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1675 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1677 MachineFunction &MF = DAG.getMachineFunction();
1678 FunctionType *FType = MF.getFunction().getFunctionType();
1679 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1680 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1682 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1683 const Function &Fn = MF.getFunction();
1684 DiagnosticInfoUnsupported NoGraphicsHSA(
1685 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1686 DAG.getContext()->diagnose(NoGraphicsHSA);
1687 return DAG.getEntryNode();
1690 // Create stack objects that are used for emitting debugger prologue if
1691 // "amdgpu-debugger-emit-prologue" attribute was specified.
1692 if (ST.debuggerEmitPrologue())
1693 createDebuggerPrologueStackObjects(MF);
1695 SmallVector<ISD::InputArg, 16> Splits;
1696 SmallVector<CCValAssign, 16> ArgLocs;
1697 BitVector Skipped(Ins.size());
1698 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1701 bool IsShader = AMDGPU::isShader(CallConv);
1702 bool IsKernel = AMDGPU::isKernel(CallConv);
1703 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1706 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1707 // this when allocating argument fixed offsets.
1708 CCInfo.AllocateStack(4, 4);
1712 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1714 // At least one interpolation mode must be enabled or else the GPU will
1717 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1718 // set PSInputAddr, the user wants to enable some bits after the compilation
1719 // based on run-time states. Since we can't know what the final PSInputEna
1720 // will look like, so we shouldn't do anything here and the user should take
1721 // responsibility for the correct programming.
1723 // Otherwise, the following restrictions apply:
1724 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1725 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1727 if (CallConv == CallingConv::AMDGPU_PS) {
1728 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1729 ((Info->getPSInputAddr() & 0xF) == 0 &&
1730 Info->isPSInputAllocated(11))) {
1731 CCInfo.AllocateReg(AMDGPU::VGPR0);
1732 CCInfo.AllocateReg(AMDGPU::VGPR1);
1733 Info->markPSInputAllocated(0);
1734 Info->markPSInputEnabled(0);
1736 if (Subtarget->isAmdPalOS()) {
1737 // For isAmdPalOS, the user does not enable some bits after compilation
1738 // based on run-time states; the register values being generated here are
1739 // the final ones set in hardware. Therefore we need to apply the
1740 // workaround to PSInputAddr and PSInputEnable together. (The case where
1741 // a bit is set in PSInputAddr but not PSInputEnable is where the
1742 // frontend set up an input arg for a particular interpolation mode, but
1743 // nothing uses that input arg. Really we should have an earlier pass
1744 // that removes such an arg.)
1745 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1746 if ((PsInputBits & 0x7F) == 0 ||
1747 ((PsInputBits & 0xF) == 0 &&
1748 (PsInputBits >> 11 & 1)))
1749 Info->markPSInputEnabled(
1750 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1754 assert(!Info->hasDispatchPtr() &&
1755 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1756 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1757 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1758 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1759 !Info->hasWorkItemIDZ());
1760 } else if (IsKernel) {
1761 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1763 Splits.append(Ins.begin(), Ins.end());
1767 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1768 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1772 analyzeFormalArgumentsCompute(CCInfo, Ins);
1774 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1775 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1778 SmallVector<SDValue, 16> Chains;
1780 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1781 const ISD::InputArg &Arg = Ins[i];
1783 InVals.push_back(DAG.getUNDEF(Arg.VT));
1787 CCValAssign &VA = ArgLocs[ArgIdx++];
1788 MVT VT = VA.getLocVT();
1790 if (IsEntryFunc && VA.isMemLoc()) {
1792 EVT MemVT = VA.getLocVT();
1794 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1795 VA.getLocMemOffset();
1796 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1798 // The first 36 bytes of the input buffer contains information about
1799 // thread group and global sizes.
1800 SDValue Arg = lowerKernargMemParameter(
1801 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1802 Chains.push_back(Arg.getValue(1));
1805 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1806 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1807 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1808 // On SI local pointers are just offsets into LDS, so they are always
1809 // less than 16-bits. On CI and newer they could potentially be
1810 // real pointers, so we can't guarantee their size.
1811 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1812 DAG.getValueType(MVT::i16));
1815 InVals.push_back(Arg);
1817 } else if (!IsEntryFunc && VA.isMemLoc()) {
1818 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1819 InVals.push_back(Val);
1820 if (!Arg.Flags.isByVal())
1821 Chains.push_back(Val.getValue(1));
1825 assert(VA.isRegLoc() && "Parameter must be in a register!");
1827 unsigned Reg = VA.getLocReg();
1828 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1829 EVT ValVT = VA.getValVT();
1831 Reg = MF.addLiveIn(Reg, RC);
1832 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1834 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1835 // The return object should be reasonably addressable.
1837 // FIXME: This helps when the return is a real sret. If it is a
1838 // automatically inserted sret (i.e. CanLowerReturn returns false), an
1839 // extra copy is inserted in SelectionDAGBuilder which obscures this.
1840 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1841 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1842 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1845 // If this is an 8 or 16-bit value, it is really passed promoted
1846 // to 32 bits. Insert an assert[sz]ext to capture this, then
1847 // truncate to the right size.
1848 switch (VA.getLocInfo()) {
1849 case CCValAssign::Full:
1851 case CCValAssign::BCvt:
1852 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1854 case CCValAssign::SExt:
1855 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1856 DAG.getValueType(ValVT));
1857 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1859 case CCValAssign::ZExt:
1860 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1861 DAG.getValueType(ValVT));
1862 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1864 case CCValAssign::AExt:
1865 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1868 llvm_unreachable("Unknown loc info!");
1871 if (IsShader && Arg.VT.isVector()) {
1872 // Build a vector from the registers
1873 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1874 unsigned NumElements = ParamType->getVectorNumElements();
1876 SmallVector<SDValue, 4> Regs;
1877 Regs.push_back(Val);
1878 for (unsigned j = 1; j != NumElements; ++j) {
1879 Reg = ArgLocs[ArgIdx++].getLocReg();
1880 Reg = MF.addLiveIn(Reg, RC);
1882 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1883 Regs.push_back(Copy);
1886 // Fill up the missing vector elements
1887 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1888 Regs.append(NumElements, DAG.getUNDEF(VT));
1890 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1894 InVals.push_back(Val);
1898 // Special inputs come after user arguments.
1899 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1902 // Start adding system SGPRs.
1904 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1906 CCInfo.AllocateReg(Info->getScratchRSrcReg());
1907 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1908 CCInfo.AllocateReg(Info->getFrameOffsetReg());
1909 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
1912 auto &ArgUsageInfo =
1913 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1914 ArgUsageInfo.setFuncArgInfo(MF.getFunction(), Info->getArgInfo());
1916 unsigned StackArgSize = CCInfo.getNextStackOffset();
1917 Info->setBytesInStackArgArea(StackArgSize);
1919 return Chains.empty() ? Chain :
1920 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1923 // TODO: If return values can't fit in registers, we should return as many as
1924 // possible in registers before passing on stack.
1925 bool SITargetLowering::CanLowerReturn(
1926 CallingConv::ID CallConv,
1927 MachineFunction &MF, bool IsVarArg,
1928 const SmallVectorImpl<ISD::OutputArg> &Outs,
1929 LLVMContext &Context) const {
1930 // Replacing returns with sret/stack usage doesn't make sense for shaders.
1931 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1932 // for shaders. Vector types should be explicitly handled by CC.
1933 if (AMDGPU::isEntryFunctionCC(CallConv))
1936 SmallVector<CCValAssign, 16> RVLocs;
1937 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1938 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1942 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1944 const SmallVectorImpl<ISD::OutputArg> &Outs,
1945 const SmallVectorImpl<SDValue> &OutVals,
1946 const SDLoc &DL, SelectionDAG &DAG) const {
1947 MachineFunction &MF = DAG.getMachineFunction();
1948 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1950 if (AMDGPU::isKernel(CallConv)) {
1951 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1955 bool IsShader = AMDGPU::isShader(CallConv);
1957 Info->setIfReturnsVoid(Outs.size() == 0);
1958 bool IsWaveEnd = Info->returnsVoid() && IsShader;
1960 SmallVector<ISD::OutputArg, 48> Splits;
1961 SmallVector<SDValue, 48> SplitVals;
1963 // Split vectors into their elements.
1964 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1965 const ISD::OutputArg &Out = Outs[i];
1967 if (IsShader && Out.VT.isVector()) {
1968 MVT VT = Out.VT.getVectorElementType();
1969 ISD::OutputArg NewOut = Out;
1970 NewOut.Flags.setSplit();
1973 // We want the original number of vector elements here, e.g.
1974 // three or five, not four or eight.
1975 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1977 for (unsigned j = 0; j != NumElements; ++j) {
1978 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1979 DAG.getConstant(j, DL, MVT::i32));
1980 SplitVals.push_back(Elem);
1981 Splits.push_back(NewOut);
1982 NewOut.PartOffset += NewOut.VT.getStoreSize();
1985 SplitVals.push_back(OutVals[i]);
1986 Splits.push_back(Out);
1990 // CCValAssign - represent the assignment of the return value to a location.
1991 SmallVector<CCValAssign, 48> RVLocs;
1993 // CCState - Info about the registers and stack slots.
1994 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1997 // Analyze outgoing return values.
1998 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
2001 SmallVector<SDValue, 48> RetOps;
2002 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2004 // Add return address for callable functions.
2005 if (!Info->isEntryFunction()) {
2006 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2007 SDValue ReturnAddrReg = CreateLiveInRegister(
2008 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2010 // FIXME: Should be able to use a vreg here, but need a way to prevent it
2011 // from being allcoated to a CSR.
2013 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2016 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2017 Flag = Chain.getValue(1);
2019 RetOps.push_back(PhysReturnAddrReg);
2022 // Copy the result values into the output registers.
2023 for (unsigned i = 0, realRVLocIdx = 0;
2025 ++i, ++realRVLocIdx) {
2026 CCValAssign &VA = RVLocs[i];
2027 assert(VA.isRegLoc() && "Can only return in registers!");
2028 // TODO: Partially return in registers if return values don't fit.
2030 SDValue Arg = SplitVals[realRVLocIdx];
2032 // Copied from other backends.
2033 switch (VA.getLocInfo()) {
2034 case CCValAssign::Full:
2036 case CCValAssign::BCvt:
2037 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2039 case CCValAssign::SExt:
2040 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2042 case CCValAssign::ZExt:
2043 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2045 case CCValAssign::AExt:
2046 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2049 llvm_unreachable("Unknown loc info!");
2052 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2053 Flag = Chain.getValue(1);
2054 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2057 // FIXME: Does sret work properly?
2058 if (!Info->isEntryFunction()) {
2059 const SIRegisterInfo *TRI
2060 = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo();
2061 const MCPhysReg *I =
2062 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2065 if (AMDGPU::SReg_64RegClass.contains(*I))
2066 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2067 else if (AMDGPU::SReg_32RegClass.contains(*I))
2068 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2070 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2075 // Update chain and glue.
2078 RetOps.push_back(Flag);
2080 unsigned Opc = AMDGPUISD::ENDPGM;
2082 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2083 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2086 SDValue SITargetLowering::LowerCallResult(
2087 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2088 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2089 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2090 SDValue ThisVal) const {
2091 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2093 // Assign locations to each value returned by this call.
2094 SmallVector<CCValAssign, 16> RVLocs;
2095 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2097 CCInfo.AnalyzeCallResult(Ins, RetCC);
2099 // Copy all of the result registers out of their specified physreg.
2100 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2101 CCValAssign VA = RVLocs[i];
2104 if (VA.isRegLoc()) {
2105 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2106 Chain = Val.getValue(1);
2107 InFlag = Val.getValue(2);
2108 } else if (VA.isMemLoc()) {
2109 report_fatal_error("TODO: return values in memory");
2111 llvm_unreachable("unknown argument location type");
2113 switch (VA.getLocInfo()) {
2114 case CCValAssign::Full:
2116 case CCValAssign::BCvt:
2117 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2119 case CCValAssign::ZExt:
2120 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2121 DAG.getValueType(VA.getValVT()));
2122 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2124 case CCValAssign::SExt:
2125 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2126 DAG.getValueType(VA.getValVT()));
2127 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2129 case CCValAssign::AExt:
2130 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2133 llvm_unreachable("Unknown loc info!");
2136 InVals.push_back(Val);
2142 // Add code to pass special inputs required depending on used features separate
2143 // from the explicit user arguments present in the IR.
2144 void SITargetLowering::passSpecialInputs(
2145 CallLoweringInfo &CLI,
2146 const SIMachineFunctionInfo &Info,
2147 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2148 SmallVectorImpl<SDValue> &MemOpChains,
2150 SDValue StackPtr) const {
2151 // If we don't have a call site, this was a call inserted by
2152 // legalization. These can never use special inputs.
2156 const Function *CalleeFunc = CLI.CS.getCalledFunction();
2159 SelectionDAG &DAG = CLI.DAG;
2160 const SDLoc &DL = CLI.DL;
2162 const SISubtarget *ST = getSubtarget();
2163 const SIRegisterInfo *TRI = ST->getRegisterInfo();
2165 auto &ArgUsageInfo =
2166 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2167 const AMDGPUFunctionArgInfo &CalleeArgInfo
2168 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2170 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2172 // TODO: Unify with private memory register handling. This is complicated by
2173 // the fact that at least in kernels, the input argument is not necessarily
2174 // in the same location as the input.
2175 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2176 AMDGPUFunctionArgInfo::DISPATCH_PTR,
2177 AMDGPUFunctionArgInfo::QUEUE_PTR,
2178 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2179 AMDGPUFunctionArgInfo::DISPATCH_ID,
2180 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2181 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2182 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2183 AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2184 AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2185 AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2186 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2189 for (auto InputID : InputRegs) {
2190 const ArgDescriptor *OutgoingArg;
2191 const TargetRegisterClass *ArgRC;
2193 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2197 const ArgDescriptor *IncomingArg;
2198 const TargetRegisterClass *IncomingArgRC;
2199 std::tie(IncomingArg, IncomingArgRC)
2200 = CallerArgInfo.getPreloadedValue(InputID);
2201 assert(IncomingArgRC == ArgRC);
2203 // All special arguments are ints for now.
2204 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2208 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2210 // The implicit arg ptr is special because it doesn't have a corresponding
2211 // input for kernels, and is computed from the kernarg segment pointer.
2212 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2213 InputReg = getImplicitArgPtr(DAG, DL);
2216 if (OutgoingArg->isRegister()) {
2217 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2219 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr,
2221 OutgoingArg->getStackOffset());
2222 MemOpChains.push_back(ArgStore);
2227 static bool canGuaranteeTCO(CallingConv::ID CC) {
2228 return CC == CallingConv::Fast;
2231 /// Return true if we might ever do TCO for calls with this calling convention.
2232 static bool mayTailCallThisCC(CallingConv::ID CC) {
2234 case CallingConv::C:
2237 return canGuaranteeTCO(CC);
2241 bool SITargetLowering::isEligibleForTailCallOptimization(
2242 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2243 const SmallVectorImpl<ISD::OutputArg> &Outs,
2244 const SmallVectorImpl<SDValue> &OutVals,
2245 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2246 if (!mayTailCallThisCC(CalleeCC))
2249 MachineFunction &MF = DAG.getMachineFunction();
2250 const Function &CallerF = MF.getFunction();
2251 CallingConv::ID CallerCC = CallerF.getCallingConv();
2252 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2253 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2255 // Kernels aren't callable, and don't have a live in return address so it
2256 // doesn't make sense to do a tail call with entry functions.
2257 if (!CallerPreserved)
2260 bool CCMatch = CallerCC == CalleeCC;
2262 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2263 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2268 // TODO: Can we handle var args?
2272 for (const Argument &Arg : CallerF.args()) {
2273 if (Arg.hasByValAttr())
2277 LLVMContext &Ctx = *DAG.getContext();
2279 // Check that the call results are passed in the same way.
2280 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2281 CCAssignFnForCall(CalleeCC, IsVarArg),
2282 CCAssignFnForCall(CallerCC, IsVarArg)))
2285 // The callee has to preserve all registers the caller needs to preserve.
2287 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2288 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2292 // Nothing more to check if the callee is taking no arguments.
2296 SmallVector<CCValAssign, 16> ArgLocs;
2297 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2299 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2301 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2302 // If the stack arguments for this call do not fit into our own save area then
2303 // the call cannot be made tail.
2304 // TODO: Is this really necessary?
2305 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2308 const MachineRegisterInfo &MRI = MF.getRegInfo();
2309 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2312 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2313 if (!CI->isTailCall())
2316 const Function *ParentFn = CI->getParent()->getParent();
2317 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2320 auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2321 return (Attr.getValueAsString() != "true");
2324 // The wave scratch offset register is used as the global base pointer.
2325 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2326 SmallVectorImpl<SDValue> &InVals) const {
2327 SelectionDAG &DAG = CLI.DAG;
2328 const SDLoc &DL = CLI.DL;
2329 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2330 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2331 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2332 SDValue Chain = CLI.Chain;
2333 SDValue Callee = CLI.Callee;
2334 bool &IsTailCall = CLI.IsTailCall;
2335 CallingConv::ID CallConv = CLI.CallConv;
2336 bool IsVarArg = CLI.IsVarArg;
2337 bool IsSibCall = false;
2338 bool IsThisReturn = false;
2339 MachineFunction &MF = DAG.getMachineFunction();
2342 return lowerUnhandledCall(CLI, InVals,
2343 "unsupported call to variadic function ");
2346 if (!CLI.CS.getCalledFunction()) {
2347 return lowerUnhandledCall(CLI, InVals,
2348 "unsupported indirect call to function ");
2351 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2352 return lowerUnhandledCall(CLI, InVals,
2353 "unsupported required tail call to function ");
2356 // The first 4 bytes are reserved for the callee's emergency stack slot.
2357 const unsigned CalleeUsableStackOffset = 4;
2360 IsTailCall = isEligibleForTailCallOptimization(
2361 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2362 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2363 report_fatal_error("failed to perform tail call elimination on a call "
2364 "site marked musttail");
2367 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2369 // A sibling call is one where we're under the usual C ABI and not planning
2370 // to change that but can still do a tail call:
2371 if (!TailCallOpt && IsTailCall)
2378 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) {
2379 // FIXME: Remove this hack for function pointer types after removing
2380 // support of old address space mapping. In the new address space
2381 // mapping the pointer in default address space is 64 bit, therefore
2382 // does not need this hack.
2383 if (Callee.getValueType() == MVT::i32) {
2384 const GlobalValue *GV = GA->getGlobal();
2385 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false,
2386 GA->getTargetFlags());
2389 assert(Callee.getValueType() == MVT::i64);
2391 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2393 // Analyze operands of the call, assigning locations to each operand.
2394 SmallVector<CCValAssign, 16> ArgLocs;
2395 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2396 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2397 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2399 // Get a count of how many bytes are to be pushed on the stack.
2400 unsigned NumBytes = CCInfo.getNextStackOffset();
2403 // Since we're not changing the ABI to make this a tail call, the memory
2404 // operands are already available in the caller's incoming argument space.
2408 // FPDiff is the byte offset of the call's argument area from the callee's.
2409 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2410 // by this amount for a tail call. In a sibling call it must be 0 because the
2411 // caller will deallocate the entire stack and the callee still expects its
2412 // arguments to begin at SP+0. Completely unused for non-tail calls.
2414 MachineFrameInfo &MFI = MF.getFrameInfo();
2415 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2417 SDValue CallerSavedFP;
2419 // Adjust the stack pointer for the new arguments...
2420 // These operations are automatically eliminated by the prolog/epilog pass
2422 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2424 unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2426 // In the HSA case, this should be an identity copy.
2427 SDValue ScratchRSrcReg
2428 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2429 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2431 // TODO: Don't hardcode these registers and get from the callee function.
2432 SDValue ScratchWaveOffsetReg
2433 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2434 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2436 if (!Info->isEntryFunction()) {
2437 // Avoid clobbering this function's FP value. In the current convention
2438 // callee will overwrite this, so do save/restore around the call site.
2439 CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2440 Info->getFrameOffsetReg(), MVT::i32);
2444 // Stack pointer relative accesses are done by changing the offset SGPR. This
2445 // is just the VGPR offset component.
2446 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32);
2448 SmallVector<SDValue, 8> MemOpChains;
2449 MVT PtrVT = MVT::i32;
2451 // Walk the register/memloc assignments, inserting copies/loads.
2452 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2453 ++i, ++realArgIdx) {
2454 CCValAssign &VA = ArgLocs[i];
2455 SDValue Arg = OutVals[realArgIdx];
2457 // Promote the value if needed.
2458 switch (VA.getLocInfo()) {
2459 case CCValAssign::Full:
2461 case CCValAssign::BCvt:
2462 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2464 case CCValAssign::ZExt:
2465 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2467 case CCValAssign::SExt:
2468 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2470 case CCValAssign::AExt:
2471 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2473 case CCValAssign::FPExt:
2474 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2477 llvm_unreachable("Unknown loc info!");
2480 if (VA.isRegLoc()) {
2481 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2483 assert(VA.isMemLoc());
2486 MachinePointerInfo DstInfo;
2488 unsigned LocMemOffset = VA.getLocMemOffset();
2489 int32_t Offset = LocMemOffset;
2491 SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset);
2494 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2495 unsigned OpSize = Flags.isByVal() ?
2496 Flags.getByValSize() : VA.getValVT().getStoreSize();
2498 Offset = Offset + FPDiff;
2499 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2501 DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT),
2503 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2505 // Make sure any stack arguments overlapping with where we're storing
2506 // are loaded before this eventual operation. Otherwise they'll be
2509 // FIXME: Why is this really necessary? This seems to just result in a
2510 // lot of code to copy the stack and write them back to the same
2511 // locations, which are supposed to be immutable?
2512 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2515 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2518 if (Outs[i].Flags.isByVal()) {
2520 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2521 SDValue Cpy = DAG.getMemcpy(
2522 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2523 /*isVol = */ false, /*AlwaysInline = */ true,
2524 /*isTailCall = */ false, DstInfo,
2525 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2526 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS))));
2528 MemOpChains.push_back(Cpy);
2530 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
2531 MemOpChains.push_back(Store);
2536 // Copy special input registers after user input arguments.
2537 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr);
2539 if (!MemOpChains.empty())
2540 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2542 // Build a sequence of copy-to-reg nodes chained together with token chain
2543 // and flag operands which copy the outgoing args into the appropriate regs.
2545 for (auto &RegToPass : RegsToPass) {
2546 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2547 RegToPass.second, InFlag);
2548 InFlag = Chain.getValue(1);
2552 SDValue PhysReturnAddrReg;
2554 // Since the return is being combined with the call, we need to pass on the
2557 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2558 SDValue ReturnAddrReg = CreateLiveInRegister(
2559 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2561 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2563 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2564 InFlag = Chain.getValue(1);
2567 // We don't usually want to end the call-sequence here because we would tidy
2568 // the frame up *after* the call, however in the ABI-changing tail-call case
2569 // we've carefully laid out the parameters so that when sp is reset they'll be
2570 // in the correct location.
2571 if (IsTailCall && !IsSibCall) {
2572 Chain = DAG.getCALLSEQ_END(Chain,
2573 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2574 DAG.getTargetConstant(0, DL, MVT::i32),
2576 InFlag = Chain.getValue(1);
2579 std::vector<SDValue> Ops;
2580 Ops.push_back(Chain);
2581 Ops.push_back(Callee);
2584 // Each tail call may have to adjust the stack by a different amount, so
2585 // this information must travel along with the operation for eventual
2586 // consumption by emitEpilogue.
2587 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2589 Ops.push_back(PhysReturnAddrReg);
2592 // Add argument registers to the end of the list so that they are known live
2594 for (auto &RegToPass : RegsToPass) {
2595 Ops.push_back(DAG.getRegister(RegToPass.first,
2596 RegToPass.second.getValueType()));
2599 // Add a register mask operand representing the call-preserved registers.
2601 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo();
2602 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2603 assert(Mask && "Missing call preserved mask for calling convention");
2604 Ops.push_back(DAG.getRegisterMask(Mask));
2606 if (InFlag.getNode())
2607 Ops.push_back(InFlag);
2609 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2611 // If we're doing a tall call, use a TC_RETURN here rather than an
2612 // actual call instruction.
2614 MFI.setHasTailCall();
2615 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2618 // Returns a chain and a flag for retval copy to use.
2619 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2620 Chain = Call.getValue(0);
2621 InFlag = Call.getValue(1);
2623 if (CallerSavedFP) {
2624 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2625 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2626 InFlag = Chain.getValue(1);
2629 uint64_t CalleePopBytes = NumBytes;
2630 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2631 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2634 InFlag = Chain.getValue(1);
2636 // Handle result values, copying them out of physregs into vregs that we
2638 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2639 InVals, IsThisReturn,
2640 IsThisReturn ? OutVals[0] : SDValue());
2643 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2644 SelectionDAG &DAG) const {
2645 unsigned Reg = StringSwitch<unsigned>(RegName)
2646 .Case("m0", AMDGPU::M0)
2647 .Case("exec", AMDGPU::EXEC)
2648 .Case("exec_lo", AMDGPU::EXEC_LO)
2649 .Case("exec_hi", AMDGPU::EXEC_HI)
2650 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2651 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2652 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2653 .Default(AMDGPU::NoRegister);
2655 if (Reg == AMDGPU::NoRegister) {
2656 report_fatal_error(Twine("invalid register name \""
2657 + StringRef(RegName) + "\"."));
2661 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
2662 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2663 report_fatal_error(Twine("invalid register \""
2664 + StringRef(RegName) + "\" for subtarget."));
2669 case AMDGPU::EXEC_LO:
2670 case AMDGPU::EXEC_HI:
2671 case AMDGPU::FLAT_SCR_LO:
2672 case AMDGPU::FLAT_SCR_HI:
2673 if (VT.getSizeInBits() == 32)
2677 case AMDGPU::FLAT_SCR:
2678 if (VT.getSizeInBits() == 64)
2682 llvm_unreachable("missing register type checking");
2685 report_fatal_error(Twine("invalid type for register \""
2686 + StringRef(RegName) + "\"."));
2689 // If kill is not the last instruction, split the block so kill is always a
2690 // proper terminator.
2691 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2692 MachineBasicBlock *BB) const {
2693 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2695 MachineBasicBlock::iterator SplitPoint(&MI);
2698 if (SplitPoint == BB->end()) {
2699 // Don't bother with a new block.
2700 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2704 MachineFunction *MF = BB->getParent();
2705 MachineBasicBlock *SplitBB
2706 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2708 MF->insert(++MachineFunction::iterator(BB), SplitBB);
2709 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2711 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2712 BB->addSuccessor(SplitBB);
2714 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2718 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2719 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2720 // will only do one iteration. In the worst case, this will loop 64 times.
2722 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2723 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2724 const SIInstrInfo *TII,
2725 MachineRegisterInfo &MRI,
2726 MachineBasicBlock &OrigBB,
2727 MachineBasicBlock &LoopBB,
2729 const MachineOperand &IdxReg,
2733 unsigned InitSaveExecReg,
2735 bool UseGPRIdxMode) {
2736 MachineBasicBlock::iterator I = LoopBB.begin();
2738 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2739 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2740 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2741 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2743 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2749 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2750 .addReg(InitSaveExecReg)
2755 // Read the next variant <- also loop target.
2756 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2757 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2759 // Compare the just read M0 value to all possible Idx values.
2760 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2761 .addReg(CurrentIdxReg)
2762 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2764 if (UseGPRIdxMode) {
2767 IdxReg = CurrentIdxReg;
2769 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2770 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2771 .addReg(CurrentIdxReg, RegState::Kill)
2775 MachineInstr *SetIdx =
2776 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
2777 .addReg(IdxReg, RegState::Kill);
2778 SetIdx->getOperand(2).setIsUndef();
2780 // Move index from VCC into M0
2782 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2783 .addReg(CurrentIdxReg, RegState::Kill);
2785 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2786 .addReg(CurrentIdxReg, RegState::Kill)
2791 // Update EXEC, save the original EXEC value to VCC.
2792 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2793 .addReg(CondReg, RegState::Kill);
2795 MRI.setSimpleHint(NewExec, CondReg);
2797 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2798 MachineInstr *InsertPt =
2799 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2800 .addReg(AMDGPU::EXEC)
2803 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2806 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2807 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2810 return InsertPt->getIterator();
2813 // This has slightly sub-optimal regalloc when the source vector is killed by
2814 // the read. The register allocator does not understand that the kill is
2815 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2816 // subregister from it, using 1 more VGPR than necessary. This was saved when
2817 // this was expanded after register allocation.
2818 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2819 MachineBasicBlock &MBB,
2821 unsigned InitResultReg,
2824 bool UseGPRIdxMode) {
2825 MachineFunction *MF = MBB.getParent();
2826 MachineRegisterInfo &MRI = MF->getRegInfo();
2827 const DebugLoc &DL = MI.getDebugLoc();
2828 MachineBasicBlock::iterator I(&MI);
2830 unsigned DstReg = MI.getOperand(0).getReg();
2831 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2832 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2834 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2836 // Save the EXEC mask
2837 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2838 .addReg(AMDGPU::EXEC);
2840 // To insert the loop we need to split the block. Move everything after this
2841 // point to a new block, and insert a new empty block between the two.
2842 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2843 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2844 MachineFunction::iterator MBBI(MBB);
2847 MF->insert(MBBI, LoopBB);
2848 MF->insert(MBBI, RemainderBB);
2850 LoopBB->addSuccessor(LoopBB);
2851 LoopBB->addSuccessor(RemainderBB);
2853 // Move the rest of the block into a new block.
2854 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2855 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2857 MBB.addSuccessor(LoopBB);
2859 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2861 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2862 InitResultReg, DstReg, PhiReg, TmpExec,
2863 Offset, UseGPRIdxMode);
2865 MachineBasicBlock::iterator First = RemainderBB->begin();
2866 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2872 // Returns subreg index, offset
2873 static std::pair<unsigned, int>
2874 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2875 const TargetRegisterClass *SuperRC,
2878 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2880 // Skip out of bounds offsets, or else we would end up using an undefined
2882 if (Offset >= NumElts || Offset < 0)
2883 return std::make_pair(AMDGPU::sub0, Offset);
2885 return std::make_pair(AMDGPU::sub0 + Offset, 0);
2888 // Return true if the index is an SGPR and was set.
2889 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
2890 MachineRegisterInfo &MRI,
2894 bool IsIndirectSrc) {
2895 MachineBasicBlock *MBB = MI.getParent();
2896 const DebugLoc &DL = MI.getDebugLoc();
2897 MachineBasicBlock::iterator I(&MI);
2899 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2900 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2902 assert(Idx->getReg() != AMDGPU::NoRegister);
2904 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2907 if (UseGPRIdxMode) {
2908 unsigned IdxMode = IsIndirectSrc ?
2909 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2911 MachineInstr *SetOn =
2912 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2916 SetOn->getOperand(3).setIsUndef();
2918 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2919 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
2922 MachineInstr *SetOn =
2923 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2924 .addReg(Tmp, RegState::Kill)
2927 SetOn->getOperand(3).setIsUndef();
2934 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2937 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2945 // Control flow needs to be inserted if indexing with a VGPR.
2946 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
2947 MachineBasicBlock &MBB,
2948 const SISubtarget &ST) {
2949 const SIInstrInfo *TII = ST.getInstrInfo();
2950 const SIRegisterInfo &TRI = TII->getRegisterInfo();
2951 MachineFunction *MF = MBB.getParent();
2952 MachineRegisterInfo &MRI = MF->getRegInfo();
2954 unsigned Dst = MI.getOperand(0).getReg();
2955 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
2956 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2958 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
2961 std::tie(SubReg, Offset)
2962 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
2964 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2966 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
2967 MachineBasicBlock::iterator I(&MI);
2968 const DebugLoc &DL = MI.getDebugLoc();
2970 if (UseGPRIdxMode) {
2971 // TODO: Look at the uses to avoid the copy. This may require rescheduling
2972 // to avoid interfering with other uses, so probably requires a new
2973 // optimization pass.
2974 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
2975 .addReg(SrcReg, RegState::Undef, SubReg)
2976 .addReg(SrcReg, RegState::Implicit)
2977 .addReg(AMDGPU::M0, RegState::Implicit);
2978 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2980 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
2981 .addReg(SrcReg, RegState::Undef, SubReg)
2982 .addReg(SrcReg, RegState::Implicit);
2985 MI.eraseFromParent();
2990 const DebugLoc &DL = MI.getDebugLoc();
2991 MachineBasicBlock::iterator I(&MI);
2993 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2994 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2996 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
2998 if (UseGPRIdxMode) {
2999 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3000 .addImm(0) // Reset inside loop.
3001 .addImm(VGPRIndexMode::SRC0_ENABLE);
3002 SetOn->getOperand(3).setIsUndef();
3004 // Disable again after the loop.
3005 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3008 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
3009 MachineBasicBlock *LoopBB = InsPt->getParent();
3011 if (UseGPRIdxMode) {
3012 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3013 .addReg(SrcReg, RegState::Undef, SubReg)
3014 .addReg(SrcReg, RegState::Implicit)
3015 .addReg(AMDGPU::M0, RegState::Implicit);
3017 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3018 .addReg(SrcReg, RegState::Undef, SubReg)
3019 .addReg(SrcReg, RegState::Implicit);
3022 MI.eraseFromParent();
3027 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3028 const TargetRegisterClass *VecRC) {
3029 switch (TRI.getRegSizeInBits(*VecRC)) {
3031 return AMDGPU::V_MOVRELD_B32_V1;
3033 return AMDGPU::V_MOVRELD_B32_V2;
3034 case 128: // 16 bytes
3035 return AMDGPU::V_MOVRELD_B32_V4;
3036 case 256: // 32 bytes
3037 return AMDGPU::V_MOVRELD_B32_V8;
3038 case 512: // 64 bytes
3039 return AMDGPU::V_MOVRELD_B32_V16;
3041 llvm_unreachable("unsupported size for MOVRELD pseudos");
3045 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3046 MachineBasicBlock &MBB,
3047 const SISubtarget &ST) {
3048 const SIInstrInfo *TII = ST.getInstrInfo();
3049 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3050 MachineFunction *MF = MBB.getParent();
3051 MachineRegisterInfo &MRI = MF->getRegInfo();
3053 unsigned Dst = MI.getOperand(0).getReg();
3054 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3055 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3056 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3057 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3058 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3060 // This can be an immediate, but will be folded later.
3061 assert(Val->getReg());
3064 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3067 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3069 if (Idx->getReg() == AMDGPU::NoRegister) {
3070 MachineBasicBlock::iterator I(&MI);
3071 const DebugLoc &DL = MI.getDebugLoc();
3073 assert(Offset == 0);
3075 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3080 MI.eraseFromParent();
3084 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3085 MachineBasicBlock::iterator I(&MI);
3086 const DebugLoc &DL = MI.getDebugLoc();
3088 if (UseGPRIdxMode) {
3089 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3090 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3092 .addReg(Dst, RegState::ImplicitDefine)
3093 .addReg(SrcVec->getReg(), RegState::Implicit)
3094 .addReg(AMDGPU::M0, RegState::Implicit);
3096 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3098 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3100 BuildMI(MBB, I, DL, MovRelDesc)
3101 .addReg(Dst, RegState::Define)
3102 .addReg(SrcVec->getReg())
3104 .addImm(SubReg - AMDGPU::sub0);
3107 MI.eraseFromParent();
3112 MRI.clearKillFlags(Val->getReg());
3114 const DebugLoc &DL = MI.getDebugLoc();
3116 if (UseGPRIdxMode) {
3117 MachineBasicBlock::iterator I(&MI);
3119 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3120 .addImm(0) // Reset inside loop.
3121 .addImm(VGPRIndexMode::DST_ENABLE);
3122 SetOn->getOperand(3).setIsUndef();
3124 // Disable again after the loop.
3125 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3128 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3130 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3131 Offset, UseGPRIdxMode);
3132 MachineBasicBlock *LoopBB = InsPt->getParent();
3134 if (UseGPRIdxMode) {
3135 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3136 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3138 .addReg(Dst, RegState::ImplicitDefine)
3139 .addReg(PhiReg, RegState::Implicit)
3140 .addReg(AMDGPU::M0, RegState::Implicit);
3142 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3144 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3145 .addReg(Dst, RegState::Define)
3148 .addImm(SubReg - AMDGPU::sub0);
3151 MI.eraseFromParent();
3156 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3157 MachineInstr &MI, MachineBasicBlock *BB) const {
3159 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3160 MachineFunction *MF = BB->getParent();
3161 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3163 if (TII->isMIMG(MI)) {
3164 if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3165 report_fatal_error("missing mem operand from MIMG instruction");
3167 // Add a memoperand for mimg instructions so that they aren't assumed to
3168 // be ordered memory instuctions.
3173 switch (MI.getOpcode()) {
3174 case AMDGPU::S_ADD_U64_PSEUDO:
3175 case AMDGPU::S_SUB_U64_PSEUDO: {
3176 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3177 const DebugLoc &DL = MI.getDebugLoc();
3179 MachineOperand &Dest = MI.getOperand(0);
3180 MachineOperand &Src0 = MI.getOperand(1);
3181 MachineOperand &Src1 = MI.getOperand(2);
3183 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3184 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3186 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3187 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3188 &AMDGPU::SReg_32_XM0RegClass);
3189 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3190 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3191 &AMDGPU::SReg_32_XM0RegClass);
3193 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3194 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3195 &AMDGPU::SReg_32_XM0RegClass);
3196 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3197 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3198 &AMDGPU::SReg_32_XM0RegClass);
3200 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3202 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3203 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3204 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3207 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3210 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3212 .addImm(AMDGPU::sub0)
3214 .addImm(AMDGPU::sub1);
3215 MI.eraseFromParent();
3218 case AMDGPU::SI_INIT_M0: {
3219 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3220 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3221 .add(MI.getOperand(0));
3222 MI.eraseFromParent();
3225 case AMDGPU::SI_INIT_EXEC:
3226 // This should be before all vector instructions.
3227 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3229 .addImm(MI.getOperand(0).getImm());
3230 MI.eraseFromParent();
3233 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3234 // Extract the thread count from an SGPR input and set EXEC accordingly.
3235 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3237 // S_BFE_U32 count, input, {shift, 7}
3238 // S_BFM_B64 exec, count, 0
3239 // S_CMP_EQ_U32 count, 64
3240 // S_CMOV_B64 exec, -1
3241 MachineInstr *FirstMI = &*BB->begin();
3242 MachineRegisterInfo &MRI = MF->getRegInfo();
3243 unsigned InputReg = MI.getOperand(0).getReg();
3244 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3247 // Move the COPY of the input reg to the beginning, so that we can use it.
3248 for (auto I = BB->begin(); I != &MI; I++) {
3249 if (I->getOpcode() != TargetOpcode::COPY ||
3250 I->getOperand(0).getReg() != InputReg)
3254 FirstMI = &*++BB->begin();
3256 I->removeFromParent();
3257 BB->insert(FirstMI, &*I);
3265 // This should be before all vector instructions.
3266 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3268 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3269 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3273 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3274 .addReg(CountReg, RegState::Kill)
3276 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3279 MI.eraseFromParent();
3283 case AMDGPU::GET_GROUPSTATICSIZE: {
3284 DebugLoc DL = MI.getDebugLoc();
3285 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3286 .add(MI.getOperand(0))
3287 .addImm(MFI->getLDSSize());
3288 MI.eraseFromParent();
3291 case AMDGPU::SI_INDIRECT_SRC_V1:
3292 case AMDGPU::SI_INDIRECT_SRC_V2:
3293 case AMDGPU::SI_INDIRECT_SRC_V4:
3294 case AMDGPU::SI_INDIRECT_SRC_V8:
3295 case AMDGPU::SI_INDIRECT_SRC_V16:
3296 return emitIndirectSrc(MI, *BB, *getSubtarget());
3297 case AMDGPU::SI_INDIRECT_DST_V1:
3298 case AMDGPU::SI_INDIRECT_DST_V2:
3299 case AMDGPU::SI_INDIRECT_DST_V4:
3300 case AMDGPU::SI_INDIRECT_DST_V8:
3301 case AMDGPU::SI_INDIRECT_DST_V16:
3302 return emitIndirectDst(MI, *BB, *getSubtarget());
3303 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3304 case AMDGPU::SI_KILL_I1_PSEUDO:
3305 return splitKillBlock(MI, BB);
3306 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3307 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3309 unsigned Dst = MI.getOperand(0).getReg();
3310 unsigned Src0 = MI.getOperand(1).getReg();
3311 unsigned Src1 = MI.getOperand(2).getReg();
3312 const DebugLoc &DL = MI.getDebugLoc();
3313 unsigned SrcCond = MI.getOperand(3).getReg();
3315 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3316 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3317 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3319 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3321 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3322 .addReg(Src0, 0, AMDGPU::sub0)
3323 .addReg(Src1, 0, AMDGPU::sub0)
3324 .addReg(SrcCondCopy);
3325 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3326 .addReg(Src0, 0, AMDGPU::sub1)
3327 .addReg(Src1, 0, AMDGPU::sub1)
3328 .addReg(SrcCondCopy);
3330 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3332 .addImm(AMDGPU::sub0)
3334 .addImm(AMDGPU::sub1);
3335 MI.eraseFromParent();
3338 case AMDGPU::SI_BR_UNDEF: {
3339 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3340 const DebugLoc &DL = MI.getDebugLoc();
3341 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3342 .add(MI.getOperand(0));
3343 Br->getOperand(1).setIsUndef(true); // read undef SCC
3344 MI.eraseFromParent();
3347 case AMDGPU::ADJCALLSTACKUP:
3348 case AMDGPU::ADJCALLSTACKDOWN: {
3349 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3350 MachineInstrBuilder MIB(*MF, &MI);
3351 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3352 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
3355 case AMDGPU::SI_CALL_ISEL:
3356 case AMDGPU::SI_TCRETURN_ISEL: {
3357 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3358 const DebugLoc &DL = MI.getDebugLoc();
3359 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3361 MachineRegisterInfo &MRI = MF->getRegInfo();
3362 unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3363 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3364 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3366 const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3368 MachineInstrBuilder MIB;
3369 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3370 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3371 .add(MI.getOperand(0))
3372 .addGlobalAddress(G);
3374 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3375 .add(MI.getOperand(0))
3376 .addGlobalAddress(G);
3378 // There is an additional imm operand for tcreturn, but it should be in the
3379 // right place already.
3382 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3383 MIB.add(MI.getOperand(I));
3385 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3386 MI.eraseFromParent();
3390 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3394 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3395 return isTypeLegal(VT.getScalarType());
3398 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3399 // This currently forces unfolding various combinations of fsub into fma with
3400 // free fneg'd operands. As long as we have fast FMA (controlled by
3401 // isFMAFasterThanFMulAndFAdd), we should perform these.
3403 // When fma is quarter rate, for f64 where add / sub are at best half rate,
3404 // most of these combines appear to be cycle neutral but save on instruction
3405 // count / code size.
3409 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3411 if (!VT.isVector()) {
3414 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3417 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3418 // TODO: Should i16 be used always if legal? For now it would force VALU
3420 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3423 // Answering this is somewhat tricky and depends on the specific device which
3424 // have different rates for fma or all f64 operations.
3426 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3427 // regardless of which device (although the number of cycles differs between
3428 // devices), so it is always profitable for f64.
3430 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3431 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3432 // which we can always do even without fused FP ops since it returns the same
3433 // result as the separate operations and since it is always full
3434 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3435 // however does not support denormals, so we do report fma as faster if we have
3436 // a fast fma device and require denormals.
3438 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3439 VT = VT.getScalarType();
3441 switch (VT.getSimpleVT().SimpleTy) {
3443 // This is as fast on some subtargets. However, we always have full rate f32
3444 // mad available which returns the same result as the separate operations
3445 // which we should prefer over fma. We can't use this if we want to support
3446 // denormals, so only report this in these cases.
3447 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
3451 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3459 //===----------------------------------------------------------------------===//
3460 // Custom DAG Lowering Operations
3461 //===----------------------------------------------------------------------===//
3463 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3464 switch (Op.getOpcode()) {
3465 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3466 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3468 SDValue Result = LowerLOAD(Op, DAG);
3469 assert((!Result.getNode() ||
3470 Result.getNode()->getNumValues() == 2) &&
3471 "Load should return a value and a chain");
3477 return LowerTrig(Op, DAG);
3478 case ISD::SELECT: return LowerSELECT(Op, DAG);
3479 case ISD::FDIV: return LowerFDIV(Op, DAG);
3480 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3481 case ISD::STORE: return LowerSTORE(Op, DAG);
3482 case ISD::GlobalAddress: {
3483 MachineFunction &MF = DAG.getMachineFunction();
3484 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3485 return LowerGlobalAddress(MFI, Op, DAG);
3487 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3488 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3489 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3490 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3491 case ISD::INSERT_VECTOR_ELT:
3492 return lowerINSERT_VECTOR_ELT(Op, DAG);
3493 case ISD::EXTRACT_VECTOR_ELT:
3494 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3496 return lowerFP_ROUND(Op, DAG);
3498 case ISD::DEBUGTRAP:
3499 return lowerTRAP(Op, DAG);
3504 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3505 SmallVectorImpl<SDValue> &Results,
3506 SelectionDAG &DAG) const {
3507 switch (N->getOpcode()) {
3508 case ISD::INSERT_VECTOR_ELT: {
3509 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3510 Results.push_back(Res);
3513 case ISD::EXTRACT_VECTOR_ELT: {
3514 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3515 Results.push_back(Res);
3518 case ISD::INTRINSIC_WO_CHAIN: {
3519 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3520 if (IID == Intrinsic::amdgcn_cvt_pkrtz) {
3521 SDValue Src0 = N->getOperand(1);
3522 SDValue Src1 = N->getOperand(2);
3524 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3526 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3533 EVT VT = N->getValueType(0);
3534 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3535 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3536 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3538 EVT SelectVT = NewVT;
3539 if (NewVT.bitsLT(MVT::i32)) {
3540 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3541 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3542 SelectVT = MVT::i32;
3545 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3546 N->getOperand(0), LHS, RHS);
3548 if (NewVT != SelectVT)
3549 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3550 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3558 /// \brief Helper function for LowerBRCOND
3559 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3561 SDNode *Parent = Value.getNode();
3562 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3565 if (I.getUse().get() != Value)
3568 if (I->getOpcode() == Opcode)
3574 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3575 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3576 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3577 case Intrinsic::amdgcn_if:
3578 return AMDGPUISD::IF;
3579 case Intrinsic::amdgcn_else:
3580 return AMDGPUISD::ELSE;
3581 case Intrinsic::amdgcn_loop:
3582 return AMDGPUISD::LOOP;
3583 case Intrinsic::amdgcn_end_cf:
3584 llvm_unreachable("should not occur");
3590 // break, if_break, else_break are all only used as inputs to loop, not
3591 // directly as branch conditions.
3595 void SITargetLowering::createDebuggerPrologueStackObjects(
3596 MachineFunction &MF) const {
3597 // Create stack objects that are used for emitting debugger prologue.
3599 // Debugger prologue writes work group IDs and work item IDs to scratch memory
3600 // at fixed location in the following format:
3601 // offset 0: work group ID x
3602 // offset 4: work group ID y
3603 // offset 8: work group ID z
3604 // offset 16: work item ID x
3605 // offset 20: work item ID y
3606 // offset 24: work item ID z
3607 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3610 // For each dimension:
3611 for (unsigned i = 0; i < 3; ++i) {
3612 // Create fixed stack object for work group ID.
3613 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
3614 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
3615 // Create fixed stack object for work item ID.
3616 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
3617 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
3621 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
3622 const Triple &TT = getTargetMachine().getTargetTriple();
3623 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
3624 AMDGPU::shouldEmitConstantsToTextSection(TT);
3627 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
3628 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
3629 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
3630 !shouldEmitFixup(GV) &&
3631 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3634 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
3635 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
3638 /// This transforms the control flow intrinsics to get the branch destination as
3639 /// last parameter, also switches branch target with BR if the need arise
3640 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
3641 SelectionDAG &DAG) const {
3644 SDNode *Intr = BRCOND.getOperand(1).getNode();
3645 SDValue Target = BRCOND.getOperand(2);
3646 SDNode *BR = nullptr;
3647 SDNode *SetCC = nullptr;
3649 if (Intr->getOpcode() == ISD::SETCC) {
3650 // As long as we negate the condition everything is fine
3652 Intr = SetCC->getOperand(0).getNode();
3655 // Get the target from BR if we don't negate the condition
3656 BR = findUser(BRCOND, ISD::BR);
3657 Target = BR->getOperand(1);
3660 // FIXME: This changes the types of the intrinsics instead of introducing new
3661 // nodes with the correct types.
3662 // e.g. llvm.amdgcn.loop
3664 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
3665 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
3667 unsigned CFNode = isCFIntrinsic(Intr);
3669 // This is a uniform branch so we don't need to legalize.
3673 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
3674 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
3677 (SetCC->getConstantOperandVal(1) == 1 &&
3678 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
3681 // operands of the new intrinsic call
3682 SmallVector<SDValue, 4> Ops;
3684 Ops.push_back(BRCOND.getOperand(0));
3686 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
3687 Ops.push_back(Target);
3689 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
3691 // build the new intrinsic call
3692 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
3697 BRCOND.getOperand(0)
3700 Result = DAG.getMergeValues(Ops, DL).getNode();
3704 // Give the branch instruction our target
3707 BRCOND.getOperand(2)
3709 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
3710 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
3711 BR = NewBR.getNode();
3714 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
3716 // Copy the intrinsic results to registers
3717 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
3718 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
3722 Chain = DAG.getCopyToReg(
3724 CopyToReg->getOperand(1),
3725 SDValue(Result, i - 1),
3728 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
3731 // Remove the old intrinsic from the chain
3732 DAG.ReplaceAllUsesOfValueWith(
3733 SDValue(Intr, Intr->getNumValues() - 1),
3734 Intr->getOperand(0));
3739 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
3743 return Op.getValueType().bitsLE(VT) ?
3744 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
3745 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
3748 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
3749 assert(Op.getValueType() == MVT::f16 &&
3750 "Do not know how to custom lower FP_ROUND for non-f16 type");
3752 SDValue Src = Op.getOperand(0);
3753 EVT SrcVT = Src.getValueType();
3754 if (SrcVT != MVT::f64)
3759 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
3760 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
3761 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
3764 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
3766 MachineFunction &MF = DAG.getMachineFunction();
3767 SDValue Chain = Op.getOperand(0);
3769 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ?
3770 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap;
3772 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
3773 Subtarget->isTrapHandlerEnabled()) {
3774 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3775 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3776 assert(UserSGPR != AMDGPU::NoRegister);
3778 SDValue QueuePtr = CreateLiveInRegister(
3779 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3781 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
3783 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
3784 QueuePtr, SDValue());
3788 DAG.getTargetConstant(TrapID, SL, MVT::i16),
3793 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
3797 case SISubtarget::TrapIDLLVMTrap:
3798 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
3799 case SISubtarget::TrapIDLLVMDebugTrap: {
3800 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
3801 "debugtrap handler not supported",
3804 LLVMContext &Ctx = MF.getFunction().getContext();
3805 Ctx.diagnose(NoTrap);
3809 llvm_unreachable("unsupported trap handler type!");
3815 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
3816 SelectionDAG &DAG) const {
3817 // FIXME: Use inline constants (src_{shared, private}_base) instead.
3818 if (Subtarget->hasApertureRegs()) {
3819 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
3820 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
3821 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
3822 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
3823 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
3824 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
3826 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
3827 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
3828 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
3830 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
3831 SDValue ApertureReg = SDValue(
3832 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
3833 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
3834 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
3837 MachineFunction &MF = DAG.getMachineFunction();
3838 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3839 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3840 assert(UserSGPR != AMDGPU::NoRegister);
3842 SDValue QueuePtr = CreateLiveInRegister(
3843 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3845 // Offset into amd_queue_t for group_segment_aperture_base_hi /
3846 // private_segment_aperture_base_hi.
3847 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
3849 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
3851 // TODO: Use custom target PseudoSourceValue.
3852 // TODO: We should use the value from the IR intrinsic call, but it might not
3853 // be available and how do we get it?
3854 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
3855 AMDGPUASI.CONSTANT_ADDRESS));
3857 MachinePointerInfo PtrInfo(V, StructOffset);
3858 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
3859 MinAlign(64, StructOffset),
3860 MachineMemOperand::MODereferenceable |
3861 MachineMemOperand::MOInvariant);
3864 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
3865 SelectionDAG &DAG) const {
3867 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
3869 SDValue Src = ASC->getOperand(0);
3870 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
3872 const AMDGPUTargetMachine &TM =
3873 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
3875 // flat -> local/private
3876 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
3877 unsigned DestAS = ASC->getDestAddressSpace();
3879 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
3880 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
3881 unsigned NullVal = TM.getNullPointerValue(DestAS);
3882 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
3883 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
3884 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
3886 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
3887 NonNull, Ptr, SegmentNullPtr);
3891 // local/private -> flat
3892 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
3893 unsigned SrcAS = ASC->getSrcAddressSpace();
3895 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
3896 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
3897 unsigned NullVal = TM.getNullPointerValue(SrcAS);
3898 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
3901 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
3903 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
3905 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
3907 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
3908 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
3913 // global <-> flat are no-ops and never emitted.
3915 const MachineFunction &MF = DAG.getMachineFunction();
3916 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
3917 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
3918 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
3920 return DAG.getUNDEF(ASC->getValueType(0));
3923 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3924 SelectionDAG &DAG) const {
3925 SDValue Idx = Op.getOperand(2);
3926 if (isa<ConstantSDNode>(Idx))
3929 // Avoid stack access for dynamic indexing.
3931 SDValue Vec = Op.getOperand(0);
3932 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
3934 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
3935 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
3937 // Convert vector index to bit-index.
3938 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
3939 DAG.getConstant(16, SL, MVT::i32));
3941 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3943 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
3944 DAG.getConstant(0xffff, SL, MVT::i32),
3947 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
3948 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
3949 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
3951 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
3952 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
3955 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3956 SelectionDAG &DAG) const {
3959 EVT ResultVT = Op.getValueType();
3960 SDValue Vec = Op.getOperand(0);
3961 SDValue Idx = Op.getOperand(1);
3963 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
3965 // Make sure we we do any optimizations that will make it easier to fold
3966 // source modifiers before obscuring it with bit operations.
3968 // XXX - Why doesn't this get called when vector_shuffle is expanded?
3969 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
3972 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
3973 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3975 if (CIdx->getZExtValue() == 1) {
3976 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
3977 DAG.getConstant(16, SL, MVT::i32));
3979 assert(CIdx->getZExtValue() == 0);
3982 if (ResultVT.bitsLT(MVT::i32))
3983 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
3984 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
3987 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
3989 // Convert vector index to bit-index.
3990 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
3992 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3993 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
3995 SDValue Result = Elt;
3996 if (ResultVT.bitsLT(MVT::i32))
3997 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
3999 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4003 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4004 // We can fold offsets for anything that doesn't require a GOT relocation.
4005 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
4006 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
4007 !shouldEmitGOTReloc(GA->getGlobal());
4011 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4012 const SDLoc &DL, unsigned Offset, EVT PtrVT,
4013 unsigned GAFlags = SIInstrInfo::MO_NONE) {
4014 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4015 // lowered to the following code sequence:
4017 // For constant address space:
4018 // s_getpc_b64 s[0:1]
4019 // s_add_u32 s0, s0, $symbol
4020 // s_addc_u32 s1, s1, 0
4022 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4023 // a fixup or relocation is emitted to replace $symbol with a literal
4024 // constant, which is a pc-relative offset from the encoding of the $symbol
4025 // operand to the global variable.
4027 // For global address space:
4028 // s_getpc_b64 s[0:1]
4029 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4030 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4032 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4033 // fixups or relocations are emitted to replace $symbol@*@lo and
4034 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4035 // which is a 64-bit pc-relative offset from the encoding of the $symbol
4036 // operand to the global variable.
4038 // What we want here is an offset from the value returned by s_getpc
4039 // (which is the address of the s_add_u32 instruction) to the global
4040 // variable, but since the encoding of $symbol starts 4 bytes after the start
4041 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4042 // small. This requires us to add 4 to the global variable offset in order to
4043 // compute the correct address.
4044 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4046 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4047 GAFlags == SIInstrInfo::MO_NONE ?
4048 GAFlags : GAFlags + 1);
4049 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4052 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4054 SelectionDAG &DAG) const {
4055 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4056 const GlobalValue *GV = GSD->getGlobal();
4058 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
4059 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS &&
4060 // FIXME: It isn't correct to rely on the type of the pointer. This should
4061 // be removed when address space 0 is 64-bit.
4062 !GV->getType()->getElementType()->isFunctionTy())
4063 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4066 EVT PtrVT = Op.getValueType();
4068 if (shouldEmitFixup(GV))
4069 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4070 else if (shouldEmitPCReloc(GV))
4071 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4072 SIInstrInfo::MO_REL32);
4074 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4075 SIInstrInfo::MO_GOTPCREL32);
4077 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4078 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
4079 const DataLayout &DataLayout = DAG.getDataLayout();
4080 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4081 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
4082 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
4084 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4085 MachineMemOperand::MODereferenceable |
4086 MachineMemOperand::MOInvariant);
4089 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4090 const SDLoc &DL, SDValue V) const {
4091 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4092 // the destination register.
4094 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4095 // so we will end up with redundant moves to m0.
4097 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4099 // A Null SDValue creates a glue result.
4100 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4102 return SDValue(M0, 0);
4105 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4108 unsigned Offset) const {
4110 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4111 DAG.getEntryNode(), Offset, false);
4112 // The local size values will have the hi 16-bits as zero.
4113 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4114 DAG.getValueType(VT));
4117 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4119 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4120 "non-hsa intrinsic with hsa target",
4122 DAG.getContext()->diagnose(BadIntrin);
4123 return DAG.getUNDEF(VT);
4126 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4128 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4129 "intrinsic not supported on subtarget",
4131 DAG.getContext()->diagnose(BadIntrin);
4132 return DAG.getUNDEF(VT);
4135 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4136 SelectionDAG &DAG) const {
4137 MachineFunction &MF = DAG.getMachineFunction();
4138 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
4140 EVT VT = Op.getValueType();
4142 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4144 // TODO: Should this propagate fast-math-flags?
4146 switch (IntrinsicID) {
4147 case Intrinsic::amdgcn_implicit_buffer_ptr: {
4148 if (getSubtarget()->isAmdCodeObjectV2(MF))
4149 return emitNonHSAIntrinsicError(DAG, DL, VT);
4150 return getPreloadedValue(DAG, *MFI, VT,
4151 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
4153 case Intrinsic::amdgcn_dispatch_ptr:
4154 case Intrinsic::amdgcn_queue_ptr: {
4155 if (!Subtarget->isAmdCodeObjectV2(MF)) {
4156 DiagnosticInfoUnsupported BadIntrin(
4157 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
4159 DAG.getContext()->diagnose(BadIntrin);
4160 return DAG.getUNDEF(VT);
4163 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
4164 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
4165 return getPreloadedValue(DAG, *MFI, VT, RegID);
4167 case Intrinsic::amdgcn_implicitarg_ptr: {
4168 if (MFI->isEntryFunction())
4169 return getImplicitArgPtr(DAG, DL);
4170 return getPreloadedValue(DAG, *MFI, VT,
4171 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
4173 case Intrinsic::amdgcn_kernarg_segment_ptr: {
4174 return getPreloadedValue(DAG, *MFI, VT,
4175 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
4177 case Intrinsic::amdgcn_dispatch_id: {
4178 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
4180 case Intrinsic::amdgcn_rcp:
4181 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
4182 case Intrinsic::amdgcn_rsq:
4183 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4184 case Intrinsic::amdgcn_rsq_legacy:
4185 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4186 return emitRemovedIntrinsicError(DAG, DL, VT);
4188 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
4189 case Intrinsic::amdgcn_rcp_legacy:
4190 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4191 return emitRemovedIntrinsicError(DAG, DL, VT);
4192 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
4193 case Intrinsic::amdgcn_rsq_clamp: {
4194 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4195 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
4197 Type *Type = VT.getTypeForEVT(*DAG.getContext());
4198 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
4199 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
4201 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4202 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
4203 DAG.getConstantFP(Max, DL, VT));
4204 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
4205 DAG.getConstantFP(Min, DL, VT));
4207 case Intrinsic::r600_read_ngroups_x:
4208 if (Subtarget->isAmdHsaOS())
4209 return emitNonHSAIntrinsicError(DAG, DL, VT);
4211 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4212 SI::KernelInputOffsets::NGROUPS_X, false);
4213 case Intrinsic::r600_read_ngroups_y:
4214 if (Subtarget->isAmdHsaOS())
4215 return emitNonHSAIntrinsicError(DAG, DL, VT);
4217 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4218 SI::KernelInputOffsets::NGROUPS_Y, false);
4219 case Intrinsic::r600_read_ngroups_z:
4220 if (Subtarget->isAmdHsaOS())
4221 return emitNonHSAIntrinsicError(DAG, DL, VT);
4223 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4224 SI::KernelInputOffsets::NGROUPS_Z, false);
4225 case Intrinsic::r600_read_global_size_x:
4226 if (Subtarget->isAmdHsaOS())
4227 return emitNonHSAIntrinsicError(DAG, DL, VT);
4229 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4230 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
4231 case Intrinsic::r600_read_global_size_y:
4232 if (Subtarget->isAmdHsaOS())
4233 return emitNonHSAIntrinsicError(DAG, DL, VT);
4235 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4236 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
4237 case Intrinsic::r600_read_global_size_z:
4238 if (Subtarget->isAmdHsaOS())
4239 return emitNonHSAIntrinsicError(DAG, DL, VT);
4241 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4242 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
4243 case Intrinsic::r600_read_local_size_x:
4244 if (Subtarget->isAmdHsaOS())
4245 return emitNonHSAIntrinsicError(DAG, DL, VT);
4247 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4248 SI::KernelInputOffsets::LOCAL_SIZE_X);
4249 case Intrinsic::r600_read_local_size_y:
4250 if (Subtarget->isAmdHsaOS())
4251 return emitNonHSAIntrinsicError(DAG, DL, VT);
4253 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4254 SI::KernelInputOffsets::LOCAL_SIZE_Y);
4255 case Intrinsic::r600_read_local_size_z:
4256 if (Subtarget->isAmdHsaOS())
4257 return emitNonHSAIntrinsicError(DAG, DL, VT);
4259 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4260 SI::KernelInputOffsets::LOCAL_SIZE_Z);
4261 case Intrinsic::amdgcn_workgroup_id_x:
4262 case Intrinsic::r600_read_tgid_x:
4263 return getPreloadedValue(DAG, *MFI, VT,
4264 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
4265 case Intrinsic::amdgcn_workgroup_id_y:
4266 case Intrinsic::r600_read_tgid_y:
4267 return getPreloadedValue(DAG, *MFI, VT,
4268 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
4269 case Intrinsic::amdgcn_workgroup_id_z:
4270 case Intrinsic::r600_read_tgid_z:
4271 return getPreloadedValue(DAG, *MFI, VT,
4272 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
4273 case Intrinsic::amdgcn_workitem_id_x: {
4274 case Intrinsic::r600_read_tidig_x:
4275 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4276 SDLoc(DAG.getEntryNode()),
4277 MFI->getArgInfo().WorkItemIDX);
4279 case Intrinsic::amdgcn_workitem_id_y:
4280 case Intrinsic::r600_read_tidig_y:
4281 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4282 SDLoc(DAG.getEntryNode()),
4283 MFI->getArgInfo().WorkItemIDY);
4284 case Intrinsic::amdgcn_workitem_id_z:
4285 case Intrinsic::r600_read_tidig_z:
4286 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4287 SDLoc(DAG.getEntryNode()),
4288 MFI->getArgInfo().WorkItemIDZ);
4289 case AMDGPUIntrinsic::SI_load_const: {
4295 MachineMemOperand *MMO = MF.getMachineMemOperand(
4296 MachinePointerInfo(),
4297 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
4298 MachineMemOperand::MOInvariant,
4299 VT.getStoreSize(), 4);
4300 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
4301 Op->getVTList(), Ops, VT, MMO);
4303 case Intrinsic::amdgcn_fdiv_fast:
4304 return lowerFDIV_FAST(Op, DAG);
4305 case Intrinsic::amdgcn_interp_mov: {
4306 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4307 SDValue Glue = M0.getValue(1);
4308 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
4309 Op.getOperand(2), Op.getOperand(3), Glue);
4311 case Intrinsic::amdgcn_interp_p1: {
4312 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4313 SDValue Glue = M0.getValue(1);
4314 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
4315 Op.getOperand(2), Op.getOperand(3), Glue);
4317 case Intrinsic::amdgcn_interp_p2: {
4318 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
4319 SDValue Glue = SDValue(M0.getNode(), 1);
4320 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
4321 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
4324 case Intrinsic::amdgcn_sin:
4325 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
4327 case Intrinsic::amdgcn_cos:
4328 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
4330 case Intrinsic::amdgcn_log_clamp: {
4331 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4334 DiagnosticInfoUnsupported BadIntrin(
4335 MF.getFunction(), "intrinsic not supported on subtarget",
4337 DAG.getContext()->diagnose(BadIntrin);
4338 return DAG.getUNDEF(VT);
4340 case Intrinsic::amdgcn_ldexp:
4341 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
4342 Op.getOperand(1), Op.getOperand(2));
4344 case Intrinsic::amdgcn_fract:
4345 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
4347 case Intrinsic::amdgcn_class:
4348 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
4349 Op.getOperand(1), Op.getOperand(2));
4350 case Intrinsic::amdgcn_div_fmas:
4351 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
4352 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
4355 case Intrinsic::amdgcn_div_fixup:
4356 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
4357 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4359 case Intrinsic::amdgcn_trig_preop:
4360 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
4361 Op.getOperand(1), Op.getOperand(2));
4362 case Intrinsic::amdgcn_div_scale: {
4363 // 3rd parameter required to be a constant.
4364 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4366 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
4368 // Translate to the operands expected by the machine instruction. The
4369 // first parameter must be the same as the first instruction.
4370 SDValue Numerator = Op.getOperand(1);
4371 SDValue Denominator = Op.getOperand(2);
4373 // Note this order is opposite of the machine instruction's operations,
4374 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
4375 // intrinsic has the numerator as the first operand to match a normal
4376 // division operation.
4378 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
4380 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
4381 Denominator, Numerator);
4383 case Intrinsic::amdgcn_icmp: {
4384 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4386 return DAG.getUNDEF(VT);
4388 int CondCode = CD->getSExtValue();
4389 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4390 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4391 return DAG.getUNDEF(VT);
4393 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4394 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4395 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4396 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4398 case Intrinsic::amdgcn_fcmp: {
4399 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4401 return DAG.getUNDEF(VT);
4403 int CondCode = CD->getSExtValue();
4404 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4405 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
4406 return DAG.getUNDEF(VT);
4408 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4409 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4410 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4411 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4413 case Intrinsic::amdgcn_fmed3:
4414 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
4415 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4416 case Intrinsic::amdgcn_fmul_legacy:
4417 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
4418 Op.getOperand(1), Op.getOperand(2));
4419 case Intrinsic::amdgcn_sffbh:
4420 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
4421 case Intrinsic::amdgcn_sbfe:
4422 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
4423 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4424 case Intrinsic::amdgcn_ubfe:
4425 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
4426 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4427 case Intrinsic::amdgcn_cvt_pkrtz: {
4428 // FIXME: Stop adding cast if v2f16 legal.
4429 EVT VT = Op.getValueType();
4430 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
4431 Op.getOperand(1), Op.getOperand(2));
4432 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
4434 case Intrinsic::amdgcn_wqm: {
4435 SDValue Src = Op.getOperand(1);
4436 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
4439 case Intrinsic::amdgcn_wwm: {
4440 SDValue Src = Op.getOperand(1);
4441 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
4444 case Intrinsic::amdgcn_image_getlod:
4445 case Intrinsic::amdgcn_image_getresinfo: {
4446 unsigned Idx = (IntrinsicID == Intrinsic::amdgcn_image_getresinfo) ? 3 : 4;
4448 // Replace dmask with everything disabled with undef.
4449 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(Idx));
4450 if (!DMask || DMask->isNullValue())
4451 return DAG.getUNDEF(Op.getValueType());
4459 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4460 SelectionDAG &DAG) const {
4461 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4465 case Intrinsic::amdgcn_atomic_inc:
4466 case Intrinsic::amdgcn_atomic_dec: {
4467 MemSDNode *M = cast<MemSDNode>(Op);
4468 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
4469 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
4471 M->getOperand(0), // Chain
4472 M->getOperand(2), // Ptr
4473 M->getOperand(3) // Value
4476 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
4477 M->getMemoryVT(), M->getMemOperand());
4479 case Intrinsic::amdgcn_buffer_load:
4480 case Intrinsic::amdgcn_buffer_load_format: {
4482 Op.getOperand(0), // Chain
4483 Op.getOperand(2), // rsrc
4484 Op.getOperand(3), // vindex
4485 Op.getOperand(4), // offset
4486 Op.getOperand(5), // glc
4487 Op.getOperand(6) // slc
4490 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
4491 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
4492 EVT VT = Op.getValueType();
4493 EVT IntVT = VT.changeTypeToInteger();
4495 auto *M = cast<MemSDNode>(Op);
4496 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
4497 M->getMemOperand());
4499 case Intrinsic::amdgcn_tbuffer_load: {
4500 MemSDNode *M = cast<MemSDNode>(Op);
4502 Op.getOperand(0), // Chain
4503 Op.getOperand(2), // rsrc
4504 Op.getOperand(3), // vindex
4505 Op.getOperand(4), // voffset
4506 Op.getOperand(5), // soffset
4507 Op.getOperand(6), // offset
4508 Op.getOperand(7), // dfmt
4509 Op.getOperand(8), // nfmt
4510 Op.getOperand(9), // glc
4511 Op.getOperand(10) // slc
4514 EVT VT = Op.getValueType();
4516 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
4517 Op->getVTList(), Ops, VT, M->getMemOperand());
4519 case Intrinsic::amdgcn_buffer_atomic_swap:
4520 case Intrinsic::amdgcn_buffer_atomic_add:
4521 case Intrinsic::amdgcn_buffer_atomic_sub:
4522 case Intrinsic::amdgcn_buffer_atomic_smin:
4523 case Intrinsic::amdgcn_buffer_atomic_umin:
4524 case Intrinsic::amdgcn_buffer_atomic_smax:
4525 case Intrinsic::amdgcn_buffer_atomic_umax:
4526 case Intrinsic::amdgcn_buffer_atomic_and:
4527 case Intrinsic::amdgcn_buffer_atomic_or:
4528 case Intrinsic::amdgcn_buffer_atomic_xor: {
4530 Op.getOperand(0), // Chain
4531 Op.getOperand(2), // vdata
4532 Op.getOperand(3), // rsrc
4533 Op.getOperand(4), // vindex
4534 Op.getOperand(5), // offset
4535 Op.getOperand(6) // slc
4537 EVT VT = Op.getValueType();
4539 auto *M = cast<MemSDNode>(Op);
4540 unsigned Opcode = 0;
4543 case Intrinsic::amdgcn_buffer_atomic_swap:
4544 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
4546 case Intrinsic::amdgcn_buffer_atomic_add:
4547 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
4549 case Intrinsic::amdgcn_buffer_atomic_sub:
4550 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
4552 case Intrinsic::amdgcn_buffer_atomic_smin:
4553 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
4555 case Intrinsic::amdgcn_buffer_atomic_umin:
4556 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
4558 case Intrinsic::amdgcn_buffer_atomic_smax:
4559 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
4561 case Intrinsic::amdgcn_buffer_atomic_umax:
4562 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
4564 case Intrinsic::amdgcn_buffer_atomic_and:
4565 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
4567 case Intrinsic::amdgcn_buffer_atomic_or:
4568 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
4570 case Intrinsic::amdgcn_buffer_atomic_xor:
4571 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
4574 llvm_unreachable("unhandled atomic opcode");
4577 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
4578 M->getMemOperand());
4581 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
4583 Op.getOperand(0), // Chain
4584 Op.getOperand(2), // src
4585 Op.getOperand(3), // cmp
4586 Op.getOperand(4), // rsrc
4587 Op.getOperand(5), // vindex
4588 Op.getOperand(6), // offset
4589 Op.getOperand(7) // slc
4591 EVT VT = Op.getValueType();
4592 auto *M = cast<MemSDNode>(Op);
4594 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
4595 Op->getVTList(), Ops, VT, M->getMemOperand());
4599 case Intrinsic::amdgcn_image_sample:
4600 case Intrinsic::amdgcn_image_sample_cl:
4601 case Intrinsic::amdgcn_image_sample_d:
4602 case Intrinsic::amdgcn_image_sample_d_cl:
4603 case Intrinsic::amdgcn_image_sample_l:
4604 case Intrinsic::amdgcn_image_sample_b:
4605 case Intrinsic::amdgcn_image_sample_b_cl:
4606 case Intrinsic::amdgcn_image_sample_lz:
4607 case Intrinsic::amdgcn_image_sample_cd:
4608 case Intrinsic::amdgcn_image_sample_cd_cl:
4610 // Sample with comparison.
4611 case Intrinsic::amdgcn_image_sample_c:
4612 case Intrinsic::amdgcn_image_sample_c_cl:
4613 case Intrinsic::amdgcn_image_sample_c_d:
4614 case Intrinsic::amdgcn_image_sample_c_d_cl:
4615 case Intrinsic::amdgcn_image_sample_c_l:
4616 case Intrinsic::amdgcn_image_sample_c_b:
4617 case Intrinsic::amdgcn_image_sample_c_b_cl:
4618 case Intrinsic::amdgcn_image_sample_c_lz:
4619 case Intrinsic::amdgcn_image_sample_c_cd:
4620 case Intrinsic::amdgcn_image_sample_c_cd_cl:
4622 // Sample with offsets.
4623 case Intrinsic::amdgcn_image_sample_o:
4624 case Intrinsic::amdgcn_image_sample_cl_o:
4625 case Intrinsic::amdgcn_image_sample_d_o:
4626 case Intrinsic::amdgcn_image_sample_d_cl_o:
4627 case Intrinsic::amdgcn_image_sample_l_o:
4628 case Intrinsic::amdgcn_image_sample_b_o:
4629 case Intrinsic::amdgcn_image_sample_b_cl_o:
4630 case Intrinsic::amdgcn_image_sample_lz_o:
4631 case Intrinsic::amdgcn_image_sample_cd_o:
4632 case Intrinsic::amdgcn_image_sample_cd_cl_o:
4634 // Sample with comparison and offsets.
4635 case Intrinsic::amdgcn_image_sample_c_o:
4636 case Intrinsic::amdgcn_image_sample_c_cl_o:
4637 case Intrinsic::amdgcn_image_sample_c_d_o:
4638 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
4639 case Intrinsic::amdgcn_image_sample_c_l_o:
4640 case Intrinsic::amdgcn_image_sample_c_b_o:
4641 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
4642 case Intrinsic::amdgcn_image_sample_c_lz_o:
4643 case Intrinsic::amdgcn_image_sample_c_cd_o:
4644 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: {
4645 // Replace dmask with everything disabled with undef.
4646 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
4647 if (!DMask || DMask->isNullValue()) {
4648 SDValue Undef = DAG.getUNDEF(Op.getValueType());
4649 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
4659 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4660 SelectionDAG &DAG) const {
4662 SDValue Chain = Op.getOperand(0);
4663 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4664 MachineFunction &MF = DAG.getMachineFunction();
4666 switch (IntrinsicID) {
4667 case Intrinsic::amdgcn_exp: {
4668 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
4669 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
4670 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
4671 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
4673 const SDValue Ops[] = {
4675 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
4676 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
4677 Op.getOperand(4), // src0
4678 Op.getOperand(5), // src1
4679 Op.getOperand(6), // src2
4680 Op.getOperand(7), // src3
4681 DAG.getTargetConstant(0, DL, MVT::i1), // compr
4682 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
4685 unsigned Opc = Done->isNullValue() ?
4686 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
4687 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
4689 case Intrinsic::amdgcn_exp_compr: {
4690 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
4691 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
4692 SDValue Src0 = Op.getOperand(4);
4693 SDValue Src1 = Op.getOperand(5);
4694 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
4695 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
4697 SDValue Undef = DAG.getUNDEF(MVT::f32);
4698 const SDValue Ops[] = {
4700 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
4701 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
4702 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
4703 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
4706 DAG.getTargetConstant(1, DL, MVT::i1), // compr
4707 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
4710 unsigned Opc = Done->isNullValue() ?
4711 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
4712 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
4714 case Intrinsic::amdgcn_s_sendmsg:
4715 case Intrinsic::amdgcn_s_sendmsghalt: {
4716 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
4717 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
4718 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
4719 SDValue Glue = Chain.getValue(1);
4720 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
4721 Op.getOperand(2), Glue);
4723 case Intrinsic::amdgcn_init_exec: {
4724 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
4727 case Intrinsic::amdgcn_init_exec_from_input: {
4728 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
4729 Op.getOperand(2), Op.getOperand(3));
4731 case AMDGPUIntrinsic::AMDGPU_kill: {
4732 SDValue Src = Op.getOperand(2);
4733 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
4734 if (!K->isNegative())
4737 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
4738 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
4741 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
4742 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
4744 case Intrinsic::amdgcn_s_barrier: {
4745 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
4746 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
4747 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
4748 if (WGSize <= ST.getWavefrontSize())
4749 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
4750 Op.getOperand(0)), 0);
4754 case AMDGPUIntrinsic::SI_tbuffer_store: {
4756 // Extract vindex and voffset from vaddr as appropriate
4757 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10));
4758 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11));
4759 SDValue VAddr = Op.getOperand(5);
4761 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
4763 assert(!(OffEn->isOne() && IdxEn->isOne()) &&
4764 "Legacy intrinsic doesn't support both offset and index - use new version");
4766 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero;
4767 SDValue VOffset = OffEn->isOne() ? VAddr : Zero;
4769 // Deal with the vec-3 case
4770 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4));
4771 auto Opcode = NumChannels->getZExtValue() == 3 ?
4772 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT;
4776 Op.getOperand(3), // vdata
4777 Op.getOperand(2), // rsrc
4780 Op.getOperand(6), // soffset
4781 Op.getOperand(7), // inst_offset
4782 Op.getOperand(8), // dfmt
4783 Op.getOperand(9), // nfmt
4784 Op.getOperand(12), // glc
4785 Op.getOperand(13), // slc
4788 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 &&
4789 "Value of tfe other than zero is unsupported");
4791 EVT VT = Op.getOperand(3).getValueType();
4792 MachineMemOperand *MMO = MF.getMachineMemOperand(
4793 MachinePointerInfo(),
4794 MachineMemOperand::MOStore,
4795 VT.getStoreSize(), 4);
4796 return DAG.getMemIntrinsicNode(Opcode, DL,
4797 Op->getVTList(), Ops, VT, MMO);
4800 case Intrinsic::amdgcn_tbuffer_store: {
4803 Op.getOperand(2), // vdata
4804 Op.getOperand(3), // rsrc
4805 Op.getOperand(4), // vindex
4806 Op.getOperand(5), // voffset
4807 Op.getOperand(6), // soffset
4808 Op.getOperand(7), // offset
4809 Op.getOperand(8), // dfmt
4810 Op.getOperand(9), // nfmt
4811 Op.getOperand(10), // glc
4812 Op.getOperand(11) // slc
4814 EVT VT = Op.getOperand(3).getValueType();
4815 MachineMemOperand *MMO = MF.getMachineMemOperand(
4816 MachinePointerInfo(),
4817 MachineMemOperand::MOStore,
4818 VT.getStoreSize(), 4);
4819 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
4820 Op->getVTList(), Ops, VT, MMO);
4823 case Intrinsic::amdgcn_buffer_store:
4824 case Intrinsic::amdgcn_buffer_store_format: {
4827 Op.getOperand(2), // vdata
4828 Op.getOperand(3), // rsrc
4829 Op.getOperand(4), // vindex
4830 Op.getOperand(5), // offset
4831 Op.getOperand(6), // glc
4832 Op.getOperand(7) // slc
4834 EVT VT = Op.getOperand(3).getValueType();
4835 MachineMemOperand *MMO = MF.getMachineMemOperand(
4836 MachinePointerInfo(),
4837 MachineMemOperand::MOStore |
4838 MachineMemOperand::MODereferenceable,
4839 VT.getStoreSize(), 4);
4841 unsigned Opcode = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
4842 AMDGPUISD::BUFFER_STORE :
4843 AMDGPUISD::BUFFER_STORE_FORMAT;
4844 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, MMO);
4852 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4854 LoadSDNode *Load = cast<LoadSDNode>(Op);
4855 ISD::LoadExtType ExtType = Load->getExtensionType();
4856 EVT MemVT = Load->getMemoryVT();
4858 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
4859 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
4862 // FIXME: Copied from PPC
4863 // First, load into 32 bits, then truncate to 1 bit.
4865 SDValue Chain = Load->getChain();
4866 SDValue BasePtr = Load->getBasePtr();
4867 MachineMemOperand *MMO = Load->getMemOperand();
4869 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
4871 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
4872 BasePtr, RealMemVT, MMO);
4875 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
4879 return DAG.getMergeValues(Ops, DL);
4882 if (!MemVT.isVector())
4885 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
4886 "Custom lowering for non-i32 vectors hasn't been implemented.");
4888 unsigned AS = Load->getAddressSpace();
4889 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
4890 AS, Load->getAlignment())) {
4892 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
4893 return DAG.getMergeValues(Ops, DL);
4896 MachineFunction &MF = DAG.getMachineFunction();
4897 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4898 // If there is a possibilty that flat instruction access scratch memory
4899 // then we need to use the same legalization rules we use for private.
4900 if (AS == AMDGPUASI.FLAT_ADDRESS)
4901 AS = MFI->hasFlatScratchInit() ?
4902 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
4904 unsigned NumElements = MemVT.getVectorNumElements();
4905 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
4906 if (isMemOpUniform(Load))
4908 // Non-uniform loads will be selected to MUBUF instructions, so they
4909 // have the same legalization requirements as global and private
4913 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
4914 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
4915 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load))
4917 // Non-uniform loads will be selected to MUBUF instructions, so they
4918 // have the same legalization requirements as global and private
4922 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
4923 AS == AMDGPUASI.FLAT_ADDRESS) {
4924 if (NumElements > 4)
4925 return SplitVectorLoad(Op, DAG);
4926 // v4 loads are supported for private and global memory.
4929 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
4930 // Depending on the setting of the private_element_size field in the
4931 // resource descriptor, we can only make private accesses up to a certain
4933 switch (Subtarget->getMaxPrivateElementSize()) {
4935 return scalarizeVectorLoad(Load, DAG);
4937 if (NumElements > 2)
4938 return SplitVectorLoad(Op, DAG);
4941 // Same as global/flat
4942 if (NumElements > 4)
4943 return SplitVectorLoad(Op, DAG);
4946 llvm_unreachable("unsupported private_element_size");
4948 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
4949 if (NumElements > 2)
4950 return SplitVectorLoad(Op, DAG);
4952 if (NumElements == 2)
4955 // If properly aligned, if we split we might be able to use ds_read_b64.
4956 return SplitVectorLoad(Op, DAG);
4961 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4962 if (Op.getValueType() != MVT::i64)
4966 SDValue Cond = Op.getOperand(0);
4968 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
4969 SDValue One = DAG.getConstant(1, DL, MVT::i32);
4971 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
4972 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
4974 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
4975 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
4977 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
4979 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
4980 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
4982 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
4984 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
4985 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
4988 // Catch division cases where we can use shortcuts with rcp and rsq
4990 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
4991 SelectionDAG &DAG) const {
4993 SDValue LHS = Op.getOperand(0);
4994 SDValue RHS = Op.getOperand(1);
4995 EVT VT = Op.getValueType();
4996 const SDNodeFlags Flags = Op->getFlags();
4997 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath ||
4998 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal();
5000 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
5003 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
5004 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
5005 if (CLHS->isExactlyValue(1.0)) {
5006 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
5007 // the CI documentation has a worst case error of 1 ulp.
5008 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
5009 // use it as long as we aren't trying to use denormals.
5011 // v_rcp_f16 and v_rsq_f16 DO support denormals.
5013 // 1.0 / sqrt(x) -> rsq(x)
5015 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
5016 // error seems really high at 2^29 ULP.
5017 if (RHS.getOpcode() == ISD::FSQRT)
5018 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
5020 // 1.0 / x -> rcp(x)
5021 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5024 // Same as for 1.0, but expand the sign out of the constant.
5025 if (CLHS->isExactlyValue(-1.0)) {
5026 // -1.0 / x -> rcp (fneg x)
5027 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
5028 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
5034 // Turn into multiply by the reciprocal.
5035 // x / y -> x * (1.0 / y)
5036 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5037 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
5043 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5044 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
5045 if (GlueChain->getNumValues() <= 1) {
5046 return DAG.getNode(Opcode, SL, VT, A, B);
5049 assert(GlueChain->getNumValues() == 3);
5051 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5053 default: llvm_unreachable("no chain equivalent for opcode");
5055 Opcode = AMDGPUISD::FMUL_W_CHAIN;
5059 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
5060 GlueChain.getValue(2));
5063 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5064 EVT VT, SDValue A, SDValue B, SDValue C,
5065 SDValue GlueChain) {
5066 if (GlueChain->getNumValues() <= 1) {
5067 return DAG.getNode(Opcode, SL, VT, A, B, C);
5070 assert(GlueChain->getNumValues() == 3);
5072 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5074 default: llvm_unreachable("no chain equivalent for opcode");
5076 Opcode = AMDGPUISD::FMA_W_CHAIN;
5080 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
5081 GlueChain.getValue(2));
5084 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
5085 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5089 SDValue Src0 = Op.getOperand(0);
5090 SDValue Src1 = Op.getOperand(1);
5092 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5093 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5095 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
5096 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
5098 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
5099 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
5101 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
5104 // Faster 2.5 ULP division that does not support denormals.
5105 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
5107 SDValue LHS = Op.getOperand(1);
5108 SDValue RHS = Op.getOperand(2);
5110 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
5112 const APFloat K0Val(BitsToFloat(0x6f800000));
5113 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
5115 const APFloat K1Val(BitsToFloat(0x2f800000));
5116 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
5118 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5121 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
5123 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
5125 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
5127 // TODO: Should this propagate fast-math-flags?
5128 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
5130 // rcp does not support denormals.
5131 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
5133 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
5135 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
5138 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
5139 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5143 SDValue LHS = Op.getOperand(0);
5144 SDValue RHS = Op.getOperand(1);
5146 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5148 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
5150 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5152 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5155 // Denominator is scaled to not be denormal, so using rcp is ok.
5156 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
5158 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
5161 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
5162 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
5163 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
5165 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
5167 if (!Subtarget->hasFP32Denormals()) {
5168 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
5169 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
5171 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
5173 EnableDenormValue, BitField);
5176 EnableDenorm.getValue(0),
5177 EnableDenorm.getValue(1)
5180 NegDivScale0 = DAG.getMergeValues(Ops, SL);
5183 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
5184 ApproxRcp, One, NegDivScale0);
5186 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
5189 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
5192 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
5193 NumeratorScaled, Mul);
5195 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
5197 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
5198 NumeratorScaled, Fma3);
5200 if (!Subtarget->hasFP32Denormals()) {
5201 const SDValue DisableDenormValue =
5202 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
5203 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
5209 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
5210 DisableDenorm, DAG.getRoot());
5211 DAG.setRoot(OutputChain);
5214 SDValue Scale = NumeratorScaled.getValue(1);
5215 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
5216 Fma4, Fma1, Fma3, Scale);
5218 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
5221 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
5222 if (DAG.getTarget().Options.UnsafeFPMath)
5223 return lowerFastUnsafeFDIV(Op, DAG);
5226 SDValue X = Op.getOperand(0);
5227 SDValue Y = Op.getOperand(1);
5229 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
5231 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
5233 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
5235 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
5237 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
5239 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
5241 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
5243 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
5245 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
5247 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
5248 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
5250 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
5251 NegDivScale0, Mul, DivScale1);
5255 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
5256 // Workaround a hardware bug on SI where the condition output from div_scale
5259 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
5261 // Figure out if the scale to use for div_fmas.
5262 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
5263 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
5264 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
5265 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
5267 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
5268 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
5271 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
5273 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
5275 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
5276 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
5277 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
5279 Scale = DivScale1.getValue(1);
5282 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
5283 Fma4, Fma3, Mul, Scale);
5285 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
5288 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
5289 EVT VT = Op.getValueType();
5292 return LowerFDIV32(Op, DAG);
5295 return LowerFDIV64(Op, DAG);
5298 return LowerFDIV16(Op, DAG);
5300 llvm_unreachable("Unexpected type for fdiv");
5303 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5305 StoreSDNode *Store = cast<StoreSDNode>(Op);
5306 EVT VT = Store->getMemoryVT();
5308 if (VT == MVT::i1) {
5309 return DAG.getTruncStore(Store->getChain(), DL,
5310 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
5311 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
5314 assert(VT.isVector() &&
5315 Store->getValue().getValueType().getScalarType() == MVT::i32);
5317 unsigned AS = Store->getAddressSpace();
5318 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
5319 AS, Store->getAlignment())) {
5320 return expandUnalignedStore(Store, DAG);
5323 MachineFunction &MF = DAG.getMachineFunction();
5324 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5325 // If there is a possibilty that flat instruction access scratch memory
5326 // then we need to use the same legalization rules we use for private.
5327 if (AS == AMDGPUASI.FLAT_ADDRESS)
5328 AS = MFI->hasFlatScratchInit() ?
5329 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5331 unsigned NumElements = VT.getVectorNumElements();
5332 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
5333 AS == AMDGPUASI.FLAT_ADDRESS) {
5334 if (NumElements > 4)
5335 return SplitVectorStore(Op, DAG);
5337 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5338 switch (Subtarget->getMaxPrivateElementSize()) {
5340 return scalarizeVectorStore(Store, DAG);
5342 if (NumElements > 2)
5343 return SplitVectorStore(Op, DAG);
5346 if (NumElements > 4)
5347 return SplitVectorStore(Op, DAG);
5350 llvm_unreachable("unsupported private_element_size");
5352 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5353 if (NumElements > 2)
5354 return SplitVectorStore(Op, DAG);
5356 if (NumElements == 2)
5359 // If properly aligned, if we split we might be able to use ds_write_b64.
5360 return SplitVectorStore(Op, DAG);
5362 llvm_unreachable("unhandled address space");
5366 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
5368 EVT VT = Op.getValueType();
5369 SDValue Arg = Op.getOperand(0);
5370 // TODO: Should this propagate fast-math-flags?
5371 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
5372 DAG.getNode(ISD::FMUL, DL, VT, Arg,
5373 DAG.getConstantFP(0.5/M_PI, DL,
5376 switch (Op.getOpcode()) {
5378 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
5380 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
5382 llvm_unreachable("Wrong trig opcode");
5386 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
5387 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
5388 assert(AtomicNode->isCompareAndSwap());
5389 unsigned AS = AtomicNode->getAddressSpace();
5391 // No custom lowering required for local address space
5392 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
5395 // Non-local address space requires custom lowering for atomic compare
5396 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
5398 SDValue ChainIn = Op.getOperand(0);
5399 SDValue Addr = Op.getOperand(1);
5400 SDValue Old = Op.getOperand(2);
5401 SDValue New = Op.getOperand(3);
5402 EVT VT = Op.getValueType();
5403 MVT SimpleVT = VT.getSimpleVT();
5404 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
5406 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
5407 SDValue Ops[] = { ChainIn, Addr, NewOld };
5409 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
5410 Ops, VT, AtomicNode->getMemOperand());
5413 //===----------------------------------------------------------------------===//
5414 // Custom DAG optimizations
5415 //===----------------------------------------------------------------------===//
5417 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
5418 DAGCombinerInfo &DCI) const {
5419 EVT VT = N->getValueType(0);
5420 EVT ScalarVT = VT.getScalarType();
5421 if (ScalarVT != MVT::f32)
5424 SelectionDAG &DAG = DCI.DAG;
5427 SDValue Src = N->getOperand(0);
5428 EVT SrcVT = Src.getValueType();
5430 // TODO: We could try to match extracting the higher bytes, which would be
5431 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
5432 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
5433 // about in practice.
5434 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
5435 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
5436 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
5437 DCI.AddToWorklist(Cvt.getNode());
5445 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
5447 // This is a variant of
5448 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
5450 // The normal DAG combiner will do this, but only if the add has one use since
5451 // that would increase the number of instructions.
5453 // This prevents us from seeing a constant offset that can be folded into a
5454 // memory instruction's addressing mode. If we know the resulting add offset of
5455 // a pointer can be folded into an addressing offset, we can replace the pointer
5456 // operand with the add of new constant offset. This eliminates one of the uses,
5457 // and may allow the remaining use to also be simplified.
5459 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
5462 DAGCombinerInfo &DCI) const {
5463 SDValue N0 = N->getOperand(0);
5464 SDValue N1 = N->getOperand(1);
5466 // We only do this to handle cases where it's profitable when there are
5467 // multiple uses of the add, so defer to the standard combine.
5468 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
5472 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
5476 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5480 // If the resulting offset is too large, we can't fold it into the addressing
5482 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
5483 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
5486 AM.HasBaseReg = true;
5487 AM.BaseOffs = Offset.getSExtValue();
5488 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
5491 SelectionDAG &DAG = DCI.DAG;
5493 EVT VT = N->getValueType(0);
5495 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
5496 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
5499 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
5500 (N0.getOpcode() == ISD::OR ||
5501 N0->getFlags().hasNoUnsignedWrap()));
5503 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
5506 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
5507 DAGCombinerInfo &DCI) const {
5508 SDValue Ptr = N->getBasePtr();
5509 SelectionDAG &DAG = DCI.DAG;
5512 // TODO: We could also do this for multiplies.
5513 if (Ptr.getOpcode() == ISD::SHL) {
5514 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
5515 N->getMemoryVT(), DCI);
5517 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
5519 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
5520 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
5527 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
5528 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
5529 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
5530 (Opc == ISD::XOR && Val == 0);
5533 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
5534 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
5535 // integer combine opportunities since most 64-bit operations are decomposed
5536 // this way. TODO: We won't want this for SALU especially if it is an inline
5538 SDValue SITargetLowering::splitBinaryBitConstantOp(
5539 DAGCombinerInfo &DCI,
5541 unsigned Opc, SDValue LHS,
5542 const ConstantSDNode *CRHS) const {
5543 uint64_t Val = CRHS->getZExtValue();
5544 uint32_t ValLo = Lo_32(Val);
5545 uint32_t ValHi = Hi_32(Val);
5546 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5548 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
5549 bitOpWithConstantIsReducible(Opc, ValHi)) ||
5550 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
5551 // If we need to materialize a 64-bit immediate, it will be split up later
5552 // anyway. Avoid creating the harder to understand 64-bit immediate
5554 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
5560 // Returns true if argument is a boolean value which is not serialized into
5561 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
5562 static bool isBoolSGPR(SDValue V) {
5563 if (V.getValueType() != MVT::i1)
5565 switch (V.getOpcode()) {
5571 case AMDGPUISD::FP_CLASS:
5577 SDValue SITargetLowering::performAndCombine(SDNode *N,
5578 DAGCombinerInfo &DCI) const {
5579 if (DCI.isBeforeLegalize())
5582 SelectionDAG &DAG = DCI.DAG;
5583 EVT VT = N->getValueType(0);
5584 SDValue LHS = N->getOperand(0);
5585 SDValue RHS = N->getOperand(1);
5588 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
5589 if (VT == MVT::i64 && CRHS) {
5591 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
5595 if (CRHS && VT == MVT::i32) {
5596 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
5597 // nb = number of trailing zeroes in mask
5598 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
5599 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
5600 uint64_t Mask = CRHS->getZExtValue();
5601 unsigned Bits = countPopulation(Mask);
5602 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
5603 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
5604 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
5605 unsigned Shift = CShift->getZExtValue();
5606 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
5607 unsigned Offset = NB + Shift;
5608 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
5610 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
5612 DAG.getConstant(Offset, SL, MVT::i32),
5613 DAG.getConstant(Bits, SL, MVT::i32));
5614 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
5615 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
5616 DAG.getValueType(NarrowVT));
5617 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
5618 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
5625 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
5626 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
5627 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
5628 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
5629 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
5631 SDValue X = LHS.getOperand(0);
5632 SDValue Y = RHS.getOperand(0);
5633 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
5636 if (LCC == ISD::SETO) {
5637 if (X != LHS.getOperand(1))
5640 if (RCC == ISD::SETUNE) {
5641 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
5642 if (!C1 || !C1->isInfinity() || C1->isNegative())
5645 const uint32_t Mask = SIInstrFlags::N_NORMAL |
5646 SIInstrFlags::N_SUBNORMAL |
5647 SIInstrFlags::N_ZERO |
5648 SIInstrFlags::P_ZERO |
5649 SIInstrFlags::P_SUBNORMAL |
5650 SIInstrFlags::P_NORMAL;
5652 static_assert(((~(SIInstrFlags::S_NAN |
5653 SIInstrFlags::Q_NAN |
5654 SIInstrFlags::N_INFINITY |
5655 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
5659 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
5660 X, DAG.getConstant(Mask, DL, MVT::i32));
5665 if (VT == MVT::i32 &&
5666 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
5667 // and x, (sext cc from i1) => select cc, x, 0
5668 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
5669 std::swap(LHS, RHS);
5670 if (isBoolSGPR(RHS.getOperand(0)))
5671 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
5672 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
5678 SDValue SITargetLowering::performOrCombine(SDNode *N,
5679 DAGCombinerInfo &DCI) const {
5680 SelectionDAG &DAG = DCI.DAG;
5681 SDValue LHS = N->getOperand(0);
5682 SDValue RHS = N->getOperand(1);
5684 EVT VT = N->getValueType(0);
5685 if (VT == MVT::i1) {
5686 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
5687 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
5688 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
5689 SDValue Src = LHS.getOperand(0);
5690 if (Src != RHS.getOperand(0))
5693 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
5694 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
5698 // Only 10 bits are used.
5699 static const uint32_t MaxMask = 0x3ff;
5701 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
5703 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
5704 Src, DAG.getConstant(NewMask, DL, MVT::i32));
5713 // TODO: This could be a generic combine with a predicate for extracting the
5714 // high half of an integer being free.
5716 // (or i64:x, (zero_extend i32:y)) ->
5717 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
5718 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
5719 RHS.getOpcode() != ISD::ZERO_EXTEND)
5720 std::swap(LHS, RHS);
5722 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
5723 SDValue ExtSrc = RHS.getOperand(0);
5724 EVT SrcVT = ExtSrc.getValueType();
5725 if (SrcVT == MVT::i32) {
5727 SDValue LowLHS, HiBits;
5728 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
5729 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
5731 DCI.AddToWorklist(LowOr.getNode());
5732 DCI.AddToWorklist(HiBits.getNode());
5734 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
5736 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5740 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
5743 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
5750 SDValue SITargetLowering::performXorCombine(SDNode *N,
5751 DAGCombinerInfo &DCI) const {
5752 EVT VT = N->getValueType(0);
5756 SDValue LHS = N->getOperand(0);
5757 SDValue RHS = N->getOperand(1);
5759 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
5762 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
5769 // Instructions that will be lowered with a final instruction that zeros the
5770 // high result bits.
5771 // XXX - probably only need to list legal operations.
5772 static bool fp16SrcZerosHighBits(unsigned Opc) {
5781 case ISD::FCANONICALIZE:
5783 case ISD::UINT_TO_FP:
5784 case ISD::SINT_TO_FP:
5786 // Fabs is lowered to a bit operation, but it's an and which will clear the
5787 // high bits anyway.
5801 case ISD::FNEARBYINT:
5806 case AMDGPUISD::FRACT:
5807 case AMDGPUISD::CLAMP:
5808 case AMDGPUISD::COS_HW:
5809 case AMDGPUISD::SIN_HW:
5810 case AMDGPUISD::FMIN3:
5811 case AMDGPUISD::FMAX3:
5812 case AMDGPUISD::FMED3:
5813 case AMDGPUISD::FMAD_FTZ:
5814 case AMDGPUISD::RCP:
5815 case AMDGPUISD::RSQ:
5816 case AMDGPUISD::LDEXP:
5819 // fcopysign, select and others may be lowered to 32-bit bit operations
5820 // which don't zero the high bits.
5825 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
5826 DAGCombinerInfo &DCI) const {
5827 if (!Subtarget->has16BitInsts() ||
5828 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
5831 EVT VT = N->getValueType(0);
5835 SDValue Src = N->getOperand(0);
5836 if (Src.getValueType() != MVT::i16)
5839 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
5840 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
5841 if (Src.getOpcode() == ISD::BITCAST) {
5842 SDValue BCSrc = Src.getOperand(0);
5843 if (BCSrc.getValueType() == MVT::f16 &&
5844 fp16SrcZerosHighBits(BCSrc.getOpcode()))
5845 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
5851 SDValue SITargetLowering::performClassCombine(SDNode *N,
5852 DAGCombinerInfo &DCI) const {
5853 SelectionDAG &DAG = DCI.DAG;
5854 SDValue Mask = N->getOperand(1);
5856 // fp_class x, 0 -> false
5857 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
5858 if (CMask->isNullValue())
5859 return DAG.getConstant(0, SDLoc(N), MVT::i1);
5862 if (N->getOperand(0).isUndef())
5863 return DAG.getUNDEF(MVT::i1);
5868 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
5869 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
5872 return DAG.isKnownNeverNaN(Op);
5875 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op,
5876 const SISubtarget *ST, unsigned MaxDepth=5) {
5877 // If source is a result of another standard FP operation it is already in
5880 switch (Op.getOpcode()) {
5884 // These will flush denorms if required.
5894 case ISD::FCANONICALIZE:
5898 return Op.getValueType().getScalarType() != MVT::f16 ||
5899 ST->hasFP16Denormals();
5901 case ISD::FP_EXTEND:
5902 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 ||
5903 ST->hasFP16Denormals();
5905 case ISD::FP16_TO_FP:
5906 case ISD::FP_TO_FP16:
5907 return ST->hasFP16Denormals();
5909 // It can/will be lowered or combined as a bit operation.
5910 // Need to check their input recursively to handle.
5913 return (MaxDepth > 0) &&
5914 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1);
5919 return Op.getValueType().getScalarType() != MVT::f16;
5921 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms.
5922 // For such targets need to check their input recursively.
5928 if (ST->supportsMinMaxDenormModes() &&
5929 DAG.isKnownNeverNaN(Op.getOperand(0)) &&
5930 DAG.isKnownNeverNaN(Op.getOperand(1)))
5933 return (MaxDepth > 0) &&
5934 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) &&
5935 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1);
5937 case ISD::ConstantFP: {
5938 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF();
5939 return !F.isDenormal() && !(F.isNaN() && F.isSignaling());
5945 // Constant fold canonicalize.
5946 SDValue SITargetLowering::performFCanonicalizeCombine(
5948 DAGCombinerInfo &DCI) const {
5949 SelectionDAG &DAG = DCI.DAG;
5950 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
5953 SDValue N0 = N->getOperand(0);
5954 EVT VT = N0.getValueType().getScalarType();
5955 auto ST = getSubtarget();
5957 if (((VT == MVT::f32 && ST->hasFP32Denormals()) ||
5958 (VT == MVT::f64 && ST->hasFP64Denormals()) ||
5959 (VT == MVT::f16 && ST->hasFP16Denormals())) &&
5960 DAG.isKnownNeverNaN(N0))
5963 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
5965 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) &&
5966 isCanonicalized(DAG, N0, ST))
5972 const APFloat &C = CFP->getValueAPF();
5974 // Flush denormals to 0 if not enabled.
5975 if (C.isDenormal()) {
5976 EVT VT = N->getValueType(0);
5977 EVT SVT = VT.getScalarType();
5978 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
5979 return DAG.getConstantFP(0.0, SDLoc(N), VT);
5981 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
5982 return DAG.getConstantFP(0.0, SDLoc(N), VT);
5984 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
5985 return DAG.getConstantFP(0.0, SDLoc(N), VT);
5989 EVT VT = N->getValueType(0);
5990 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
5991 if (C.isSignaling()) {
5992 // Quiet a signaling NaN.
5993 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
5996 // Make sure it is the canonical NaN bitpattern.
5998 // TODO: Can we use -1 as the canonical NaN value since it's an inline
6000 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
6001 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6004 return N->getOperand(0);
6007 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
6010 return AMDGPUISD::FMAX3;
6012 return AMDGPUISD::SMAX3;
6014 return AMDGPUISD::UMAX3;
6016 return AMDGPUISD::FMIN3;
6018 return AMDGPUISD::SMIN3;
6020 return AMDGPUISD::UMIN3;
6022 llvm_unreachable("Not a min/max opcode");
6026 SDValue SITargetLowering::performIntMed3ImmCombine(
6027 SelectionDAG &DAG, const SDLoc &SL,
6028 SDValue Op0, SDValue Op1, bool Signed) const {
6029 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
6033 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
6038 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
6041 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
6045 EVT VT = K0->getValueType(0);
6046 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
6047 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
6048 return DAG.getNode(Med3Opc, SL, VT,
6049 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
6052 // If there isn't a 16-bit med3 operation, convert to 32-bit.
6054 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6056 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
6057 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
6058 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
6060 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
6061 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
6064 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
6065 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
6068 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
6069 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
6076 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
6079 SDValue Op1) const {
6080 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
6084 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
6088 // Ordered >= (although NaN inputs should have folded away by now).
6089 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
6090 if (Cmp == APFloat::cmpGreaterThan)
6093 // TODO: Check IEEE bit enabled?
6094 EVT VT = Op0.getValueType();
6095 if (Subtarget->enableDX10Clamp()) {
6096 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
6097 // hardware fmed3 behavior converting to a min.
6098 // FIXME: Should this be allowing -0.0?
6099 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
6100 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
6103 // med3 for f16 is only available on gfx9+, and not available for v2f16.
6104 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
6105 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
6106 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
6107 // then give the other result, which is different from med3 with a NaN
6109 SDValue Var = Op0.getOperand(0);
6110 if (!isKnownNeverSNan(DAG, Var))
6113 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
6114 Var, SDValue(K0, 0), SDValue(K1, 0));
6120 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
6121 DAGCombinerInfo &DCI) const {
6122 SelectionDAG &DAG = DCI.DAG;
6124 EVT VT = N->getValueType(0);
6125 unsigned Opc = N->getOpcode();
6126 SDValue Op0 = N->getOperand(0);
6127 SDValue Op1 = N->getOperand(1);
6129 // Only do this if the inner op has one use since this will just increases
6130 // register pressure for no benefit.
6133 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
6135 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
6136 // max(max(a, b), c) -> max3(a, b, c)
6137 // min(min(a, b), c) -> min3(a, b, c)
6138 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
6140 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
6149 // max(a, max(b, c)) -> max3(a, b, c)
6150 // min(a, min(b, c)) -> min3(a, b, c)
6151 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
6153 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
6162 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
6163 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
6164 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
6168 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
6169 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
6173 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
6174 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
6175 (Opc == AMDGPUISD::FMIN_LEGACY &&
6176 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
6177 (VT == MVT::f32 || VT == MVT::f64 ||
6178 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
6179 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
6181 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
6188 static bool isClampZeroToOne(SDValue A, SDValue B) {
6189 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
6190 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
6191 // FIXME: Should this be allowing -0.0?
6192 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
6193 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
6200 // FIXME: Should only worry about snans for version with chain.
6201 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
6202 DAGCombinerInfo &DCI) const {
6203 EVT VT = N->getValueType(0);
6204 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
6205 // NaNs. With a NaN input, the order of the operands may change the result.
6207 SelectionDAG &DAG = DCI.DAG;
6210 SDValue Src0 = N->getOperand(0);
6211 SDValue Src1 = N->getOperand(1);
6212 SDValue Src2 = N->getOperand(2);
6214 if (isClampZeroToOne(Src0, Src1)) {
6215 // const_a, const_b, x -> clamp is safe in all cases including signaling
6217 // FIXME: Should this be allowing -0.0?
6218 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
6221 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
6222 // handling no dx10-clamp?
6223 if (Subtarget->enableDX10Clamp()) {
6224 // If NaNs is clamped to 0, we are free to reorder the inputs.
6226 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6227 std::swap(Src0, Src1);
6229 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
6230 std::swap(Src1, Src2);
6232 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6233 std::swap(Src0, Src1);
6235 if (isClampZeroToOne(Src1, Src2))
6236 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
6242 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
6243 DAGCombinerInfo &DCI) const {
6244 SDValue Src0 = N->getOperand(0);
6245 SDValue Src1 = N->getOperand(1);
6246 if (Src0.isUndef() && Src1.isUndef())
6247 return DCI.DAG.getUNDEF(N->getValueType(0));
6251 SDValue SITargetLowering::performExtractVectorEltCombine(
6252 SDNode *N, DAGCombinerInfo &DCI) const {
6253 SDValue Vec = N->getOperand(0);
6255 SelectionDAG &DAG = DCI.DAG;
6256 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) {
6258 EVT EltVT = N->getValueType(0);
6259 SDValue Idx = N->getOperand(1);
6260 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6261 Vec.getOperand(0), Idx);
6262 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt);
6268 static bool convertBuildVectorCastElt(SelectionDAG &DAG,
6269 SDValue &Lo, SDValue &Hi) {
6270 if (Hi.getOpcode() == ISD::BITCAST &&
6271 Hi.getOperand(0).getValueType() == MVT::f16 &&
6272 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) {
6273 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo);
6274 Hi = Hi.getOperand(0);
6281 SDValue SITargetLowering::performBuildVectorCombine(
6282 SDNode *N, DAGCombinerInfo &DCI) const {
6285 if (!isTypeLegal(MVT::v2i16))
6287 SelectionDAG &DAG = DCI.DAG;
6288 EVT VT = N->getValueType(0);
6290 if (VT == MVT::v2i16) {
6291 SDValue Lo = N->getOperand(0);
6292 SDValue Hi = N->getOperand(1);
6294 // v2i16 build_vector (const|undef), (bitcast f16:$x)
6295 // -> bitcast (v2f16 build_vector const|undef, $x
6296 if (convertBuildVectorCastElt(DAG, Lo, Hi)) {
6297 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi });
6298 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6301 if (convertBuildVectorCastElt(DAG, Hi, Lo)) {
6302 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo });
6303 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6310 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
6312 const SDNode *N1) const {
6313 EVT VT = N0->getValueType(0);
6315 // Only do this if we are not trying to support denormals. v_mad_f32 does not
6316 // support denormals ever.
6317 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
6318 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
6321 const TargetOptions &Options = DAG.getTarget().Options;
6322 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
6323 (N0->getFlags().hasUnsafeAlgebra() &&
6324 N1->getFlags().hasUnsafeAlgebra())) &&
6325 isFMAFasterThanFMulAndFAdd(VT)) {
6332 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
6334 SDValue N0, SDValue N1, SDValue N2,
6336 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
6337 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
6338 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
6339 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
6342 SDValue SITargetLowering::performAddCombine(SDNode *N,
6343 DAGCombinerInfo &DCI) const {
6344 SelectionDAG &DAG = DCI.DAG;
6345 EVT VT = N->getValueType(0);
6347 SDValue LHS = N->getOperand(0);
6348 SDValue RHS = N->getOperand(1);
6350 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
6351 && Subtarget->hasMad64_32() &&
6352 !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
6353 VT.getScalarSizeInBits() <= 64) {
6354 if (LHS.getOpcode() != ISD::MUL)
6355 std::swap(LHS, RHS);
6357 SDValue MulLHS = LHS.getOperand(0);
6358 SDValue MulRHS = LHS.getOperand(1);
6359 SDValue AddRHS = RHS;
6361 // TODO: Maybe restrict if SGPR inputs.
6362 if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
6363 numBitsUnsigned(MulRHS, DAG) <= 32) {
6364 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
6365 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
6366 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
6367 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
6370 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
6371 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
6372 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
6373 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
6374 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
6383 // add x, zext (setcc) => addcarry x, 0, setcc
6384 // add x, sext (setcc) => subcarry x, 0, setcc
6385 unsigned Opc = LHS.getOpcode();
6386 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
6387 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
6388 std::swap(RHS, LHS);
6390 Opc = RHS.getOpcode();
6393 case ISD::ZERO_EXTEND:
6394 case ISD::SIGN_EXTEND:
6395 case ISD::ANY_EXTEND: {
6396 auto Cond = RHS.getOperand(0);
6397 if (!isBoolSGPR(Cond))
6399 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
6400 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
6401 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
6402 return DAG.getNode(Opc, SL, VTList, Args);
6404 case ISD::ADDCARRY: {
6405 // add x, (addcarry y, 0, cc) => addcarry x, y, cc
6406 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6407 if (!C || C->getZExtValue() != 0) break;
6408 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
6409 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
6415 SDValue SITargetLowering::performSubCombine(SDNode *N,
6416 DAGCombinerInfo &DCI) const {
6417 SelectionDAG &DAG = DCI.DAG;
6418 EVT VT = N->getValueType(0);
6424 SDValue LHS = N->getOperand(0);
6425 SDValue RHS = N->getOperand(1);
6427 unsigned Opc = LHS.getOpcode();
6428 if (Opc != ISD::SUBCARRY)
6429 std::swap(RHS, LHS);
6431 if (LHS.getOpcode() == ISD::SUBCARRY) {
6432 // sub (subcarry x, 0, cc), y => subcarry x, y, cc
6433 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6434 if (!C || C->getZExtValue() != 0)
6436 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
6437 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
6442 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
6443 DAGCombinerInfo &DCI) const {
6445 if (N->getValueType(0) != MVT::i32)
6448 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6449 if (!C || C->getZExtValue() != 0)
6452 SelectionDAG &DAG = DCI.DAG;
6453 SDValue LHS = N->getOperand(0);
6455 // addcarry (add x, y), 0, cc => addcarry x, y, cc
6456 // subcarry (sub x, y), 0, cc => subcarry x, y, cc
6457 unsigned LHSOpc = LHS.getOpcode();
6458 unsigned Opc = N->getOpcode();
6459 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
6460 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
6461 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
6462 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
6467 SDValue SITargetLowering::performFAddCombine(SDNode *N,
6468 DAGCombinerInfo &DCI) const {
6469 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6472 SelectionDAG &DAG = DCI.DAG;
6473 EVT VT = N->getValueType(0);
6476 SDValue LHS = N->getOperand(0);
6477 SDValue RHS = N->getOperand(1);
6479 // These should really be instruction patterns, but writing patterns with
6480 // source modiifiers is a pain.
6482 // fadd (fadd (a, a), b) -> mad 2.0, a, b
6483 if (LHS.getOpcode() == ISD::FADD) {
6484 SDValue A = LHS.getOperand(0);
6485 if (A == LHS.getOperand(1)) {
6486 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
6488 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6489 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
6494 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
6495 if (RHS.getOpcode() == ISD::FADD) {
6496 SDValue A = RHS.getOperand(0);
6497 if (A == RHS.getOperand(1)) {
6498 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
6500 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6501 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
6509 SDValue SITargetLowering::performFSubCombine(SDNode *N,
6510 DAGCombinerInfo &DCI) const {
6511 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6514 SelectionDAG &DAG = DCI.DAG;
6516 EVT VT = N->getValueType(0);
6517 assert(!VT.isVector());
6519 // Try to get the fneg to fold into the source modifier. This undoes generic
6520 // DAG combines and folds them into the mad.
6522 // Only do this if we are not trying to support denormals. v_mad_f32 does
6523 // not support denormals ever.
6524 SDValue LHS = N->getOperand(0);
6525 SDValue RHS = N->getOperand(1);
6526 if (LHS.getOpcode() == ISD::FADD) {
6527 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
6528 SDValue A = LHS.getOperand(0);
6529 if (A == LHS.getOperand(1)) {
6530 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
6532 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6533 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
6535 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
6540 if (RHS.getOpcode() == ISD::FADD) {
6541 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
6543 SDValue A = RHS.getOperand(0);
6544 if (A == RHS.getOperand(1)) {
6545 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
6547 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
6548 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
6556 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
6557 DAGCombinerInfo &DCI) const {
6558 SelectionDAG &DAG = DCI.DAG;
6561 SDValue LHS = N->getOperand(0);
6562 SDValue RHS = N->getOperand(1);
6563 EVT VT = LHS.getValueType();
6564 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
6566 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
6568 CRHS = dyn_cast<ConstantSDNode>(LHS);
6570 std::swap(LHS, RHS);
6571 CC = getSetCCSwappedOperands(CC);
6575 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
6576 isBoolSGPR(LHS.getOperand(0))) {
6577 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
6578 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
6579 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
6580 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
6581 if ((CRHS->isAllOnesValue() &&
6582 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
6583 (CRHS->isNullValue() &&
6584 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
6585 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
6586 DAG.getConstant(-1, SL, MVT::i1));
6587 if ((CRHS->isAllOnesValue() &&
6588 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
6589 (CRHS->isNullValue() &&
6590 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
6591 return LHS.getOperand(0);
6594 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
6598 // Match isinf pattern
6599 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
6600 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
6601 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
6605 const APFloat &APF = CRHS->getValueAPF();
6606 if (APF.isInfinity() && !APF.isNegative()) {
6607 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
6608 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
6609 DAG.getConstant(Mask, SL, MVT::i32));
6616 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
6617 DAGCombinerInfo &DCI) const {
6618 SelectionDAG &DAG = DCI.DAG;
6620 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
6622 SDValue Src = N->getOperand(0);
6623 SDValue Srl = N->getOperand(0);
6624 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
6625 Srl = Srl.getOperand(0);
6627 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
6628 if (Srl.getOpcode() == ISD::SRL) {
6629 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
6630 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
6631 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
6633 if (const ConstantSDNode *C =
6634 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
6635 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
6638 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
6639 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
6640 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
6646 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
6649 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
6650 !DCI.isBeforeLegalizeOps());
6651 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6652 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
6653 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
6654 DCI.CommitTargetLoweringOpt(TLO);
6660 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
6661 DAGCombinerInfo &DCI) const {
6662 switch (N->getOpcode()) {
6664 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
6666 return performAddCombine(N, DCI);
6668 return performSubCombine(N, DCI);
6671 return performAddCarrySubCarryCombine(N, DCI);
6673 return performFAddCombine(N, DCI);
6675 return performFSubCombine(N, DCI);
6677 return performSetCCCombine(N, DCI);
6684 case AMDGPUISD::FMIN_LEGACY:
6685 case AMDGPUISD::FMAX_LEGACY: {
6686 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
6687 getTargetMachine().getOptLevel() > CodeGenOpt::None)
6688 return performMinMaxCombine(N, DCI);
6693 case ISD::ATOMIC_LOAD:
6694 case ISD::ATOMIC_STORE:
6695 case ISD::ATOMIC_CMP_SWAP:
6696 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
6697 case ISD::ATOMIC_SWAP:
6698 case ISD::ATOMIC_LOAD_ADD:
6699 case ISD::ATOMIC_LOAD_SUB:
6700 case ISD::ATOMIC_LOAD_AND:
6701 case ISD::ATOMIC_LOAD_OR:
6702 case ISD::ATOMIC_LOAD_XOR:
6703 case ISD::ATOMIC_LOAD_NAND:
6704 case ISD::ATOMIC_LOAD_MIN:
6705 case ISD::ATOMIC_LOAD_MAX:
6706 case ISD::ATOMIC_LOAD_UMIN:
6707 case ISD::ATOMIC_LOAD_UMAX:
6708 case AMDGPUISD::ATOMIC_INC:
6709 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
6710 if (DCI.isBeforeLegalize())
6712 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
6714 return performAndCombine(N, DCI);
6716 return performOrCombine(N, DCI);
6718 return performXorCombine(N, DCI);
6719 case ISD::ZERO_EXTEND:
6720 return performZeroExtendCombine(N, DCI);
6721 case AMDGPUISD::FP_CLASS:
6722 return performClassCombine(N, DCI);
6723 case ISD::FCANONICALIZE:
6724 return performFCanonicalizeCombine(N, DCI);
6725 case AMDGPUISD::FRACT:
6726 case AMDGPUISD::RCP:
6727 case AMDGPUISD::RSQ:
6728 case AMDGPUISD::RCP_LEGACY:
6729 case AMDGPUISD::RSQ_LEGACY:
6730 case AMDGPUISD::RSQ_CLAMP:
6731 case AMDGPUISD::LDEXP: {
6732 SDValue Src = N->getOperand(0);
6737 case ISD::SINT_TO_FP:
6738 case ISD::UINT_TO_FP:
6739 return performUCharToFloatCombine(N, DCI);
6740 case AMDGPUISD::CVT_F32_UBYTE0:
6741 case AMDGPUISD::CVT_F32_UBYTE1:
6742 case AMDGPUISD::CVT_F32_UBYTE2:
6743 case AMDGPUISD::CVT_F32_UBYTE3:
6744 return performCvtF32UByteNCombine(N, DCI);
6745 case AMDGPUISD::FMED3:
6746 return performFMed3Combine(N, DCI);
6747 case AMDGPUISD::CVT_PKRTZ_F16_F32:
6748 return performCvtPkRTZCombine(N, DCI);
6749 case ISD::SCALAR_TO_VECTOR: {
6750 SelectionDAG &DAG = DCI.DAG;
6751 EVT VT = N->getValueType(0);
6753 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
6754 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
6756 SDValue Src = N->getOperand(0);
6757 EVT EltVT = Src.getValueType();
6758 if (EltVT == MVT::f16)
6759 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
6761 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
6762 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
6767 case ISD::EXTRACT_VECTOR_ELT:
6768 return performExtractVectorEltCombine(N, DCI);
6769 case ISD::BUILD_VECTOR:
6770 return performBuildVectorCombine(N, DCI);
6772 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
6775 /// \brief Helper function for adjustWritemask
6776 static unsigned SubIdx2Lane(unsigned Idx) {
6779 case AMDGPU::sub0: return 0;
6780 case AMDGPU::sub1: return 1;
6781 case AMDGPU::sub2: return 2;
6782 case AMDGPU::sub3: return 3;
6786 /// \brief Adjust the writemask of MIMG instructions
6787 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
6788 SelectionDAG &DAG) const {
6789 SDNode *Users[4] = { nullptr };
6791 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
6792 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
6793 unsigned NewDmask = 0;
6794 bool HasChain = Node->getNumValues() > 1;
6796 if (OldDmask == 0) {
6797 // These are folded out, but on the chance it happens don't assert.
6801 // Try to figure out the used register components
6802 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
6805 // Don't look at users of the chain.
6806 if (I.getUse().getResNo() != 0)
6809 // Abort if we can't understand the usage
6810 if (!I->isMachineOpcode() ||
6811 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
6814 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
6815 // Note that subregs are packed, i.e. Lane==0 is the first bit set
6816 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
6818 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
6820 // Set which texture component corresponds to the lane.
6822 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
6823 Comp = countTrailingZeros(Dmask);
6824 Dmask &= ~(1 << Comp);
6827 // Abort if we have more than one user per component
6832 NewDmask |= 1 << Comp;
6835 // Abort if there's no change
6836 if (NewDmask == OldDmask)
6839 unsigned BitsSet = countPopulation(NewDmask);
6841 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6842 int NewOpcode = AMDGPU::getMaskedMIMGOp(*TII,
6843 Node->getMachineOpcode(), BitsSet);
6844 assert(NewOpcode != -1 &&
6845 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
6846 "failed to find equivalent MIMG op");
6848 // Adjust the writemask in the node
6849 SmallVector<SDValue, 12> Ops;
6850 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
6851 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
6852 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
6854 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
6856 MVT ResultVT = BitsSet == 1 ?
6857 SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet);
6858 SDVTList NewVTList = HasChain ?
6859 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
6862 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
6867 NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end());
6868 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
6872 assert(Node->hasNUsesOfValue(1, 0));
6873 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
6874 SDLoc(Node), Users[Lane]->getValueType(0),
6875 SDValue(NewNode, 0));
6876 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
6880 // Update the users of the node with the new indices
6881 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
6882 SDNode *User = Users[i];
6886 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
6887 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
6891 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
6892 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
6893 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
6897 DAG.RemoveDeadNode(Node);
6901 static bool isFrameIndexOp(SDValue Op) {
6902 if (Op.getOpcode() == ISD::AssertZext)
6903 Op = Op.getOperand(0);
6905 return isa<FrameIndexSDNode>(Op);
6908 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
6909 /// with frame index operands.
6910 /// LLVM assumes that inputs are to these instructions are registers.
6911 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
6912 SelectionDAG &DAG) const {
6913 if (Node->getOpcode() == ISD::CopyToReg) {
6914 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
6915 SDValue SrcVal = Node->getOperand(2);
6917 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
6918 // to try understanding copies to physical registers.
6919 if (SrcVal.getValueType() == MVT::i1 &&
6920 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
6922 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
6923 SDValue VReg = DAG.getRegister(
6924 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
6926 SDNode *Glued = Node->getGluedNode();
6928 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
6929 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
6931 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
6932 VReg, ToVReg.getValue(1));
6933 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
6934 DAG.RemoveDeadNode(Node);
6935 return ToResultReg.getNode();
6939 SmallVector<SDValue, 8> Ops;
6940 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
6941 if (!isFrameIndexOp(Node->getOperand(i))) {
6942 Ops.push_back(Node->getOperand(i));
6947 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
6948 Node->getOperand(i).getValueType(),
6949 Node->getOperand(i)), 0));
6952 return DAG.UpdateNodeOperands(Node, Ops);
6955 /// \brief Fold the instructions after selecting them.
6956 /// Returns null if users were already updated.
6957 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
6958 SelectionDAG &DAG) const {
6959 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6960 unsigned Opcode = Node->getMachineOpcode();
6962 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
6963 !TII->isGather4(Opcode)) {
6964 return adjustWritemask(Node, DAG);
6967 if (Opcode == AMDGPU::INSERT_SUBREG ||
6968 Opcode == AMDGPU::REG_SEQUENCE) {
6969 legalizeTargetIndependentNode(Node, DAG);
6974 case AMDGPU::V_DIV_SCALE_F32:
6975 case AMDGPU::V_DIV_SCALE_F64: {
6976 // Satisfy the operand register constraint when one of the inputs is
6977 // undefined. Ordinarily each undef value will have its own implicit_def of
6978 // a vreg, so force these to use a single register.
6979 SDValue Src0 = Node->getOperand(0);
6980 SDValue Src1 = Node->getOperand(1);
6981 SDValue Src2 = Node->getOperand(2);
6983 if ((Src0.isMachineOpcode() &&
6984 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
6985 (Src0 == Src1 || Src0 == Src2))
6988 MVT VT = Src0.getValueType().getSimpleVT();
6989 const TargetRegisterClass *RC = getRegClassFor(VT);
6991 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
6992 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
6994 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
6995 UndefReg, Src0, SDValue());
6997 // src0 must be the same register as src1 or src2, even if the value is
6998 // undefined, so make sure we don't violate this constraint.
6999 if (Src0.isMachineOpcode() &&
7000 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
7001 if (Src1.isMachineOpcode() &&
7002 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
7004 else if (Src2.isMachineOpcode() &&
7005 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
7008 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
7015 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
7016 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
7017 Ops.push_back(Node->getOperand(I));
7019 Ops.push_back(ImpDef.getValue(1));
7020 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
7029 /// \brief Assign the register class depending on the number of
7030 /// bits set in the writemask
7031 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
7032 SDNode *Node) const {
7033 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7035 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7037 if (TII->isVOP3(MI.getOpcode())) {
7038 // Make sure constant bus requirements are respected.
7039 TII->legalizeOperandsVOP3(MRI, MI);
7043 // Replace unused atomics with the no return version.
7044 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
7045 if (NoRetAtomicOp != -1) {
7046 if (!Node->hasAnyUseOfValue(0)) {
7047 MI.setDesc(TII->get(NoRetAtomicOp));
7048 MI.RemoveOperand(0);
7052 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
7053 // instruction, because the return type of these instructions is a vec2 of
7054 // the memory type, so it can be tied to the input operand.
7055 // This means these instructions always have a use, so we need to add a
7056 // special case to check if the atomic has only one extract_subreg use,
7057 // which itself has no uses.
7058 if ((Node->hasNUsesOfValue(1, 0) &&
7059 Node->use_begin()->isMachineOpcode() &&
7060 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
7061 !Node->use_begin()->hasAnyUseOfValue(0))) {
7062 unsigned Def = MI.getOperand(0).getReg();
7064 // Change this into a noret atomic.
7065 MI.setDesc(TII->get(NoRetAtomicOp));
7066 MI.RemoveOperand(0);
7068 // If we only remove the def operand from the atomic instruction, the
7069 // extract_subreg will be left with a use of a vreg without a def.
7070 // So we need to insert an implicit_def to avoid machine verifier
7072 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
7073 TII->get(AMDGPU::IMPLICIT_DEF), Def);
7079 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
7081 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
7082 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
7085 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
7087 SDValue Ptr) const {
7088 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7090 // Build the half of the subregister with the constants before building the
7091 // full 128-bit register. If we are building multiple resource descriptors,
7092 // this will allow CSEing of the 2-component register.
7093 const SDValue Ops0[] = {
7094 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
7095 buildSMovImm32(DAG, DL, 0),
7096 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
7097 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
7098 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
7101 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
7102 MVT::v2i32, Ops0), 0);
7104 // Combine the constants and the pointer.
7105 const SDValue Ops1[] = {
7106 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
7108 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
7110 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
7113 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
7116 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
7117 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
7118 /// of the resource descriptor) to create an offset, which is added to
7119 /// the resource pointer.
7120 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
7121 SDValue Ptr, uint32_t RsrcDword1,
7122 uint64_t RsrcDword2And3) const {
7123 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
7124 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
7126 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
7127 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
7131 SDValue DataLo = buildSMovImm32(DAG, DL,
7132 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
7133 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
7135 const SDValue Ops[] = {
7136 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
7138 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
7140 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
7142 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
7144 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
7147 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
7150 //===----------------------------------------------------------------------===//
7151 // SI Inline Assembly Support
7152 //===----------------------------------------------------------------------===//
7154 std::pair<unsigned, const TargetRegisterClass *>
7155 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
7156 StringRef Constraint,
7158 if (!isTypeLegal(VT))
7159 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7161 if (Constraint.size() == 1) {
7162 switch (Constraint[0]) {
7165 switch (VT.getSizeInBits()) {
7167 return std::make_pair(0U, nullptr);
7170 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
7172 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
7174 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
7176 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
7178 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
7182 switch (VT.getSizeInBits()) {
7184 return std::make_pair(0U, nullptr);
7187 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
7189 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
7191 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
7193 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
7195 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
7197 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
7202 if (Constraint.size() > 1) {
7203 const TargetRegisterClass *RC = nullptr;
7204 if (Constraint[1] == 'v') {
7205 RC = &AMDGPU::VGPR_32RegClass;
7206 } else if (Constraint[1] == 's') {
7207 RC = &AMDGPU::SGPR_32RegClass;
7212 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
7213 if (!Failed && Idx < RC->getNumRegs())
7214 return std::make_pair(RC->getRegister(Idx), RC);
7217 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7220 SITargetLowering::ConstraintType
7221 SITargetLowering::getConstraintType(StringRef Constraint) const {
7222 if (Constraint.size() == 1) {
7223 switch (Constraint[0]) {
7227 return C_RegisterClass;
7230 return TargetLowering::getConstraintType(Constraint);
7233 // Figure out which registers should be reserved for stack access. Only after
7234 // the function is legalized do we know all of the non-spill stack objects or if
7235 // calls are present.
7236 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
7237 MachineRegisterInfo &MRI = MF.getRegInfo();
7238 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
7239 const MachineFrameInfo &MFI = MF.getFrameInfo();
7240 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
7241 const SIRegisterInfo *TRI = ST.getRegisterInfo();
7243 if (Info->isEntryFunction()) {
7244 // Callable functions have fixed registers used for stack access.
7245 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
7248 // We have to assume the SP is needed in case there are calls in the function
7249 // during lowering. Calls are only detected after the function is
7250 // lowered. We're about to reserve registers, so don't bother using it if we
7251 // aren't really going to use it.
7252 bool NeedSP = !Info->isEntryFunction() ||
7253 MFI.hasVarSizedObjects() ||
7257 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
7258 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
7260 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
7261 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
7262 Info->getStackPtrOffsetReg()));
7263 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
7266 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
7267 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
7268 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
7269 Info->getScratchWaveOffsetReg());
7271 TargetLoweringBase::finalizeLowering(MF);
7274 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
7276 const APInt &DemandedElts,
7277 const SelectionDAG &DAG,
7278 unsigned Depth) const {
7279 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
7282 if (getSubtarget()->enableHugePrivateBuffer())
7285 // Technically it may be possible to have a dispatch with a single workitem
7286 // that uses the full private memory size, but that's not really useful. We
7287 // can't use vaddr in MUBUF instructions if we don't know the address
7288 // calculation won't overflow, so assume the sign bit is never set.
7289 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);