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/SelectionDAG.h"
53 #include "llvm/CodeGen/SelectionDAGNodes.h"
54 #include "llvm/CodeGen/TargetCallingConv.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/ValueTypes.h"
57 #include "llvm/IR/Constants.h"
58 #include "llvm/IR/DataLayout.h"
59 #include "llvm/IR/DebugLoc.h"
60 #include "llvm/IR/DerivedTypes.h"
61 #include "llvm/IR/DiagnosticInfo.h"
62 #include "llvm/IR/Function.h"
63 #include "llvm/IR/GlobalValue.h"
64 #include "llvm/IR/InstrTypes.h"
65 #include "llvm/IR/Instruction.h"
66 #include "llvm/IR/Instructions.h"
67 #include "llvm/IR/IntrinsicInst.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/CodeGen.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Compiler.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/KnownBits.h"
75 #include "llvm/Support/MachineValueType.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<bool> EnableDS128(
99 cl::desc("Use DS_read/write_b128"),
102 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
103 "amdgpu-frame-index-zero-bits",
104 cl::desc("High bits of frame index assumed to be zero"),
108 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
109 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
110 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
111 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
112 return AMDGPU::SGPR0 + Reg;
115 llvm_unreachable("Cannot allocate sgpr");
118 SITargetLowering::SITargetLowering(const TargetMachine &TM,
119 const SISubtarget &STI)
120 : AMDGPUTargetLowering(TM, STI) {
121 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
122 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
124 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
125 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
127 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
128 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
129 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
131 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
132 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
134 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
135 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
137 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
138 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
140 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
141 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
143 if (Subtarget->has16BitInsts()) {
144 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
145 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
148 if (Subtarget->hasVOP3PInsts()) {
149 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
150 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
153 computeRegisterProperties(STI.getRegisterInfo());
155 // We need to custom lower vector stores from local memory
156 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
157 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
158 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
159 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
160 setOperationAction(ISD::LOAD, MVT::i1, Custom);
162 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
163 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
164 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
165 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
166 setOperationAction(ISD::STORE, MVT::i1, Custom);
168 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
169 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
170 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
171 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
172 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
173 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
174 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
175 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
176 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
177 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
179 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
180 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
181 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
183 setOperationAction(ISD::SELECT, MVT::i1, Promote);
184 setOperationAction(ISD::SELECT, MVT::i64, Custom);
185 setOperationAction(ISD::SELECT, MVT::f64, Promote);
186 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
188 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
189 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
190 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
191 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
192 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
194 setOperationAction(ISD::SETCC, MVT::i1, Promote);
195 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
196 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
197 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
199 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
200 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
206 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
207 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
208 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
210 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
211 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
212 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
213 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
214 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
216 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
217 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
218 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
220 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
221 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
222 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
223 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
225 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
226 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
227 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
228 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
229 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
230 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
232 setOperationAction(ISD::UADDO, MVT::i32, Legal);
233 setOperationAction(ISD::USUBO, MVT::i32, Legal);
235 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
236 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
239 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
240 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
243 //setOperationAction(ISD::ADDC, MVT::i64, Expand);
244 //setOperationAction(ISD::SUBC, MVT::i64, Expand);
246 // We only support LOAD/STORE and vector manipulation ops for vectors
247 // with > 4 elements.
248 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
249 MVT::v2i64, MVT::v2f64}) {
250 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
254 case ISD::BUILD_VECTOR:
256 case ISD::EXTRACT_VECTOR_ELT:
257 case ISD::INSERT_VECTOR_ELT:
258 case ISD::INSERT_SUBVECTOR:
259 case ISD::EXTRACT_SUBVECTOR:
260 case ISD::SCALAR_TO_VECTOR:
262 case ISD::CONCAT_VECTORS:
263 setOperationAction(Op, VT, Custom);
266 setOperationAction(Op, VT, Expand);
272 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
273 // is expanded to avoid having two separate loops in case the index is a VGPR.
275 // Most operations are naturally 32-bit vector operations. We only support
276 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
277 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
278 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
279 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
281 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
282 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
284 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
285 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
287 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
288 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
291 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
292 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
293 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
294 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
296 // Avoid stack access for these.
297 // TODO: Generalize to more vector types.
298 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
299 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
300 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
301 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
303 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
304 // and output demarshalling
305 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
306 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
308 // We can't return success/failure, only the old value,
309 // let LLVM add the comparison
310 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
311 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
313 if (getSubtarget()->hasFlatAddressSpace()) {
314 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
315 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
318 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
319 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
321 // On SI this is s_memtime and s_memrealtime on VI.
322 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
323 setOperationAction(ISD::TRAP, MVT::Other, Custom);
324 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
326 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
327 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
329 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
330 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
331 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
332 setOperationAction(ISD::FRINT, MVT::f64, Legal);
335 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
337 setOperationAction(ISD::FSIN, MVT::f32, Custom);
338 setOperationAction(ISD::FCOS, MVT::f32, Custom);
339 setOperationAction(ISD::FDIV, MVT::f32, Custom);
340 setOperationAction(ISD::FDIV, MVT::f64, Custom);
342 if (Subtarget->has16BitInsts()) {
343 setOperationAction(ISD::Constant, MVT::i16, Legal);
345 setOperationAction(ISD::SMIN, MVT::i16, Legal);
346 setOperationAction(ISD::SMAX, MVT::i16, Legal);
348 setOperationAction(ISD::UMIN, MVT::i16, Legal);
349 setOperationAction(ISD::UMAX, MVT::i16, Legal);
351 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
352 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
354 setOperationAction(ISD::ROTR, MVT::i16, Promote);
355 setOperationAction(ISD::ROTL, MVT::i16, Promote);
357 setOperationAction(ISD::SDIV, MVT::i16, Promote);
358 setOperationAction(ISD::UDIV, MVT::i16, Promote);
359 setOperationAction(ISD::SREM, MVT::i16, Promote);
360 setOperationAction(ISD::UREM, MVT::i16, Promote);
362 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
363 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
365 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
366 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
367 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
368 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
369 setOperationAction(ISD::CTPOP, MVT::i16, Promote);
371 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
373 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
375 setOperationAction(ISD::LOAD, MVT::i16, Custom);
377 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
379 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
380 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
381 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
382 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
384 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
385 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
386 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
387 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
389 // F16 - Constant Actions.
390 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
392 // F16 - Load/Store Actions.
393 setOperationAction(ISD::LOAD, MVT::f16, Promote);
394 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
395 setOperationAction(ISD::STORE, MVT::f16, Promote);
396 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
398 // F16 - VOP1 Actions.
399 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
400 setOperationAction(ISD::FCOS, MVT::f16, Promote);
401 setOperationAction(ISD::FSIN, MVT::f16, Promote);
402 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
403 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
404 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
405 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
406 setOperationAction(ISD::FROUND, MVT::f16, Custom);
408 // F16 - VOP2 Actions.
409 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
410 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
411 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
412 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
413 setOperationAction(ISD::FDIV, MVT::f16, Custom);
415 // F16 - VOP3 Actions.
416 setOperationAction(ISD::FMA, MVT::f16, Legal);
417 if (!Subtarget->hasFP16Denormals())
418 setOperationAction(ISD::FMAD, MVT::f16, Legal);
421 if (Subtarget->hasVOP3PInsts()) {
422 for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
423 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
427 case ISD::BUILD_VECTOR:
429 case ISD::EXTRACT_VECTOR_ELT:
430 case ISD::INSERT_VECTOR_ELT:
431 case ISD::INSERT_SUBVECTOR:
432 case ISD::EXTRACT_SUBVECTOR:
433 case ISD::SCALAR_TO_VECTOR:
435 case ISD::CONCAT_VECTORS:
436 setOperationAction(Op, VT, Custom);
439 setOperationAction(Op, VT, Expand);
445 // XXX - Do these do anything? Vector constants turn into build_vector.
446 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
447 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
449 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
450 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
451 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
452 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
454 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
455 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
456 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
457 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
459 setOperationAction(ISD::AND, MVT::v2i16, Promote);
460 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
461 setOperationAction(ISD::OR, MVT::v2i16, Promote);
462 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
463 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
464 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
465 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
466 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
467 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
468 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
470 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
471 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
472 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
473 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
474 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
475 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
476 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
477 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
478 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
479 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
481 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
482 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
483 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
484 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
485 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
486 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
488 // This isn't really legal, but this avoids the legalizer unrolling it (and
489 // allows matching fneg (fabs x) patterns)
490 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
492 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
493 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
495 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
496 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
497 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
498 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
500 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
501 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
504 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
505 setOperationAction(ISD::SELECT, VT, Custom);
508 setTargetDAGCombine(ISD::ADD);
509 setTargetDAGCombine(ISD::ADDCARRY);
510 setTargetDAGCombine(ISD::SUB);
511 setTargetDAGCombine(ISD::SUBCARRY);
512 setTargetDAGCombine(ISD::FADD);
513 setTargetDAGCombine(ISD::FSUB);
514 setTargetDAGCombine(ISD::FMINNUM);
515 setTargetDAGCombine(ISD::FMAXNUM);
516 setTargetDAGCombine(ISD::SMIN);
517 setTargetDAGCombine(ISD::SMAX);
518 setTargetDAGCombine(ISD::UMIN);
519 setTargetDAGCombine(ISD::UMAX);
520 setTargetDAGCombine(ISD::SETCC);
521 setTargetDAGCombine(ISD::AND);
522 setTargetDAGCombine(ISD::OR);
523 setTargetDAGCombine(ISD::XOR);
524 setTargetDAGCombine(ISD::SINT_TO_FP);
525 setTargetDAGCombine(ISD::UINT_TO_FP);
526 setTargetDAGCombine(ISD::FCANONICALIZE);
527 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
528 setTargetDAGCombine(ISD::ZERO_EXTEND);
529 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
530 setTargetDAGCombine(ISD::BUILD_VECTOR);
532 // All memory operations. Some folding on the pointer operand is done to help
533 // matching the constant offsets in the addressing modes.
534 setTargetDAGCombine(ISD::LOAD);
535 setTargetDAGCombine(ISD::STORE);
536 setTargetDAGCombine(ISD::ATOMIC_LOAD);
537 setTargetDAGCombine(ISD::ATOMIC_STORE);
538 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
539 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
540 setTargetDAGCombine(ISD::ATOMIC_SWAP);
541 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
542 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
543 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
544 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
545 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
546 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
547 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
548 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
549 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
550 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
552 setSchedulingPreference(Sched::RegPressure);
555 const SISubtarget *SITargetLowering::getSubtarget() const {
556 return static_cast<const SISubtarget *>(Subtarget);
559 //===----------------------------------------------------------------------===//
560 // TargetLowering queries
561 //===----------------------------------------------------------------------===//
563 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
564 // SI has some legal vector types, but no legal vector operations. Say no
565 // shuffles are legal in order to prefer scalarizing some vector operations.
569 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
572 unsigned IntrID) const {
574 case Intrinsic::amdgcn_atomic_inc:
575 case Intrinsic::amdgcn_atomic_dec:
576 case Intrinsic::amdgcn_ds_fadd:
577 case Intrinsic::amdgcn_ds_fmin:
578 case Intrinsic::amdgcn_ds_fmax: {
579 Info.opc = ISD::INTRINSIC_W_CHAIN;
580 Info.memVT = MVT::getVT(CI.getType());
581 Info.ptrVal = CI.getOperand(0);
583 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
585 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
586 if (!Vol || !Vol->isZero())
587 Info.flags |= MachineMemOperand::MOVolatile;
593 case Intrinsic::amdgcn_image_load:
594 case Intrinsic::amdgcn_image_load_mip:
597 case Intrinsic::amdgcn_image_sample:
598 case Intrinsic::amdgcn_image_sample_cl:
599 case Intrinsic::amdgcn_image_sample_d:
600 case Intrinsic::amdgcn_image_sample_d_cl:
601 case Intrinsic::amdgcn_image_sample_l:
602 case Intrinsic::amdgcn_image_sample_b:
603 case Intrinsic::amdgcn_image_sample_b_cl:
604 case Intrinsic::amdgcn_image_sample_lz:
605 case Intrinsic::amdgcn_image_sample_cd:
606 case Intrinsic::amdgcn_image_sample_cd_cl:
608 // Sample with comparison.
609 case Intrinsic::amdgcn_image_sample_c:
610 case Intrinsic::amdgcn_image_sample_c_cl:
611 case Intrinsic::amdgcn_image_sample_c_d:
612 case Intrinsic::amdgcn_image_sample_c_d_cl:
613 case Intrinsic::amdgcn_image_sample_c_l:
614 case Intrinsic::amdgcn_image_sample_c_b:
615 case Intrinsic::amdgcn_image_sample_c_b_cl:
616 case Intrinsic::amdgcn_image_sample_c_lz:
617 case Intrinsic::amdgcn_image_sample_c_cd:
618 case Intrinsic::amdgcn_image_sample_c_cd_cl:
620 // Sample with offsets.
621 case Intrinsic::amdgcn_image_sample_o:
622 case Intrinsic::amdgcn_image_sample_cl_o:
623 case Intrinsic::amdgcn_image_sample_d_o:
624 case Intrinsic::amdgcn_image_sample_d_cl_o:
625 case Intrinsic::amdgcn_image_sample_l_o:
626 case Intrinsic::amdgcn_image_sample_b_o:
627 case Intrinsic::amdgcn_image_sample_b_cl_o:
628 case Intrinsic::amdgcn_image_sample_lz_o:
629 case Intrinsic::amdgcn_image_sample_cd_o:
630 case Intrinsic::amdgcn_image_sample_cd_cl_o:
632 // Sample with comparison and offsets.
633 case Intrinsic::amdgcn_image_sample_c_o:
634 case Intrinsic::amdgcn_image_sample_c_cl_o:
635 case Intrinsic::amdgcn_image_sample_c_d_o:
636 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
637 case Intrinsic::amdgcn_image_sample_c_l_o:
638 case Intrinsic::amdgcn_image_sample_c_b_o:
639 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
640 case Intrinsic::amdgcn_image_sample_c_lz_o:
641 case Intrinsic::amdgcn_image_sample_c_cd_o:
642 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
645 case Intrinsic::amdgcn_image_gather4:
646 case Intrinsic::amdgcn_image_gather4_cl:
647 case Intrinsic::amdgcn_image_gather4_l:
648 case Intrinsic::amdgcn_image_gather4_b:
649 case Intrinsic::amdgcn_image_gather4_b_cl:
650 case Intrinsic::amdgcn_image_gather4_lz:
652 // Gather4 with comparison
653 case Intrinsic::amdgcn_image_gather4_c:
654 case Intrinsic::amdgcn_image_gather4_c_cl:
655 case Intrinsic::amdgcn_image_gather4_c_l:
656 case Intrinsic::amdgcn_image_gather4_c_b:
657 case Intrinsic::amdgcn_image_gather4_c_b_cl:
658 case Intrinsic::amdgcn_image_gather4_c_lz:
660 // Gather4 with offsets
661 case Intrinsic::amdgcn_image_gather4_o:
662 case Intrinsic::amdgcn_image_gather4_cl_o:
663 case Intrinsic::amdgcn_image_gather4_l_o:
664 case Intrinsic::amdgcn_image_gather4_b_o:
665 case Intrinsic::amdgcn_image_gather4_b_cl_o:
666 case Intrinsic::amdgcn_image_gather4_lz_o:
668 // Gather4 with comparison and offsets
669 case Intrinsic::amdgcn_image_gather4_c_o:
670 case Intrinsic::amdgcn_image_gather4_c_cl_o:
671 case Intrinsic::amdgcn_image_gather4_c_l_o:
672 case Intrinsic::amdgcn_image_gather4_c_b_o:
673 case Intrinsic::amdgcn_image_gather4_c_b_cl_o:
674 case Intrinsic::amdgcn_image_gather4_c_lz_o: {
675 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
676 Info.opc = ISD::INTRINSIC_W_CHAIN;
677 Info.memVT = MVT::getVT(CI.getType());
678 Info.ptrVal = MFI->getImagePSV(
679 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
680 CI.getArgOperand(1));
682 Info.flags = MachineMemOperand::MOLoad |
683 MachineMemOperand::MODereferenceable;
686 case Intrinsic::amdgcn_image_store:
687 case Intrinsic::amdgcn_image_store_mip: {
688 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
689 Info.opc = ISD::INTRINSIC_VOID;
690 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
691 Info.ptrVal = MFI->getImagePSV(
692 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
693 CI.getArgOperand(2));
694 Info.flags = MachineMemOperand::MOStore |
695 MachineMemOperand::MODereferenceable;
699 case Intrinsic::amdgcn_image_atomic_swap:
700 case Intrinsic::amdgcn_image_atomic_add:
701 case Intrinsic::amdgcn_image_atomic_sub:
702 case Intrinsic::amdgcn_image_atomic_smin:
703 case Intrinsic::amdgcn_image_atomic_umin:
704 case Intrinsic::amdgcn_image_atomic_smax:
705 case Intrinsic::amdgcn_image_atomic_umax:
706 case Intrinsic::amdgcn_image_atomic_and:
707 case Intrinsic::amdgcn_image_atomic_or:
708 case Intrinsic::amdgcn_image_atomic_xor:
709 case Intrinsic::amdgcn_image_atomic_inc:
710 case Intrinsic::amdgcn_image_atomic_dec: {
711 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
712 Info.opc = ISD::INTRINSIC_W_CHAIN;
713 Info.memVT = MVT::getVT(CI.getType());
714 Info.ptrVal = MFI->getImagePSV(
715 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
716 CI.getArgOperand(2));
718 Info.flags = MachineMemOperand::MOLoad |
719 MachineMemOperand::MOStore |
720 MachineMemOperand::MODereferenceable;
722 // XXX - Should this be volatile without known ordering?
723 Info.flags |= MachineMemOperand::MOVolatile;
726 case Intrinsic::amdgcn_image_atomic_cmpswap: {
727 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
728 Info.opc = ISD::INTRINSIC_W_CHAIN;
729 Info.memVT = MVT::getVT(CI.getType());
730 Info.ptrVal = MFI->getImagePSV(
731 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
732 CI.getArgOperand(3));
734 Info.flags = MachineMemOperand::MOLoad |
735 MachineMemOperand::MOStore |
736 MachineMemOperand::MODereferenceable;
738 // XXX - Should this be volatile without known ordering?
739 Info.flags |= MachineMemOperand::MOVolatile;
742 case Intrinsic::amdgcn_tbuffer_load:
743 case Intrinsic::amdgcn_buffer_load:
744 case Intrinsic::amdgcn_buffer_load_format: {
745 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
746 Info.opc = ISD::INTRINSIC_W_CHAIN;
747 Info.ptrVal = MFI->getBufferPSV(
748 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
749 CI.getArgOperand(0));
750 Info.memVT = MVT::getVT(CI.getType());
751 Info.flags = MachineMemOperand::MOLoad |
752 MachineMemOperand::MODereferenceable;
754 // There is a constant offset component, but there are additional register
755 // offsets which could break AA if we set the offset to anything non-0.
758 case Intrinsic::amdgcn_tbuffer_store:
759 case Intrinsic::amdgcn_buffer_store:
760 case Intrinsic::amdgcn_buffer_store_format: {
761 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
762 Info.opc = ISD::INTRINSIC_VOID;
763 Info.ptrVal = MFI->getBufferPSV(
764 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
765 CI.getArgOperand(1));
766 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
767 Info.flags = MachineMemOperand::MOStore |
768 MachineMemOperand::MODereferenceable;
771 case Intrinsic::amdgcn_buffer_atomic_swap:
772 case Intrinsic::amdgcn_buffer_atomic_add:
773 case Intrinsic::amdgcn_buffer_atomic_sub:
774 case Intrinsic::amdgcn_buffer_atomic_smin:
775 case Intrinsic::amdgcn_buffer_atomic_umin:
776 case Intrinsic::amdgcn_buffer_atomic_smax:
777 case Intrinsic::amdgcn_buffer_atomic_umax:
778 case Intrinsic::amdgcn_buffer_atomic_and:
779 case Intrinsic::amdgcn_buffer_atomic_or:
780 case Intrinsic::amdgcn_buffer_atomic_xor: {
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(1));
786 Info.memVT = MVT::getVT(CI.getType());
787 Info.flags = MachineMemOperand::MOLoad |
788 MachineMemOperand::MOStore |
789 MachineMemOperand::MODereferenceable |
790 MachineMemOperand::MOVolatile;
793 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
794 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
795 Info.opc = ISD::INTRINSIC_W_CHAIN;
796 Info.ptrVal = MFI->getBufferPSV(
797 *MF.getSubtarget<SISubtarget>().getInstrInfo(),
798 CI.getArgOperand(2));
799 Info.memVT = MVT::getVT(CI.getType());
800 Info.flags = MachineMemOperand::MOLoad |
801 MachineMemOperand::MOStore |
802 MachineMemOperand::MODereferenceable |
803 MachineMemOperand::MOVolatile;
811 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
812 SmallVectorImpl<Value*> &Ops,
813 Type *&AccessTy) const {
814 switch (II->getIntrinsicID()) {
815 case Intrinsic::amdgcn_atomic_inc:
816 case Intrinsic::amdgcn_atomic_dec:
817 case Intrinsic::amdgcn_ds_fadd:
818 case Intrinsic::amdgcn_ds_fmin:
819 case Intrinsic::amdgcn_ds_fmax: {
820 Value *Ptr = II->getArgOperand(0);
821 AccessTy = II->getType();
830 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
831 if (!Subtarget->hasFlatInstOffsets()) {
832 // Flat instructions do not have offsets, and only have the register
834 return AM.BaseOffs == 0 && AM.Scale == 0;
837 // GFX9 added a 13-bit signed offset. When using regular flat instructions,
838 // the sign bit is ignored and is treated as a 12-bit unsigned offset.
841 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
844 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
845 if (Subtarget->hasFlatGlobalInsts())
846 return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
848 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
849 // Assume the we will use FLAT for all global memory accesses
851 // FIXME: This assumption is currently wrong. On VI we still use
852 // MUBUF instructions for the r + i addressing mode. As currently
853 // implemented, the MUBUF instructions only work on buffer < 4GB.
854 // It may be possible to support > 4GB buffers with MUBUF instructions,
855 // by setting the stride value in the resource descriptor which would
856 // increase the size limit to (stride * 4GB). However, this is risky,
857 // because it has never been validated.
858 return isLegalFlatAddressingMode(AM);
861 return isLegalMUBUFAddressingMode(AM);
864 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
865 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
866 // additionally can do r + r + i with addr64. 32-bit has more addressing
867 // mode options. Depending on the resource constant, it can also do
868 // (i64 r0) + (i32 r1) * (i14 i).
870 // Private arrays end up using a scratch buffer most of the time, so also
871 // assume those use MUBUF instructions. Scratch loads / stores are currently
872 // implemented as mubuf instructions with offen bit set, so slightly
873 // different than the normal addr64.
874 if (!isUInt<12>(AM.BaseOffs))
877 // FIXME: Since we can split immediate into soffset and immediate offset,
878 // would it make sense to allow any immediate?
881 case 0: // r + i or just i, depending on HasBaseReg.
884 return true; // We have r + r or r + i.
891 // Allow 2 * r as r + r
892 // Or 2 * r + i is allowed as r + r + i.
894 default: // Don't allow n * r
899 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
900 const AddrMode &AM, Type *Ty,
901 unsigned AS, Instruction *I) const {
902 // No global is ever allowed as a base.
906 if (AS == AMDGPUASI.GLOBAL_ADDRESS)
907 return isLegalGlobalAddressingMode(AM);
909 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
910 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
911 // If the offset isn't a multiple of 4, it probably isn't going to be
912 // correctly aligned.
913 // FIXME: Can we get the real alignment here?
914 if (AM.BaseOffs % 4 != 0)
915 return isLegalMUBUFAddressingMode(AM);
917 // There are no SMRD extloads, so if we have to do a small type access we
918 // will use a MUBUF load.
919 // FIXME?: We also need to do this if unaligned, but we don't know the
921 if (DL.getTypeStoreSize(Ty) < 4)
922 return isLegalGlobalAddressingMode(AM);
924 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
925 // SMRD instructions have an 8-bit, dword offset on SI.
926 if (!isUInt<8>(AM.BaseOffs / 4))
928 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
929 // On CI+, this can also be a 32-bit literal constant offset. If it fits
930 // in 8-bits, it can use a smaller encoding.
931 if (!isUInt<32>(AM.BaseOffs / 4))
933 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
934 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
935 if (!isUInt<20>(AM.BaseOffs))
938 llvm_unreachable("unhandled generation");
940 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
943 if (AM.Scale == 1 && AM.HasBaseReg)
948 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
949 return isLegalMUBUFAddressingMode(AM);
950 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
951 AS == AMDGPUASI.REGION_ADDRESS) {
952 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
954 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
955 // an 8-bit dword offset but we don't know the alignment here.
956 if (!isUInt<16>(AM.BaseOffs))
959 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
962 if (AM.Scale == 1 && AM.HasBaseReg)
966 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
967 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
968 // For an unknown address space, this usually means that this is for some
969 // reason being used for pure arithmetic, and not based on some addressing
970 // computation. We don't have instructions that compute pointers with any
971 // addressing modes, so treat them as having no offset like flat
973 return isLegalFlatAddressingMode(AM);
975 llvm_unreachable("unhandled address space");
979 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
980 const SelectionDAG &DAG) const {
981 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
982 return (MemVT.getSizeInBits() <= 4 * 32);
983 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
984 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
985 return (MemVT.getSizeInBits() <= MaxPrivateBits);
986 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
987 return (MemVT.getSizeInBits() <= 2 * 32);
992 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
995 bool *IsFast) const {
999 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1000 // which isn't a simple VT.
1001 // Until MVT is extended to handle this, simply check for the size and
1002 // rely on the condition below: allow accesses if the size is a multiple of 4.
1003 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1004 VT.getStoreSize() > 16)) {
1008 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
1009 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
1010 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1011 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1012 // with adjacent offsets.
1013 bool AlignedBy4 = (Align % 4 == 0);
1015 *IsFast = AlignedBy4;
1020 // FIXME: We have to be conservative here and assume that flat operations
1021 // will access scratch. If we had access to the IR function, then we
1022 // could determine if any private memory was used in the function.
1023 if (!Subtarget->hasUnalignedScratchAccess() &&
1024 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
1025 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
1029 if (Subtarget->hasUnalignedBufferAccess()) {
1030 // If we have an uniform constant load, it still requires using a slow
1031 // buffer instruction if unaligned.
1033 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS ||
1034 AddrSpace == AMDGPUASI.CONSTANT_ADDRESS_32BIT) ?
1035 (Align % 4 == 0) : true;
1041 // Smaller than dword value must be aligned.
1042 if (VT.bitsLT(MVT::i32))
1045 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1046 // byte-address are ignored, thus forcing Dword alignment.
1047 // This applies to private, global, and constant memory.
1051 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1054 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
1055 unsigned SrcAlign, bool IsMemset,
1058 MachineFunction &MF) const {
1059 // FIXME: Should account for address space here.
1061 // The default fallback uses the private pointer size as a guess for a type to
1062 // use. Make sure we switch these to 64-bit accesses.
1064 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1067 if (Size >= 8 && DstAlign >= 4)
1074 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
1075 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
1076 AS == AMDGPUASI.FLAT_ADDRESS ||
1077 AS == AMDGPUASI.CONSTANT_ADDRESS ||
1078 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT;
1081 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1082 unsigned DestAS) const {
1083 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
1084 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
1087 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1088 const MemSDNode *MemNode = cast<MemSDNode>(N);
1089 const Value *Ptr = MemNode->getMemOperand()->getValue();
1090 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1091 return I && I->getMetadata("amdgpu.noclobber");
1094 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
1095 unsigned DestAS) const {
1096 // Flat -> private/local is a simple truncate.
1097 // Flat -> global is no-op
1098 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
1101 return isNoopAddrSpaceCast(SrcAS, DestAS);
1104 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1105 const MemSDNode *MemNode = cast<MemSDNode>(N);
1107 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1110 TargetLoweringBase::LegalizeTypeAction
1111 SITargetLowering::getPreferredVectorAction(EVT VT) const {
1112 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1113 return TypeSplitVector;
1115 return TargetLoweringBase::getPreferredVectorAction(VT);
1118 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1120 // FIXME: Could be smarter if called for vector constants.
1124 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1125 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1130 // These operations are done with 32-bit instructions anyway.
1135 // TODO: Extensions?
1142 // SimplifySetCC uses this function to determine whether or not it should
1143 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1144 if (VT == MVT::i1 && Op == ISD::SETCC)
1147 return TargetLowering::isTypeDesirableForOp(Op, VT);
1150 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1153 uint64_t Offset) const {
1154 const DataLayout &DL = DAG.getDataLayout();
1155 MachineFunction &MF = DAG.getMachineFunction();
1156 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1158 const ArgDescriptor *InputPtrReg;
1159 const TargetRegisterClass *RC;
1161 std::tie(InputPtrReg, RC)
1162 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1164 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1165 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
1166 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1167 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1169 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1170 DAG.getConstant(Offset, SL, PtrVT));
1173 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1174 const SDLoc &SL) const {
1175 auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
1176 uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
1177 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1180 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1181 const SDLoc &SL, SDValue Val,
1183 const ISD::InputArg *Arg) const {
1184 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1186 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1187 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1190 if (MemVT.isFloatingPoint())
1191 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1193 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1195 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1200 SDValue SITargetLowering::lowerKernargMemParameter(
1201 SelectionDAG &DAG, EVT VT, EVT MemVT,
1202 const SDLoc &SL, SDValue Chain,
1203 uint64_t Offset, bool Signed,
1204 const ISD::InputArg *Arg) const {
1205 const DataLayout &DL = DAG.getDataLayout();
1206 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1207 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
1208 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1210 unsigned Align = DL.getABITypeAlignment(Ty);
1212 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1213 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1214 MachineMemOperand::MODereferenceable |
1215 MachineMemOperand::MOInvariant);
1217 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1218 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1221 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1222 const SDLoc &SL, SDValue Chain,
1223 const ISD::InputArg &Arg) const {
1224 MachineFunction &MF = DAG.getMachineFunction();
1225 MachineFrameInfo &MFI = MF.getFrameInfo();
1227 if (Arg.Flags.isByVal()) {
1228 unsigned Size = Arg.Flags.getByValSize();
1229 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1230 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1233 unsigned ArgOffset = VA.getLocMemOffset();
1234 unsigned ArgSize = VA.getValVT().getStoreSize();
1236 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1238 // Create load nodes to retrieve arguments from the stack.
1239 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1242 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1243 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1244 MVT MemVT = VA.getValVT();
1246 switch (VA.getLocInfo()) {
1249 case CCValAssign::BCvt:
1250 MemVT = VA.getLocVT();
1252 case CCValAssign::SExt:
1253 ExtType = ISD::SEXTLOAD;
1255 case CCValAssign::ZExt:
1256 ExtType = ISD::ZEXTLOAD;
1258 case CCValAssign::AExt:
1259 ExtType = ISD::EXTLOAD;
1263 ArgValue = DAG.getExtLoad(
1264 ExtType, SL, VA.getLocVT(), Chain, FIN,
1265 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1270 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1271 const SIMachineFunctionInfo &MFI,
1273 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1274 const ArgDescriptor *Reg;
1275 const TargetRegisterClass *RC;
1277 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1278 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1281 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1282 CallingConv::ID CallConv,
1283 ArrayRef<ISD::InputArg> Ins,
1285 FunctionType *FType,
1286 SIMachineFunctionInfo *Info) {
1287 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1288 const ISD::InputArg &Arg = Ins[I];
1290 // First check if it's a PS input addr.
1291 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
1292 !Arg.Flags.isByVal() && PSInputNum <= 15) {
1294 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
1295 // We can safely skip PS inputs.
1301 Info->markPSInputAllocated(PSInputNum);
1303 Info->markPSInputEnabled(PSInputNum);
1308 // Second split vertices into their elements.
1309 if (Arg.VT.isVector()) {
1310 ISD::InputArg NewArg = Arg;
1311 NewArg.Flags.setSplit();
1312 NewArg.VT = Arg.VT.getVectorElementType();
1314 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1315 // three or five element vertex only needs three or five registers,
1316 // NOT four or eight.
1317 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1318 unsigned NumElements = ParamType->getVectorNumElements();
1320 for (unsigned J = 0; J != NumElements; ++J) {
1321 Splits.push_back(NewArg);
1322 NewArg.PartOffset += NewArg.VT.getStoreSize();
1325 Splits.push_back(Arg);
1330 // Allocate special inputs passed in VGPRs.
1331 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1332 MachineFunction &MF,
1333 const SIRegisterInfo &TRI,
1334 SIMachineFunctionInfo &Info) {
1335 if (Info.hasWorkItemIDX()) {
1336 unsigned Reg = AMDGPU::VGPR0;
1337 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1339 CCInfo.AllocateReg(Reg);
1340 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1343 if (Info.hasWorkItemIDY()) {
1344 unsigned Reg = AMDGPU::VGPR1;
1345 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1347 CCInfo.AllocateReg(Reg);
1348 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1351 if (Info.hasWorkItemIDZ()) {
1352 unsigned Reg = AMDGPU::VGPR2;
1353 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1355 CCInfo.AllocateReg(Reg);
1356 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1360 // Try to allocate a VGPR at the end of the argument list, or if no argument
1361 // VGPRs are left allocating a stack slot.
1362 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1363 ArrayRef<MCPhysReg> ArgVGPRs
1364 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1365 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1366 if (RegIdx == ArgVGPRs.size()) {
1367 // Spill to stack required.
1368 int64_t Offset = CCInfo.AllocateStack(4, 4);
1370 return ArgDescriptor::createStack(Offset);
1373 unsigned Reg = ArgVGPRs[RegIdx];
1374 Reg = CCInfo.AllocateReg(Reg);
1375 assert(Reg != AMDGPU::NoRegister);
1377 MachineFunction &MF = CCInfo.getMachineFunction();
1378 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1379 return ArgDescriptor::createRegister(Reg);
1382 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1383 const TargetRegisterClass *RC,
1384 unsigned NumArgRegs) {
1385 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1386 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1387 if (RegIdx == ArgSGPRs.size())
1388 report_fatal_error("ran out of SGPRs for arguments");
1390 unsigned Reg = ArgSGPRs[RegIdx];
1391 Reg = CCInfo.AllocateReg(Reg);
1392 assert(Reg != AMDGPU::NoRegister);
1394 MachineFunction &MF = CCInfo.getMachineFunction();
1395 MF.addLiveIn(Reg, RC);
1396 return ArgDescriptor::createRegister(Reg);
1399 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1400 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1403 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1404 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1407 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1408 MachineFunction &MF,
1409 const SIRegisterInfo &TRI,
1410 SIMachineFunctionInfo &Info) {
1411 if (Info.hasWorkItemIDX())
1412 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1414 if (Info.hasWorkItemIDY())
1415 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1417 if (Info.hasWorkItemIDZ())
1418 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1421 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1422 MachineFunction &MF,
1423 const SIRegisterInfo &TRI,
1424 SIMachineFunctionInfo &Info) {
1425 auto &ArgInfo = Info.getArgInfo();
1427 // TODO: Unify handling with private memory pointers.
1429 if (Info.hasDispatchPtr())
1430 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1432 if (Info.hasQueuePtr())
1433 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1435 if (Info.hasKernargSegmentPtr())
1436 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1438 if (Info.hasDispatchID())
1439 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1441 // flat_scratch_init is not applicable for non-kernel functions.
1443 if (Info.hasWorkGroupIDX())
1444 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1446 if (Info.hasWorkGroupIDY())
1447 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1449 if (Info.hasWorkGroupIDZ())
1450 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1452 if (Info.hasImplicitArgPtr())
1453 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1456 // Allocate special inputs passed in user SGPRs.
1457 static void allocateHSAUserSGPRs(CCState &CCInfo,
1458 MachineFunction &MF,
1459 const SIRegisterInfo &TRI,
1460 SIMachineFunctionInfo &Info) {
1461 if (Info.hasImplicitBufferPtr()) {
1462 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1463 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1464 CCInfo.AllocateReg(ImplicitBufferPtrReg);
1467 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1468 if (Info.hasPrivateSegmentBuffer()) {
1469 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1470 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1471 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1474 if (Info.hasDispatchPtr()) {
1475 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1476 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1477 CCInfo.AllocateReg(DispatchPtrReg);
1480 if (Info.hasQueuePtr()) {
1481 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1482 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1483 CCInfo.AllocateReg(QueuePtrReg);
1486 if (Info.hasKernargSegmentPtr()) {
1487 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1488 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1489 CCInfo.AllocateReg(InputPtrReg);
1492 if (Info.hasDispatchID()) {
1493 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1494 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1495 CCInfo.AllocateReg(DispatchIDReg);
1498 if (Info.hasFlatScratchInit()) {
1499 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1500 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1501 CCInfo.AllocateReg(FlatScratchInitReg);
1504 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1505 // these from the dispatch pointer.
1508 // Allocate special input registers that are initialized per-wave.
1509 static void allocateSystemSGPRs(CCState &CCInfo,
1510 MachineFunction &MF,
1511 SIMachineFunctionInfo &Info,
1512 CallingConv::ID CallConv,
1514 if (Info.hasWorkGroupIDX()) {
1515 unsigned Reg = Info.addWorkGroupIDX();
1516 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1517 CCInfo.AllocateReg(Reg);
1520 if (Info.hasWorkGroupIDY()) {
1521 unsigned Reg = Info.addWorkGroupIDY();
1522 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1523 CCInfo.AllocateReg(Reg);
1526 if (Info.hasWorkGroupIDZ()) {
1527 unsigned Reg = Info.addWorkGroupIDZ();
1528 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1529 CCInfo.AllocateReg(Reg);
1532 if (Info.hasWorkGroupInfo()) {
1533 unsigned Reg = Info.addWorkGroupInfo();
1534 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1535 CCInfo.AllocateReg(Reg);
1538 if (Info.hasPrivateSegmentWaveByteOffset()) {
1539 // Scratch wave offset passed in system SGPR.
1540 unsigned PrivateSegmentWaveByteOffsetReg;
1543 PrivateSegmentWaveByteOffsetReg =
1544 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1546 // This is true if the scratch wave byte offset doesn't have a fixed
1548 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1549 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1550 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1553 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1555 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1556 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1560 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1561 MachineFunction &MF,
1562 const SIRegisterInfo &TRI,
1563 SIMachineFunctionInfo &Info) {
1564 // Now that we've figured out where the scratch register inputs are, see if
1565 // should reserve the arguments and use them directly.
1566 MachineFrameInfo &MFI = MF.getFrameInfo();
1567 bool HasStackObjects = MFI.hasStackObjects();
1569 // Record that we know we have non-spill stack objects so we don't need to
1570 // check all stack objects later.
1571 if (HasStackObjects)
1572 Info.setHasNonSpillStackObjects(true);
1574 // Everything live out of a block is spilled with fast regalloc, so it's
1575 // almost certain that spilling will be required.
1576 if (TM.getOptLevel() == CodeGenOpt::None)
1577 HasStackObjects = true;
1579 // For now assume stack access is needed in any callee functions, so we need
1580 // the scratch registers to pass in.
1581 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1583 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1584 if (ST.isAmdCodeObjectV2(MF)) {
1585 if (RequiresStackAccess) {
1586 // If we have stack objects, we unquestionably need the private buffer
1587 // resource. For the Code Object V2 ABI, this will be the first 4 user
1588 // SGPR inputs. We can reserve those and use them directly.
1590 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1591 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1592 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1594 if (MFI.hasCalls()) {
1595 // If we have calls, we need to keep the frame register in a register
1596 // that won't be clobbered by a call, so ensure it is copied somewhere.
1598 // This is not a problem for the scratch wave offset, because the same
1599 // registers are reserved in all functions.
1601 // FIXME: Nothing is really ensuring this is a call preserved register,
1602 // it's just selected from the end so it happens to be.
1603 unsigned ReservedOffsetReg
1604 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1605 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1607 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1608 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1609 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1612 unsigned ReservedBufferReg
1613 = TRI.reservedPrivateSegmentBufferReg(MF);
1614 unsigned ReservedOffsetReg
1615 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1617 // We tentatively reserve the last registers (skipping the last two
1618 // which may contain VCC). After register allocation, we'll replace
1619 // these with the ones immediately after those which were really
1620 // allocated. In the prologue copies will be inserted from the argument
1621 // to these reserved registers.
1622 Info.setScratchRSrcReg(ReservedBufferReg);
1623 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1626 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1628 // Without HSA, relocations are used for the scratch pointer and the
1629 // buffer resource setup is always inserted in the prologue. Scratch wave
1630 // offset is still in an input SGPR.
1631 Info.setScratchRSrcReg(ReservedBufferReg);
1633 if (HasStackObjects && !MFI.hasCalls()) {
1634 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1635 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1636 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1638 unsigned ReservedOffsetReg
1639 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1640 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1645 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1646 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1647 return !Info->isEntryFunction();
1650 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1654 void SITargetLowering::insertCopiesSplitCSR(
1655 MachineBasicBlock *Entry,
1656 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1657 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1659 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1663 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1664 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1665 MachineBasicBlock::iterator MBBI = Entry->begin();
1666 for (const MCPhysReg *I = IStart; *I; ++I) {
1667 const TargetRegisterClass *RC = nullptr;
1668 if (AMDGPU::SReg_64RegClass.contains(*I))
1669 RC = &AMDGPU::SGPR_64RegClass;
1670 else if (AMDGPU::SReg_32RegClass.contains(*I))
1671 RC = &AMDGPU::SGPR_32RegClass;
1673 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1675 unsigned NewVR = MRI->createVirtualRegister(RC);
1676 // Create copy from CSR to a virtual register.
1677 Entry->addLiveIn(*I);
1678 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1681 // Insert the copy-back instructions right before the terminator.
1682 for (auto *Exit : Exits)
1683 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1684 TII->get(TargetOpcode::COPY), *I)
1689 SDValue SITargetLowering::LowerFormalArguments(
1690 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1691 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1692 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1693 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1695 MachineFunction &MF = DAG.getMachineFunction();
1696 FunctionType *FType = MF.getFunction().getFunctionType();
1697 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1698 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1700 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1701 const Function &Fn = MF.getFunction();
1702 DiagnosticInfoUnsupported NoGraphicsHSA(
1703 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1704 DAG.getContext()->diagnose(NoGraphicsHSA);
1705 return DAG.getEntryNode();
1708 // Create stack objects that are used for emitting debugger prologue if
1709 // "amdgpu-debugger-emit-prologue" attribute was specified.
1710 if (ST.debuggerEmitPrologue())
1711 createDebuggerPrologueStackObjects(MF);
1713 SmallVector<ISD::InputArg, 16> Splits;
1714 SmallVector<CCValAssign, 16> ArgLocs;
1715 BitVector Skipped(Ins.size());
1716 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1719 bool IsShader = AMDGPU::isShader(CallConv);
1720 bool IsKernel = AMDGPU::isKernel(CallConv);
1721 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1724 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1725 // this when allocating argument fixed offsets.
1726 CCInfo.AllocateStack(4, 4);
1730 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1732 // At least one interpolation mode must be enabled or else the GPU will
1735 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1736 // set PSInputAddr, the user wants to enable some bits after the compilation
1737 // based on run-time states. Since we can't know what the final PSInputEna
1738 // will look like, so we shouldn't do anything here and the user should take
1739 // responsibility for the correct programming.
1741 // Otherwise, the following restrictions apply:
1742 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1743 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1745 if (CallConv == CallingConv::AMDGPU_PS) {
1746 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1747 ((Info->getPSInputAddr() & 0xF) == 0 &&
1748 Info->isPSInputAllocated(11))) {
1749 CCInfo.AllocateReg(AMDGPU::VGPR0);
1750 CCInfo.AllocateReg(AMDGPU::VGPR1);
1751 Info->markPSInputAllocated(0);
1752 Info->markPSInputEnabled(0);
1754 if (Subtarget->isAmdPalOS()) {
1755 // For isAmdPalOS, the user does not enable some bits after compilation
1756 // based on run-time states; the register values being generated here are
1757 // the final ones set in hardware. Therefore we need to apply the
1758 // workaround to PSInputAddr and PSInputEnable together. (The case where
1759 // a bit is set in PSInputAddr but not PSInputEnable is where the
1760 // frontend set up an input arg for a particular interpolation mode, but
1761 // nothing uses that input arg. Really we should have an earlier pass
1762 // that removes such an arg.)
1763 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1764 if ((PsInputBits & 0x7F) == 0 ||
1765 ((PsInputBits & 0xF) == 0 &&
1766 (PsInputBits >> 11 & 1)))
1767 Info->markPSInputEnabled(
1768 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1772 assert(!Info->hasDispatchPtr() &&
1773 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1774 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1775 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1776 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1777 !Info->hasWorkItemIDZ());
1778 } else if (IsKernel) {
1779 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1781 Splits.append(Ins.begin(), Ins.end());
1785 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1786 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1790 analyzeFormalArgumentsCompute(CCInfo, Ins);
1792 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1793 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1796 SmallVector<SDValue, 16> Chains;
1798 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1799 const ISD::InputArg &Arg = Ins[i];
1801 InVals.push_back(DAG.getUNDEF(Arg.VT));
1805 CCValAssign &VA = ArgLocs[ArgIdx++];
1806 MVT VT = VA.getLocVT();
1808 if (IsEntryFunc && VA.isMemLoc()) {
1810 EVT MemVT = VA.getLocVT();
1812 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1813 VA.getLocMemOffset();
1814 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1816 // The first 36 bytes of the input buffer contains information about
1817 // thread group and global sizes.
1818 SDValue Arg = lowerKernargMemParameter(
1819 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1820 Chains.push_back(Arg.getValue(1));
1823 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1824 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1825 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1826 // On SI local pointers are just offsets into LDS, so they are always
1827 // less than 16-bits. On CI and newer they could potentially be
1828 // real pointers, so we can't guarantee their size.
1829 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1830 DAG.getValueType(MVT::i16));
1833 InVals.push_back(Arg);
1835 } else if (!IsEntryFunc && VA.isMemLoc()) {
1836 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1837 InVals.push_back(Val);
1838 if (!Arg.Flags.isByVal())
1839 Chains.push_back(Val.getValue(1));
1843 assert(VA.isRegLoc() && "Parameter must be in a register!");
1845 unsigned Reg = VA.getLocReg();
1846 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1847 EVT ValVT = VA.getValVT();
1849 Reg = MF.addLiveIn(Reg, RC);
1850 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1852 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1853 // The return object should be reasonably addressable.
1855 // FIXME: This helps when the return is a real sret. If it is a
1856 // automatically inserted sret (i.e. CanLowerReturn returns false), an
1857 // extra copy is inserted in SelectionDAGBuilder which obscures this.
1858 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1859 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1860 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1863 // If this is an 8 or 16-bit value, it is really passed promoted
1864 // to 32 bits. Insert an assert[sz]ext to capture this, then
1865 // truncate to the right size.
1866 switch (VA.getLocInfo()) {
1867 case CCValAssign::Full:
1869 case CCValAssign::BCvt:
1870 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1872 case CCValAssign::SExt:
1873 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1874 DAG.getValueType(ValVT));
1875 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1877 case CCValAssign::ZExt:
1878 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1879 DAG.getValueType(ValVT));
1880 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1882 case CCValAssign::AExt:
1883 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1886 llvm_unreachable("Unknown loc info!");
1889 if (IsShader && Arg.VT.isVector()) {
1890 // Build a vector from the registers
1891 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1892 unsigned NumElements = ParamType->getVectorNumElements();
1894 SmallVector<SDValue, 4> Regs;
1895 Regs.push_back(Val);
1896 for (unsigned j = 1; j != NumElements; ++j) {
1897 Reg = ArgLocs[ArgIdx++].getLocReg();
1898 Reg = MF.addLiveIn(Reg, RC);
1900 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1901 Regs.push_back(Copy);
1904 // Fill up the missing vector elements
1905 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1906 Regs.append(NumElements, DAG.getUNDEF(VT));
1908 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1912 InVals.push_back(Val);
1916 // Special inputs come after user arguments.
1917 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1920 // Start adding system SGPRs.
1922 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1924 CCInfo.AllocateReg(Info->getScratchRSrcReg());
1925 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1926 CCInfo.AllocateReg(Info->getFrameOffsetReg());
1927 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
1930 auto &ArgUsageInfo =
1931 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1932 ArgUsageInfo.setFuncArgInfo(MF.getFunction(), Info->getArgInfo());
1934 unsigned StackArgSize = CCInfo.getNextStackOffset();
1935 Info->setBytesInStackArgArea(StackArgSize);
1937 return Chains.empty() ? Chain :
1938 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1941 // TODO: If return values can't fit in registers, we should return as many as
1942 // possible in registers before passing on stack.
1943 bool SITargetLowering::CanLowerReturn(
1944 CallingConv::ID CallConv,
1945 MachineFunction &MF, bool IsVarArg,
1946 const SmallVectorImpl<ISD::OutputArg> &Outs,
1947 LLVMContext &Context) const {
1948 // Replacing returns with sret/stack usage doesn't make sense for shaders.
1949 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1950 // for shaders. Vector types should be explicitly handled by CC.
1951 if (AMDGPU::isEntryFunctionCC(CallConv))
1954 SmallVector<CCValAssign, 16> RVLocs;
1955 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1956 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1960 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1962 const SmallVectorImpl<ISD::OutputArg> &Outs,
1963 const SmallVectorImpl<SDValue> &OutVals,
1964 const SDLoc &DL, SelectionDAG &DAG) const {
1965 MachineFunction &MF = DAG.getMachineFunction();
1966 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1968 if (AMDGPU::isKernel(CallConv)) {
1969 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1973 bool IsShader = AMDGPU::isShader(CallConv);
1975 Info->setIfReturnsVoid(Outs.size() == 0);
1976 bool IsWaveEnd = Info->returnsVoid() && IsShader;
1978 SmallVector<ISD::OutputArg, 48> Splits;
1979 SmallVector<SDValue, 48> SplitVals;
1981 // Split vectors into their elements.
1982 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1983 const ISD::OutputArg &Out = Outs[i];
1985 if (IsShader && Out.VT.isVector()) {
1986 MVT VT = Out.VT.getVectorElementType();
1987 ISD::OutputArg NewOut = Out;
1988 NewOut.Flags.setSplit();
1991 // We want the original number of vector elements here, e.g.
1992 // three or five, not four or eight.
1993 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1995 for (unsigned j = 0; j != NumElements; ++j) {
1996 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1997 DAG.getConstant(j, DL, MVT::i32));
1998 SplitVals.push_back(Elem);
1999 Splits.push_back(NewOut);
2000 NewOut.PartOffset += NewOut.VT.getStoreSize();
2003 SplitVals.push_back(OutVals[i]);
2004 Splits.push_back(Out);
2008 // CCValAssign - represent the assignment of the return value to a location.
2009 SmallVector<CCValAssign, 48> RVLocs;
2011 // CCState - Info about the registers and stack slots.
2012 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2015 // Analyze outgoing return values.
2016 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
2019 SmallVector<SDValue, 48> RetOps;
2020 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2022 // Add return address for callable functions.
2023 if (!Info->isEntryFunction()) {
2024 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2025 SDValue ReturnAddrReg = CreateLiveInRegister(
2026 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2028 // FIXME: Should be able to use a vreg here, but need a way to prevent it
2029 // from being allcoated to a CSR.
2031 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2034 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2035 Flag = Chain.getValue(1);
2037 RetOps.push_back(PhysReturnAddrReg);
2040 // Copy the result values into the output registers.
2041 for (unsigned i = 0, realRVLocIdx = 0;
2043 ++i, ++realRVLocIdx) {
2044 CCValAssign &VA = RVLocs[i];
2045 assert(VA.isRegLoc() && "Can only return in registers!");
2046 // TODO: Partially return in registers if return values don't fit.
2048 SDValue Arg = SplitVals[realRVLocIdx];
2050 // Copied from other backends.
2051 switch (VA.getLocInfo()) {
2052 case CCValAssign::Full:
2054 case CCValAssign::BCvt:
2055 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2057 case CCValAssign::SExt:
2058 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2060 case CCValAssign::ZExt:
2061 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2063 case CCValAssign::AExt:
2064 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2067 llvm_unreachable("Unknown loc info!");
2070 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2071 Flag = Chain.getValue(1);
2072 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2075 // FIXME: Does sret work properly?
2076 if (!Info->isEntryFunction()) {
2077 const SIRegisterInfo *TRI
2078 = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo();
2079 const MCPhysReg *I =
2080 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2083 if (AMDGPU::SReg_64RegClass.contains(*I))
2084 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2085 else if (AMDGPU::SReg_32RegClass.contains(*I))
2086 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2088 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2093 // Update chain and glue.
2096 RetOps.push_back(Flag);
2098 unsigned Opc = AMDGPUISD::ENDPGM;
2100 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2101 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2104 SDValue SITargetLowering::LowerCallResult(
2105 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2106 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2107 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2108 SDValue ThisVal) const {
2109 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2111 // Assign locations to each value returned by this call.
2112 SmallVector<CCValAssign, 16> RVLocs;
2113 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2115 CCInfo.AnalyzeCallResult(Ins, RetCC);
2117 // Copy all of the result registers out of their specified physreg.
2118 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2119 CCValAssign VA = RVLocs[i];
2122 if (VA.isRegLoc()) {
2123 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2124 Chain = Val.getValue(1);
2125 InFlag = Val.getValue(2);
2126 } else if (VA.isMemLoc()) {
2127 report_fatal_error("TODO: return values in memory");
2129 llvm_unreachable("unknown argument location type");
2131 switch (VA.getLocInfo()) {
2132 case CCValAssign::Full:
2134 case CCValAssign::BCvt:
2135 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2137 case CCValAssign::ZExt:
2138 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2139 DAG.getValueType(VA.getValVT()));
2140 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2142 case CCValAssign::SExt:
2143 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2144 DAG.getValueType(VA.getValVT()));
2145 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2147 case CCValAssign::AExt:
2148 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2151 llvm_unreachable("Unknown loc info!");
2154 InVals.push_back(Val);
2160 // Add code to pass special inputs required depending on used features separate
2161 // from the explicit user arguments present in the IR.
2162 void SITargetLowering::passSpecialInputs(
2163 CallLoweringInfo &CLI,
2164 const SIMachineFunctionInfo &Info,
2165 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2166 SmallVectorImpl<SDValue> &MemOpChains,
2168 SDValue StackPtr) const {
2169 // If we don't have a call site, this was a call inserted by
2170 // legalization. These can never use special inputs.
2174 const Function *CalleeFunc = CLI.CS.getCalledFunction();
2177 SelectionDAG &DAG = CLI.DAG;
2178 const SDLoc &DL = CLI.DL;
2180 const SISubtarget *ST = getSubtarget();
2181 const SIRegisterInfo *TRI = ST->getRegisterInfo();
2183 auto &ArgUsageInfo =
2184 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2185 const AMDGPUFunctionArgInfo &CalleeArgInfo
2186 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2188 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2190 // TODO: Unify with private memory register handling. This is complicated by
2191 // the fact that at least in kernels, the input argument is not necessarily
2192 // in the same location as the input.
2193 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2194 AMDGPUFunctionArgInfo::DISPATCH_PTR,
2195 AMDGPUFunctionArgInfo::QUEUE_PTR,
2196 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2197 AMDGPUFunctionArgInfo::DISPATCH_ID,
2198 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2199 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2200 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2201 AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2202 AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2203 AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2204 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2207 for (auto InputID : InputRegs) {
2208 const ArgDescriptor *OutgoingArg;
2209 const TargetRegisterClass *ArgRC;
2211 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2215 const ArgDescriptor *IncomingArg;
2216 const TargetRegisterClass *IncomingArgRC;
2217 std::tie(IncomingArg, IncomingArgRC)
2218 = CallerArgInfo.getPreloadedValue(InputID);
2219 assert(IncomingArgRC == ArgRC);
2221 // All special arguments are ints for now.
2222 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2226 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2228 // The implicit arg ptr is special because it doesn't have a corresponding
2229 // input for kernels, and is computed from the kernarg segment pointer.
2230 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2231 InputReg = getImplicitArgPtr(DAG, DL);
2234 if (OutgoingArg->isRegister()) {
2235 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2237 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr,
2239 OutgoingArg->getStackOffset());
2240 MemOpChains.push_back(ArgStore);
2245 static bool canGuaranteeTCO(CallingConv::ID CC) {
2246 return CC == CallingConv::Fast;
2249 /// Return true if we might ever do TCO for calls with this calling convention.
2250 static bool mayTailCallThisCC(CallingConv::ID CC) {
2252 case CallingConv::C:
2255 return canGuaranteeTCO(CC);
2259 bool SITargetLowering::isEligibleForTailCallOptimization(
2260 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2261 const SmallVectorImpl<ISD::OutputArg> &Outs,
2262 const SmallVectorImpl<SDValue> &OutVals,
2263 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2264 if (!mayTailCallThisCC(CalleeCC))
2267 MachineFunction &MF = DAG.getMachineFunction();
2268 const Function &CallerF = MF.getFunction();
2269 CallingConv::ID CallerCC = CallerF.getCallingConv();
2270 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2271 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2273 // Kernels aren't callable, and don't have a live in return address so it
2274 // doesn't make sense to do a tail call with entry functions.
2275 if (!CallerPreserved)
2278 bool CCMatch = CallerCC == CalleeCC;
2280 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2281 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2286 // TODO: Can we handle var args?
2290 for (const Argument &Arg : CallerF.args()) {
2291 if (Arg.hasByValAttr())
2295 LLVMContext &Ctx = *DAG.getContext();
2297 // Check that the call results are passed in the same way.
2298 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2299 CCAssignFnForCall(CalleeCC, IsVarArg),
2300 CCAssignFnForCall(CallerCC, IsVarArg)))
2303 // The callee has to preserve all registers the caller needs to preserve.
2305 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2306 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2310 // Nothing more to check if the callee is taking no arguments.
2314 SmallVector<CCValAssign, 16> ArgLocs;
2315 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2317 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2319 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2320 // If the stack arguments for this call do not fit into our own save area then
2321 // the call cannot be made tail.
2322 // TODO: Is this really necessary?
2323 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2326 const MachineRegisterInfo &MRI = MF.getRegInfo();
2327 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2330 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2331 if (!CI->isTailCall())
2334 const Function *ParentFn = CI->getParent()->getParent();
2335 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2338 auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2339 return (Attr.getValueAsString() != "true");
2342 // The wave scratch offset register is used as the global base pointer.
2343 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2344 SmallVectorImpl<SDValue> &InVals) const {
2345 SelectionDAG &DAG = CLI.DAG;
2346 const SDLoc &DL = CLI.DL;
2347 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2348 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2349 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2350 SDValue Chain = CLI.Chain;
2351 SDValue Callee = CLI.Callee;
2352 bool &IsTailCall = CLI.IsTailCall;
2353 CallingConv::ID CallConv = CLI.CallConv;
2354 bool IsVarArg = CLI.IsVarArg;
2355 bool IsSibCall = false;
2356 bool IsThisReturn = false;
2357 MachineFunction &MF = DAG.getMachineFunction();
2360 return lowerUnhandledCall(CLI, InVals,
2361 "unsupported call to variadic function ");
2364 if (!CLI.CS.getCalledFunction()) {
2365 return lowerUnhandledCall(CLI, InVals,
2366 "unsupported indirect call to function ");
2369 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2370 return lowerUnhandledCall(CLI, InVals,
2371 "unsupported required tail call to function ");
2374 // The first 4 bytes are reserved for the callee's emergency stack slot.
2375 const unsigned CalleeUsableStackOffset = 4;
2378 IsTailCall = isEligibleForTailCallOptimization(
2379 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2380 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2381 report_fatal_error("failed to perform tail call elimination on a call "
2382 "site marked musttail");
2385 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2387 // A sibling call is one where we're under the usual C ABI and not planning
2388 // to change that but can still do a tail call:
2389 if (!TailCallOpt && IsTailCall)
2396 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) {
2397 // FIXME: Remove this hack for function pointer types after removing
2398 // support of old address space mapping. In the new address space
2399 // mapping the pointer in default address space is 64 bit, therefore
2400 // does not need this hack.
2401 if (Callee.getValueType() == MVT::i32) {
2402 const GlobalValue *GV = GA->getGlobal();
2403 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false,
2404 GA->getTargetFlags());
2407 assert(Callee.getValueType() == MVT::i64);
2409 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2411 // Analyze operands of the call, assigning locations to each operand.
2412 SmallVector<CCValAssign, 16> ArgLocs;
2413 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2414 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2415 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2417 // Get a count of how many bytes are to be pushed on the stack.
2418 unsigned NumBytes = CCInfo.getNextStackOffset();
2421 // Since we're not changing the ABI to make this a tail call, the memory
2422 // operands are already available in the caller's incoming argument space.
2426 // FPDiff is the byte offset of the call's argument area from the callee's.
2427 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2428 // by this amount for a tail call. In a sibling call it must be 0 because the
2429 // caller will deallocate the entire stack and the callee still expects its
2430 // arguments to begin at SP+0. Completely unused for non-tail calls.
2432 MachineFrameInfo &MFI = MF.getFrameInfo();
2433 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2435 SDValue CallerSavedFP;
2437 // Adjust the stack pointer for the new arguments...
2438 // These operations are automatically eliminated by the prolog/epilog pass
2440 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2442 unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2444 // In the HSA case, this should be an identity copy.
2445 SDValue ScratchRSrcReg
2446 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2447 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2449 // TODO: Don't hardcode these registers and get from the callee function.
2450 SDValue ScratchWaveOffsetReg
2451 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2452 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2454 if (!Info->isEntryFunction()) {
2455 // Avoid clobbering this function's FP value. In the current convention
2456 // callee will overwrite this, so do save/restore around the call site.
2457 CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2458 Info->getFrameOffsetReg(), MVT::i32);
2462 // Stack pointer relative accesses are done by changing the offset SGPR. This
2463 // is just the VGPR offset component.
2464 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32);
2466 SmallVector<SDValue, 8> MemOpChains;
2467 MVT PtrVT = MVT::i32;
2469 // Walk the register/memloc assignments, inserting copies/loads.
2470 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2471 ++i, ++realArgIdx) {
2472 CCValAssign &VA = ArgLocs[i];
2473 SDValue Arg = OutVals[realArgIdx];
2475 // Promote the value if needed.
2476 switch (VA.getLocInfo()) {
2477 case CCValAssign::Full:
2479 case CCValAssign::BCvt:
2480 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2482 case CCValAssign::ZExt:
2483 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2485 case CCValAssign::SExt:
2486 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2488 case CCValAssign::AExt:
2489 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2491 case CCValAssign::FPExt:
2492 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2495 llvm_unreachable("Unknown loc info!");
2498 if (VA.isRegLoc()) {
2499 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2501 assert(VA.isMemLoc());
2504 MachinePointerInfo DstInfo;
2506 unsigned LocMemOffset = VA.getLocMemOffset();
2507 int32_t Offset = LocMemOffset;
2509 SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset);
2512 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2513 unsigned OpSize = Flags.isByVal() ?
2514 Flags.getByValSize() : VA.getValVT().getStoreSize();
2516 Offset = Offset + FPDiff;
2517 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2519 DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT),
2521 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2523 // Make sure any stack arguments overlapping with where we're storing
2524 // are loaded before this eventual operation. Otherwise they'll be
2527 // FIXME: Why is this really necessary? This seems to just result in a
2528 // lot of code to copy the stack and write them back to the same
2529 // locations, which are supposed to be immutable?
2530 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2533 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2536 if (Outs[i].Flags.isByVal()) {
2538 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2539 SDValue Cpy = DAG.getMemcpy(
2540 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2541 /*isVol = */ false, /*AlwaysInline = */ true,
2542 /*isTailCall = */ false, DstInfo,
2543 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2544 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS))));
2546 MemOpChains.push_back(Cpy);
2548 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
2549 MemOpChains.push_back(Store);
2554 // Copy special input registers after user input arguments.
2555 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr);
2557 if (!MemOpChains.empty())
2558 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2560 // Build a sequence of copy-to-reg nodes chained together with token chain
2561 // and flag operands which copy the outgoing args into the appropriate regs.
2563 for (auto &RegToPass : RegsToPass) {
2564 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2565 RegToPass.second, InFlag);
2566 InFlag = Chain.getValue(1);
2570 SDValue PhysReturnAddrReg;
2572 // Since the return is being combined with the call, we need to pass on the
2575 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2576 SDValue ReturnAddrReg = CreateLiveInRegister(
2577 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2579 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2581 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2582 InFlag = Chain.getValue(1);
2585 // We don't usually want to end the call-sequence here because we would tidy
2586 // the frame up *after* the call, however in the ABI-changing tail-call case
2587 // we've carefully laid out the parameters so that when sp is reset they'll be
2588 // in the correct location.
2589 if (IsTailCall && !IsSibCall) {
2590 Chain = DAG.getCALLSEQ_END(Chain,
2591 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2592 DAG.getTargetConstant(0, DL, MVT::i32),
2594 InFlag = Chain.getValue(1);
2597 std::vector<SDValue> Ops;
2598 Ops.push_back(Chain);
2599 Ops.push_back(Callee);
2602 // Each tail call may have to adjust the stack by a different amount, so
2603 // this information must travel along with the operation for eventual
2604 // consumption by emitEpilogue.
2605 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2607 Ops.push_back(PhysReturnAddrReg);
2610 // Add argument registers to the end of the list so that they are known live
2612 for (auto &RegToPass : RegsToPass) {
2613 Ops.push_back(DAG.getRegister(RegToPass.first,
2614 RegToPass.second.getValueType()));
2617 // Add a register mask operand representing the call-preserved registers.
2619 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo();
2620 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2621 assert(Mask && "Missing call preserved mask for calling convention");
2622 Ops.push_back(DAG.getRegisterMask(Mask));
2624 if (InFlag.getNode())
2625 Ops.push_back(InFlag);
2627 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2629 // If we're doing a tall call, use a TC_RETURN here rather than an
2630 // actual call instruction.
2632 MFI.setHasTailCall();
2633 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2636 // Returns a chain and a flag for retval copy to use.
2637 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2638 Chain = Call.getValue(0);
2639 InFlag = Call.getValue(1);
2641 if (CallerSavedFP) {
2642 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2643 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2644 InFlag = Chain.getValue(1);
2647 uint64_t CalleePopBytes = NumBytes;
2648 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2649 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2652 InFlag = Chain.getValue(1);
2654 // Handle result values, copying them out of physregs into vregs that we
2656 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2657 InVals, IsThisReturn,
2658 IsThisReturn ? OutVals[0] : SDValue());
2661 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2662 SelectionDAG &DAG) const {
2663 unsigned Reg = StringSwitch<unsigned>(RegName)
2664 .Case("m0", AMDGPU::M0)
2665 .Case("exec", AMDGPU::EXEC)
2666 .Case("exec_lo", AMDGPU::EXEC_LO)
2667 .Case("exec_hi", AMDGPU::EXEC_HI)
2668 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2669 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2670 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2671 .Default(AMDGPU::NoRegister);
2673 if (Reg == AMDGPU::NoRegister) {
2674 report_fatal_error(Twine("invalid register name \""
2675 + StringRef(RegName) + "\"."));
2679 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
2680 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2681 report_fatal_error(Twine("invalid register \""
2682 + StringRef(RegName) + "\" for subtarget."));
2687 case AMDGPU::EXEC_LO:
2688 case AMDGPU::EXEC_HI:
2689 case AMDGPU::FLAT_SCR_LO:
2690 case AMDGPU::FLAT_SCR_HI:
2691 if (VT.getSizeInBits() == 32)
2695 case AMDGPU::FLAT_SCR:
2696 if (VT.getSizeInBits() == 64)
2700 llvm_unreachable("missing register type checking");
2703 report_fatal_error(Twine("invalid type for register \""
2704 + StringRef(RegName) + "\"."));
2707 // If kill is not the last instruction, split the block so kill is always a
2708 // proper terminator.
2709 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2710 MachineBasicBlock *BB) const {
2711 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2713 MachineBasicBlock::iterator SplitPoint(&MI);
2716 if (SplitPoint == BB->end()) {
2717 // Don't bother with a new block.
2718 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2722 MachineFunction *MF = BB->getParent();
2723 MachineBasicBlock *SplitBB
2724 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2726 MF->insert(++MachineFunction::iterator(BB), SplitBB);
2727 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2729 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2730 BB->addSuccessor(SplitBB);
2732 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2736 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2737 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2738 // will only do one iteration. In the worst case, this will loop 64 times.
2740 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2741 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2742 const SIInstrInfo *TII,
2743 MachineRegisterInfo &MRI,
2744 MachineBasicBlock &OrigBB,
2745 MachineBasicBlock &LoopBB,
2747 const MachineOperand &IdxReg,
2751 unsigned InitSaveExecReg,
2754 bool IsIndirectSrc) {
2755 MachineBasicBlock::iterator I = LoopBB.begin();
2757 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2758 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2759 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2760 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2762 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2768 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2769 .addReg(InitSaveExecReg)
2774 // Read the next variant <- also loop target.
2775 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2776 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2778 // Compare the just read M0 value to all possible Idx values.
2779 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2780 .addReg(CurrentIdxReg)
2781 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2783 // Update EXEC, save the original EXEC value to VCC.
2784 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2785 .addReg(CondReg, RegState::Kill);
2787 MRI.setSimpleHint(NewExec, CondReg);
2789 if (UseGPRIdxMode) {
2792 IdxReg = CurrentIdxReg;
2794 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2795 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2796 .addReg(CurrentIdxReg, RegState::Kill)
2799 unsigned IdxMode = IsIndirectSrc ?
2800 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2801 MachineInstr *SetOn =
2802 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2803 .addReg(IdxReg, RegState::Kill)
2805 SetOn->getOperand(3).setIsUndef();
2807 // Move index from VCC into M0
2809 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2810 .addReg(CurrentIdxReg, RegState::Kill);
2812 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2813 .addReg(CurrentIdxReg, RegState::Kill)
2818 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2819 MachineInstr *InsertPt =
2820 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2821 .addReg(AMDGPU::EXEC)
2824 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2827 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2828 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2831 return InsertPt->getIterator();
2834 // This has slightly sub-optimal regalloc when the source vector is killed by
2835 // the read. The register allocator does not understand that the kill is
2836 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2837 // subregister from it, using 1 more VGPR than necessary. This was saved when
2838 // this was expanded after register allocation.
2839 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2840 MachineBasicBlock &MBB,
2842 unsigned InitResultReg,
2846 bool IsIndirectSrc) {
2847 MachineFunction *MF = MBB.getParent();
2848 MachineRegisterInfo &MRI = MF->getRegInfo();
2849 const DebugLoc &DL = MI.getDebugLoc();
2850 MachineBasicBlock::iterator I(&MI);
2852 unsigned DstReg = MI.getOperand(0).getReg();
2853 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2854 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2856 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2858 // Save the EXEC mask
2859 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2860 .addReg(AMDGPU::EXEC);
2862 // To insert the loop we need to split the block. Move everything after this
2863 // point to a new block, and insert a new empty block between the two.
2864 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2865 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2866 MachineFunction::iterator MBBI(MBB);
2869 MF->insert(MBBI, LoopBB);
2870 MF->insert(MBBI, RemainderBB);
2872 LoopBB->addSuccessor(LoopBB);
2873 LoopBB->addSuccessor(RemainderBB);
2875 // Move the rest of the block into a new block.
2876 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2877 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2879 MBB.addSuccessor(LoopBB);
2881 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2883 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2884 InitResultReg, DstReg, PhiReg, TmpExec,
2885 Offset, UseGPRIdxMode, IsIndirectSrc);
2887 MachineBasicBlock::iterator First = RemainderBB->begin();
2888 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2894 // Returns subreg index, offset
2895 static std::pair<unsigned, int>
2896 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2897 const TargetRegisterClass *SuperRC,
2900 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2902 // Skip out of bounds offsets, or else we would end up using an undefined
2904 if (Offset >= NumElts || Offset < 0)
2905 return std::make_pair(AMDGPU::sub0, Offset);
2907 return std::make_pair(AMDGPU::sub0 + Offset, 0);
2910 // Return true if the index is an SGPR and was set.
2911 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
2912 MachineRegisterInfo &MRI,
2916 bool IsIndirectSrc) {
2917 MachineBasicBlock *MBB = MI.getParent();
2918 const DebugLoc &DL = MI.getDebugLoc();
2919 MachineBasicBlock::iterator I(&MI);
2921 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2922 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2924 assert(Idx->getReg() != AMDGPU::NoRegister);
2926 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2929 if (UseGPRIdxMode) {
2930 unsigned IdxMode = IsIndirectSrc ?
2931 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2933 MachineInstr *SetOn =
2934 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2938 SetOn->getOperand(3).setIsUndef();
2940 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2941 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
2944 MachineInstr *SetOn =
2945 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2946 .addReg(Tmp, RegState::Kill)
2949 SetOn->getOperand(3).setIsUndef();
2956 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2959 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2967 // Control flow needs to be inserted if indexing with a VGPR.
2968 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
2969 MachineBasicBlock &MBB,
2970 const SISubtarget &ST) {
2971 const SIInstrInfo *TII = ST.getInstrInfo();
2972 const SIRegisterInfo &TRI = TII->getRegisterInfo();
2973 MachineFunction *MF = MBB.getParent();
2974 MachineRegisterInfo &MRI = MF->getRegInfo();
2976 unsigned Dst = MI.getOperand(0).getReg();
2977 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
2978 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2980 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
2983 std::tie(SubReg, Offset)
2984 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
2986 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2988 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
2989 MachineBasicBlock::iterator I(&MI);
2990 const DebugLoc &DL = MI.getDebugLoc();
2992 if (UseGPRIdxMode) {
2993 // TODO: Look at the uses to avoid the copy. This may require rescheduling
2994 // to avoid interfering with other uses, so probably requires a new
2995 // optimization pass.
2996 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
2997 .addReg(SrcReg, RegState::Undef, SubReg)
2998 .addReg(SrcReg, RegState::Implicit)
2999 .addReg(AMDGPU::M0, RegState::Implicit);
3000 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3002 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3003 .addReg(SrcReg, RegState::Undef, SubReg)
3004 .addReg(SrcReg, RegState::Implicit);
3007 MI.eraseFromParent();
3012 const DebugLoc &DL = MI.getDebugLoc();
3013 MachineBasicBlock::iterator I(&MI);
3015 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3016 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3018 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3020 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3021 Offset, UseGPRIdxMode, true);
3022 MachineBasicBlock *LoopBB = InsPt->getParent();
3024 if (UseGPRIdxMode) {
3025 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3026 .addReg(SrcReg, RegState::Undef, SubReg)
3027 .addReg(SrcReg, RegState::Implicit)
3028 .addReg(AMDGPU::M0, RegState::Implicit);
3029 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3031 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3032 .addReg(SrcReg, RegState::Undef, SubReg)
3033 .addReg(SrcReg, RegState::Implicit);
3036 MI.eraseFromParent();
3041 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3042 const TargetRegisterClass *VecRC) {
3043 switch (TRI.getRegSizeInBits(*VecRC)) {
3045 return AMDGPU::V_MOVRELD_B32_V1;
3047 return AMDGPU::V_MOVRELD_B32_V2;
3048 case 128: // 16 bytes
3049 return AMDGPU::V_MOVRELD_B32_V4;
3050 case 256: // 32 bytes
3051 return AMDGPU::V_MOVRELD_B32_V8;
3052 case 512: // 64 bytes
3053 return AMDGPU::V_MOVRELD_B32_V16;
3055 llvm_unreachable("unsupported size for MOVRELD pseudos");
3059 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3060 MachineBasicBlock &MBB,
3061 const SISubtarget &ST) {
3062 const SIInstrInfo *TII = ST.getInstrInfo();
3063 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3064 MachineFunction *MF = MBB.getParent();
3065 MachineRegisterInfo &MRI = MF->getRegInfo();
3067 unsigned Dst = MI.getOperand(0).getReg();
3068 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3069 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3070 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3071 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3072 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3074 // This can be an immediate, but will be folded later.
3075 assert(Val->getReg());
3078 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3081 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3083 if (Idx->getReg() == AMDGPU::NoRegister) {
3084 MachineBasicBlock::iterator I(&MI);
3085 const DebugLoc &DL = MI.getDebugLoc();
3087 assert(Offset == 0);
3089 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3094 MI.eraseFromParent();
3098 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3099 MachineBasicBlock::iterator I(&MI);
3100 const DebugLoc &DL = MI.getDebugLoc();
3102 if (UseGPRIdxMode) {
3103 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3104 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3106 .addReg(Dst, RegState::ImplicitDefine)
3107 .addReg(SrcVec->getReg(), RegState::Implicit)
3108 .addReg(AMDGPU::M0, RegState::Implicit);
3110 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3112 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3114 BuildMI(MBB, I, DL, MovRelDesc)
3115 .addReg(Dst, RegState::Define)
3116 .addReg(SrcVec->getReg())
3118 .addImm(SubReg - AMDGPU::sub0);
3121 MI.eraseFromParent();
3126 MRI.clearKillFlags(Val->getReg());
3128 const DebugLoc &DL = MI.getDebugLoc();
3130 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3132 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3133 Offset, UseGPRIdxMode, false);
3134 MachineBasicBlock *LoopBB = InsPt->getParent();
3136 if (UseGPRIdxMode) {
3137 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3138 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3140 .addReg(Dst, RegState::ImplicitDefine)
3141 .addReg(PhiReg, RegState::Implicit)
3142 .addReg(AMDGPU::M0, RegState::Implicit);
3143 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3145 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3147 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3148 .addReg(Dst, RegState::Define)
3151 .addImm(SubReg - AMDGPU::sub0);
3154 MI.eraseFromParent();
3159 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3160 MachineInstr &MI, MachineBasicBlock *BB) const {
3162 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3163 MachineFunction *MF = BB->getParent();
3164 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3166 if (TII->isMIMG(MI)) {
3167 if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3168 report_fatal_error("missing mem operand from MIMG instruction");
3170 // Add a memoperand for mimg instructions so that they aren't assumed to
3171 // be ordered memory instuctions.
3176 switch (MI.getOpcode()) {
3177 case AMDGPU::S_ADD_U64_PSEUDO:
3178 case AMDGPU::S_SUB_U64_PSEUDO: {
3179 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3180 const DebugLoc &DL = MI.getDebugLoc();
3182 MachineOperand &Dest = MI.getOperand(0);
3183 MachineOperand &Src0 = MI.getOperand(1);
3184 MachineOperand &Src1 = MI.getOperand(2);
3186 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3187 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3189 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3190 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3191 &AMDGPU::SReg_32_XM0RegClass);
3192 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3193 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3194 &AMDGPU::SReg_32_XM0RegClass);
3196 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3197 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3198 &AMDGPU::SReg_32_XM0RegClass);
3199 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3200 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3201 &AMDGPU::SReg_32_XM0RegClass);
3203 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3205 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3206 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3207 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3210 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3213 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3215 .addImm(AMDGPU::sub0)
3217 .addImm(AMDGPU::sub1);
3218 MI.eraseFromParent();
3221 case AMDGPU::SI_INIT_M0: {
3222 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3223 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3224 .add(MI.getOperand(0));
3225 MI.eraseFromParent();
3228 case AMDGPU::SI_INIT_EXEC:
3229 // This should be before all vector instructions.
3230 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3232 .addImm(MI.getOperand(0).getImm());
3233 MI.eraseFromParent();
3236 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3237 // Extract the thread count from an SGPR input and set EXEC accordingly.
3238 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3240 // S_BFE_U32 count, input, {shift, 7}
3241 // S_BFM_B64 exec, count, 0
3242 // S_CMP_EQ_U32 count, 64
3243 // S_CMOV_B64 exec, -1
3244 MachineInstr *FirstMI = &*BB->begin();
3245 MachineRegisterInfo &MRI = MF->getRegInfo();
3246 unsigned InputReg = MI.getOperand(0).getReg();
3247 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3250 // Move the COPY of the input reg to the beginning, so that we can use it.
3251 for (auto I = BB->begin(); I != &MI; I++) {
3252 if (I->getOpcode() != TargetOpcode::COPY ||
3253 I->getOperand(0).getReg() != InputReg)
3257 FirstMI = &*++BB->begin();
3259 I->removeFromParent();
3260 BB->insert(FirstMI, &*I);
3268 // This should be before all vector instructions.
3269 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3271 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3272 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3276 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3277 .addReg(CountReg, RegState::Kill)
3279 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3282 MI.eraseFromParent();
3286 case AMDGPU::GET_GROUPSTATICSIZE: {
3287 DebugLoc DL = MI.getDebugLoc();
3288 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3289 .add(MI.getOperand(0))
3290 .addImm(MFI->getLDSSize());
3291 MI.eraseFromParent();
3294 case AMDGPU::SI_INDIRECT_SRC_V1:
3295 case AMDGPU::SI_INDIRECT_SRC_V2:
3296 case AMDGPU::SI_INDIRECT_SRC_V4:
3297 case AMDGPU::SI_INDIRECT_SRC_V8:
3298 case AMDGPU::SI_INDIRECT_SRC_V16:
3299 return emitIndirectSrc(MI, *BB, *getSubtarget());
3300 case AMDGPU::SI_INDIRECT_DST_V1:
3301 case AMDGPU::SI_INDIRECT_DST_V2:
3302 case AMDGPU::SI_INDIRECT_DST_V4:
3303 case AMDGPU::SI_INDIRECT_DST_V8:
3304 case AMDGPU::SI_INDIRECT_DST_V16:
3305 return emitIndirectDst(MI, *BB, *getSubtarget());
3306 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3307 case AMDGPU::SI_KILL_I1_PSEUDO:
3308 return splitKillBlock(MI, BB);
3309 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3310 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3312 unsigned Dst = MI.getOperand(0).getReg();
3313 unsigned Src0 = MI.getOperand(1).getReg();
3314 unsigned Src1 = MI.getOperand(2).getReg();
3315 const DebugLoc &DL = MI.getDebugLoc();
3316 unsigned SrcCond = MI.getOperand(3).getReg();
3318 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3319 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3320 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3322 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3324 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3325 .addReg(Src0, 0, AMDGPU::sub0)
3326 .addReg(Src1, 0, AMDGPU::sub0)
3327 .addReg(SrcCondCopy);
3328 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3329 .addReg(Src0, 0, AMDGPU::sub1)
3330 .addReg(Src1, 0, AMDGPU::sub1)
3331 .addReg(SrcCondCopy);
3333 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3335 .addImm(AMDGPU::sub0)
3337 .addImm(AMDGPU::sub1);
3338 MI.eraseFromParent();
3341 case AMDGPU::SI_BR_UNDEF: {
3342 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3343 const DebugLoc &DL = MI.getDebugLoc();
3344 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3345 .add(MI.getOperand(0));
3346 Br->getOperand(1).setIsUndef(true); // read undef SCC
3347 MI.eraseFromParent();
3350 case AMDGPU::ADJCALLSTACKUP:
3351 case AMDGPU::ADJCALLSTACKDOWN: {
3352 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3353 MachineInstrBuilder MIB(*MF, &MI);
3355 // Add an implicit use of the frame offset reg to prevent the restore copy
3356 // inserted after the call from being reorderd after stack operations in the
3357 // the caller's frame.
3358 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3359 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3360 .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3363 case AMDGPU::SI_CALL_ISEL:
3364 case AMDGPU::SI_TCRETURN_ISEL: {
3365 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3366 const DebugLoc &DL = MI.getDebugLoc();
3367 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3369 MachineRegisterInfo &MRI = MF->getRegInfo();
3370 unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3371 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3372 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3374 const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3376 MachineInstrBuilder MIB;
3377 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3378 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3379 .add(MI.getOperand(0))
3380 .addGlobalAddress(G);
3382 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3383 .add(MI.getOperand(0))
3384 .addGlobalAddress(G);
3386 // There is an additional imm operand for tcreturn, but it should be in the
3387 // right place already.
3390 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3391 MIB.add(MI.getOperand(I));
3393 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3394 MI.eraseFromParent();
3398 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3402 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3403 return isTypeLegal(VT.getScalarType());
3406 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3407 // This currently forces unfolding various combinations of fsub into fma with
3408 // free fneg'd operands. As long as we have fast FMA (controlled by
3409 // isFMAFasterThanFMulAndFAdd), we should perform these.
3411 // When fma is quarter rate, for f64 where add / sub are at best half rate,
3412 // most of these combines appear to be cycle neutral but save on instruction
3413 // count / code size.
3417 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3419 if (!VT.isVector()) {
3422 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3425 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3426 // TODO: Should i16 be used always if legal? For now it would force VALU
3428 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3431 // Answering this is somewhat tricky and depends on the specific device which
3432 // have different rates for fma or all f64 operations.
3434 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3435 // regardless of which device (although the number of cycles differs between
3436 // devices), so it is always profitable for f64.
3438 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3439 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3440 // which we can always do even without fused FP ops since it returns the same
3441 // result as the separate operations and since it is always full
3442 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3443 // however does not support denormals, so we do report fma as faster if we have
3444 // a fast fma device and require denormals.
3446 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3447 VT = VT.getScalarType();
3449 switch (VT.getSimpleVT().SimpleTy) {
3451 // This is as fast on some subtargets. However, we always have full rate f32
3452 // mad available which returns the same result as the separate operations
3453 // which we should prefer over fma. We can't use this if we want to support
3454 // denormals, so only report this in these cases.
3455 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
3459 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3467 //===----------------------------------------------------------------------===//
3468 // Custom DAG Lowering Operations
3469 //===----------------------------------------------------------------------===//
3471 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3472 switch (Op.getOpcode()) {
3473 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3474 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3476 SDValue Result = LowerLOAD(Op, DAG);
3477 assert((!Result.getNode() ||
3478 Result.getNode()->getNumValues() == 2) &&
3479 "Load should return a value and a chain");
3485 return LowerTrig(Op, DAG);
3486 case ISD::SELECT: return LowerSELECT(Op, DAG);
3487 case ISD::FDIV: return LowerFDIV(Op, DAG);
3488 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3489 case ISD::STORE: return LowerSTORE(Op, DAG);
3490 case ISD::GlobalAddress: {
3491 MachineFunction &MF = DAG.getMachineFunction();
3492 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3493 return LowerGlobalAddress(MFI, Op, DAG);
3495 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3496 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3497 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3498 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3499 case ISD::INSERT_VECTOR_ELT:
3500 return lowerINSERT_VECTOR_ELT(Op, DAG);
3501 case ISD::EXTRACT_VECTOR_ELT:
3502 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3504 return lowerFP_ROUND(Op, DAG);
3506 case ISD::DEBUGTRAP:
3507 return lowerTRAP(Op, DAG);
3512 static unsigned getImageOpcode(unsigned IID) {
3514 case Intrinsic::amdgcn_image_load:
3515 return AMDGPUISD::IMAGE_LOAD;
3516 case Intrinsic::amdgcn_image_load_mip:
3517 return AMDGPUISD::IMAGE_LOAD_MIP;
3520 case Intrinsic::amdgcn_image_sample:
3521 return AMDGPUISD::IMAGE_SAMPLE;
3522 case Intrinsic::amdgcn_image_sample_cl:
3523 return AMDGPUISD::IMAGE_SAMPLE_CL;
3524 case Intrinsic::amdgcn_image_sample_d:
3525 return AMDGPUISD::IMAGE_SAMPLE_D;
3526 case Intrinsic::amdgcn_image_sample_d_cl:
3527 return AMDGPUISD::IMAGE_SAMPLE_D_CL;
3528 case Intrinsic::amdgcn_image_sample_l:
3529 return AMDGPUISD::IMAGE_SAMPLE_L;
3530 case Intrinsic::amdgcn_image_sample_b:
3531 return AMDGPUISD::IMAGE_SAMPLE_B;
3532 case Intrinsic::amdgcn_image_sample_b_cl:
3533 return AMDGPUISD::IMAGE_SAMPLE_B_CL;
3534 case Intrinsic::amdgcn_image_sample_lz:
3535 return AMDGPUISD::IMAGE_SAMPLE_LZ;
3536 case Intrinsic::amdgcn_image_sample_cd:
3537 return AMDGPUISD::IMAGE_SAMPLE_CD;
3538 case Intrinsic::amdgcn_image_sample_cd_cl:
3539 return AMDGPUISD::IMAGE_SAMPLE_CD_CL;
3541 // Sample with comparison.
3542 case Intrinsic::amdgcn_image_sample_c:
3543 return AMDGPUISD::IMAGE_SAMPLE_C;
3544 case Intrinsic::amdgcn_image_sample_c_cl:
3545 return AMDGPUISD::IMAGE_SAMPLE_C_CL;
3546 case Intrinsic::amdgcn_image_sample_c_d:
3547 return AMDGPUISD::IMAGE_SAMPLE_C_D;
3548 case Intrinsic::amdgcn_image_sample_c_d_cl:
3549 return AMDGPUISD::IMAGE_SAMPLE_C_D_CL;
3550 case Intrinsic::amdgcn_image_sample_c_l:
3551 return AMDGPUISD::IMAGE_SAMPLE_C_L;
3552 case Intrinsic::amdgcn_image_sample_c_b:
3553 return AMDGPUISD::IMAGE_SAMPLE_C_B;
3554 case Intrinsic::amdgcn_image_sample_c_b_cl:
3555 return AMDGPUISD::IMAGE_SAMPLE_C_B_CL;
3556 case Intrinsic::amdgcn_image_sample_c_lz:
3557 return AMDGPUISD::IMAGE_SAMPLE_C_LZ;
3558 case Intrinsic::amdgcn_image_sample_c_cd:
3559 return AMDGPUISD::IMAGE_SAMPLE_C_CD;
3560 case Intrinsic::amdgcn_image_sample_c_cd_cl:
3561 return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL;
3563 // Sample with offsets.
3564 case Intrinsic::amdgcn_image_sample_o:
3565 return AMDGPUISD::IMAGE_SAMPLE_O;
3566 case Intrinsic::amdgcn_image_sample_cl_o:
3567 return AMDGPUISD::IMAGE_SAMPLE_CL_O;
3568 case Intrinsic::amdgcn_image_sample_d_o:
3569 return AMDGPUISD::IMAGE_SAMPLE_D_O;
3570 case Intrinsic::amdgcn_image_sample_d_cl_o:
3571 return AMDGPUISD::IMAGE_SAMPLE_D_CL_O;
3572 case Intrinsic::amdgcn_image_sample_l_o:
3573 return AMDGPUISD::IMAGE_SAMPLE_L_O;
3574 case Intrinsic::amdgcn_image_sample_b_o:
3575 return AMDGPUISD::IMAGE_SAMPLE_B_O;
3576 case Intrinsic::amdgcn_image_sample_b_cl_o:
3577 return AMDGPUISD::IMAGE_SAMPLE_B_CL_O;
3578 case Intrinsic::amdgcn_image_sample_lz_o:
3579 return AMDGPUISD::IMAGE_SAMPLE_LZ_O;
3580 case Intrinsic::amdgcn_image_sample_cd_o:
3581 return AMDGPUISD::IMAGE_SAMPLE_CD_O;
3582 case Intrinsic::amdgcn_image_sample_cd_cl_o:
3583 return AMDGPUISD::IMAGE_SAMPLE_CD_CL_O;
3585 // Sample with comparison and offsets.
3586 case Intrinsic::amdgcn_image_sample_c_o:
3587 return AMDGPUISD::IMAGE_SAMPLE_C_O;
3588 case Intrinsic::amdgcn_image_sample_c_cl_o:
3589 return AMDGPUISD::IMAGE_SAMPLE_C_CL_O;
3590 case Intrinsic::amdgcn_image_sample_c_d_o:
3591 return AMDGPUISD::IMAGE_SAMPLE_C_D_O;
3592 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3593 return AMDGPUISD::IMAGE_SAMPLE_C_D_CL_O;
3594 case Intrinsic::amdgcn_image_sample_c_l_o:
3595 return AMDGPUISD::IMAGE_SAMPLE_C_L_O;
3596 case Intrinsic::amdgcn_image_sample_c_b_o:
3597 return AMDGPUISD::IMAGE_SAMPLE_C_B_O;
3598 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3599 return AMDGPUISD::IMAGE_SAMPLE_C_B_CL_O;
3600 case Intrinsic::amdgcn_image_sample_c_lz_o:
3601 return AMDGPUISD::IMAGE_SAMPLE_C_LZ_O;
3602 case Intrinsic::amdgcn_image_sample_c_cd_o:
3603 return AMDGPUISD::IMAGE_SAMPLE_C_CD_O;
3604 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3605 return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL_O;
3608 case Intrinsic::amdgcn_image_gather4:
3609 return AMDGPUISD::IMAGE_GATHER4;
3610 case Intrinsic::amdgcn_image_gather4_cl:
3611 return AMDGPUISD::IMAGE_GATHER4_CL;
3612 case Intrinsic::amdgcn_image_gather4_l:
3613 return AMDGPUISD::IMAGE_GATHER4_L;
3614 case Intrinsic::amdgcn_image_gather4_b:
3615 return AMDGPUISD::IMAGE_GATHER4_B;
3616 case Intrinsic::amdgcn_image_gather4_b_cl:
3617 return AMDGPUISD::IMAGE_GATHER4_B_CL;
3618 case Intrinsic::amdgcn_image_gather4_lz:
3619 return AMDGPUISD::IMAGE_GATHER4_LZ;
3621 // Gather4 with comparison.
3622 case Intrinsic::amdgcn_image_gather4_c:
3623 return AMDGPUISD::IMAGE_GATHER4_C;
3624 case Intrinsic::amdgcn_image_gather4_c_cl:
3625 return AMDGPUISD::IMAGE_GATHER4_C_CL;
3626 case Intrinsic::amdgcn_image_gather4_c_l:
3627 return AMDGPUISD::IMAGE_GATHER4_C_L;
3628 case Intrinsic::amdgcn_image_gather4_c_b:
3629 return AMDGPUISD::IMAGE_GATHER4_C_B;
3630 case Intrinsic::amdgcn_image_gather4_c_b_cl:
3631 return AMDGPUISD::IMAGE_GATHER4_C_B_CL;
3632 case Intrinsic::amdgcn_image_gather4_c_lz:
3633 return AMDGPUISD::IMAGE_GATHER4_C_LZ;
3635 // Gather4 with offsets.
3636 case Intrinsic::amdgcn_image_gather4_o:
3637 return AMDGPUISD::IMAGE_GATHER4_O;
3638 case Intrinsic::amdgcn_image_gather4_cl_o:
3639 return AMDGPUISD::IMAGE_GATHER4_CL_O;
3640 case Intrinsic::amdgcn_image_gather4_l_o:
3641 return AMDGPUISD::IMAGE_GATHER4_L_O;
3642 case Intrinsic::amdgcn_image_gather4_b_o:
3643 return AMDGPUISD::IMAGE_GATHER4_B_O;
3644 case Intrinsic::amdgcn_image_gather4_b_cl_o:
3645 return AMDGPUISD::IMAGE_GATHER4_B_CL_O;
3646 case Intrinsic::amdgcn_image_gather4_lz_o:
3647 return AMDGPUISD::IMAGE_GATHER4_LZ_O;
3649 // Gather4 with comparison and offsets.
3650 case Intrinsic::amdgcn_image_gather4_c_o:
3651 return AMDGPUISD::IMAGE_GATHER4_C_O;
3652 case Intrinsic::amdgcn_image_gather4_c_cl_o:
3653 return AMDGPUISD::IMAGE_GATHER4_C_CL_O;
3654 case Intrinsic::amdgcn_image_gather4_c_l_o:
3655 return AMDGPUISD::IMAGE_GATHER4_C_L_O;
3656 case Intrinsic::amdgcn_image_gather4_c_b_o:
3657 return AMDGPUISD::IMAGE_GATHER4_C_B_O;
3658 case Intrinsic::amdgcn_image_gather4_c_b_cl_o:
3659 return AMDGPUISD::IMAGE_GATHER4_C_B_CL_O;
3660 case Intrinsic::amdgcn_image_gather4_c_lz_o:
3661 return AMDGPUISD::IMAGE_GATHER4_C_LZ_O;
3669 static SDValue adjustLoadValueType(SDValue Result, EVT LoadVT, SDLoc DL,
3670 SelectionDAG &DAG, bool Unpacked) {
3671 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3672 // Truncate to v2i16/v4i16.
3673 EVT IntLoadVT = LoadVT.changeTypeToInteger();
3674 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, IntLoadVT, Result);
3675 // Bitcast to original type (v2f16/v4f16).
3676 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Trunc);
3678 // Cast back to the original packed type.
3679 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3682 // This is to lower INTRINSIC_W_CHAIN with illegal result types.
3683 SDValue SITargetLowering::lowerIntrinsicWChain_IllegalReturnType(SDValue Op,
3684 SDValue &Chain, SelectionDAG &DAG) const {
3685 EVT LoadVT = Op.getValueType();
3686 // TODO: handle v3f16.
3687 if (LoadVT != MVT::v2f16 && LoadVT != MVT::v4f16)
3690 bool Unpacked = Subtarget->hasUnpackedD16VMem();
3691 EVT UnpackedLoadVT = (LoadVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32;
3692 EVT EquivLoadVT = Unpacked ? UnpackedLoadVT :
3693 getEquivalentMemType(*DAG.getContext(), LoadVT);
3694 // Change from v4f16/v2f16 to EquivLoadVT.
3695 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3699 MemSDNode *M = cast<MemSDNode>(Op);
3700 unsigned IID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3702 case Intrinsic::amdgcn_tbuffer_load: {
3704 Op.getOperand(0), // Chain
3705 Op.getOperand(2), // rsrc
3706 Op.getOperand(3), // vindex
3707 Op.getOperand(4), // voffset
3708 Op.getOperand(5), // soffset
3709 Op.getOperand(6), // offset
3710 Op.getOperand(7), // dfmt
3711 Op.getOperand(8), // nfmt
3712 Op.getOperand(9), // glc
3713 Op.getOperand(10) // slc
3715 Res = DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, DL,
3716 VTList, Ops, M->getMemoryVT(),
3717 M->getMemOperand());
3718 Chain = Res.getValue(1);
3719 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked);
3721 case Intrinsic::amdgcn_buffer_load_format: {
3723 Op.getOperand(0), // Chain
3724 Op.getOperand(2), // rsrc
3725 Op.getOperand(3), // vindex
3726 Op.getOperand(4), // offset
3727 Op.getOperand(5), // glc
3728 Op.getOperand(6) // slc
3730 Res = DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
3731 DL, VTList, Ops, M->getMemoryVT(),
3732 M->getMemOperand());
3733 Chain = Res.getValue(1);
3734 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked);
3736 case Intrinsic::amdgcn_image_load:
3737 case Intrinsic::amdgcn_image_load_mip: {
3739 Op.getOperand(0), // Chain
3740 Op.getOperand(2), // vaddr
3741 Op.getOperand(3), // rsrc
3742 Op.getOperand(4), // dmask
3743 Op.getOperand(5), // glc
3744 Op.getOperand(6), // slc
3745 Op.getOperand(7), // lwe
3746 Op.getOperand(8) // da
3748 unsigned Opc = getImageOpcode(IID);
3749 Res = DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, M->getMemoryVT(),
3750 M->getMemOperand());
3751 Chain = Res.getValue(1);
3752 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked);
3755 case Intrinsic::amdgcn_image_sample:
3756 case Intrinsic::amdgcn_image_sample_cl:
3757 case Intrinsic::amdgcn_image_sample_d:
3758 case Intrinsic::amdgcn_image_sample_d_cl:
3759 case Intrinsic::amdgcn_image_sample_l:
3760 case Intrinsic::amdgcn_image_sample_b:
3761 case Intrinsic::amdgcn_image_sample_b_cl:
3762 case Intrinsic::amdgcn_image_sample_lz:
3763 case Intrinsic::amdgcn_image_sample_cd:
3764 case Intrinsic::amdgcn_image_sample_cd_cl:
3766 // Sample with comparison.
3767 case Intrinsic::amdgcn_image_sample_c:
3768 case Intrinsic::amdgcn_image_sample_c_cl:
3769 case Intrinsic::amdgcn_image_sample_c_d:
3770 case Intrinsic::amdgcn_image_sample_c_d_cl:
3771 case Intrinsic::amdgcn_image_sample_c_l:
3772 case Intrinsic::amdgcn_image_sample_c_b:
3773 case Intrinsic::amdgcn_image_sample_c_b_cl:
3774 case Intrinsic::amdgcn_image_sample_c_lz:
3775 case Intrinsic::amdgcn_image_sample_c_cd:
3776 case Intrinsic::amdgcn_image_sample_c_cd_cl:
3778 // Sample with offsets.
3779 case Intrinsic::amdgcn_image_sample_o:
3780 case Intrinsic::amdgcn_image_sample_cl_o:
3781 case Intrinsic::amdgcn_image_sample_d_o:
3782 case Intrinsic::amdgcn_image_sample_d_cl_o:
3783 case Intrinsic::amdgcn_image_sample_l_o:
3784 case Intrinsic::amdgcn_image_sample_b_o:
3785 case Intrinsic::amdgcn_image_sample_b_cl_o:
3786 case Intrinsic::amdgcn_image_sample_lz_o:
3787 case Intrinsic::amdgcn_image_sample_cd_o:
3788 case Intrinsic::amdgcn_image_sample_cd_cl_o:
3790 // Sample with comparison and offsets.
3791 case Intrinsic::amdgcn_image_sample_c_o:
3792 case Intrinsic::amdgcn_image_sample_c_cl_o:
3793 case Intrinsic::amdgcn_image_sample_c_d_o:
3794 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3795 case Intrinsic::amdgcn_image_sample_c_l_o:
3796 case Intrinsic::amdgcn_image_sample_c_b_o:
3797 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3798 case Intrinsic::amdgcn_image_sample_c_lz_o:
3799 case Intrinsic::amdgcn_image_sample_c_cd_o:
3800 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3803 case Intrinsic::amdgcn_image_gather4:
3804 case Intrinsic::amdgcn_image_gather4_cl:
3805 case Intrinsic::amdgcn_image_gather4_l:
3806 case Intrinsic::amdgcn_image_gather4_b:
3807 case Intrinsic::amdgcn_image_gather4_b_cl:
3808 case Intrinsic::amdgcn_image_gather4_lz:
3810 // Gather4 with comparison
3811 case Intrinsic::amdgcn_image_gather4_c:
3812 case Intrinsic::amdgcn_image_gather4_c_cl:
3813 case Intrinsic::amdgcn_image_gather4_c_l:
3814 case Intrinsic::amdgcn_image_gather4_c_b:
3815 case Intrinsic::amdgcn_image_gather4_c_b_cl:
3816 case Intrinsic::amdgcn_image_gather4_c_lz:
3818 // Gather4 with offsets
3819 case Intrinsic::amdgcn_image_gather4_o:
3820 case Intrinsic::amdgcn_image_gather4_cl_o:
3821 case Intrinsic::amdgcn_image_gather4_l_o:
3822 case Intrinsic::amdgcn_image_gather4_b_o:
3823 case Intrinsic::amdgcn_image_gather4_b_cl_o:
3824 case Intrinsic::amdgcn_image_gather4_lz_o:
3826 // Gather4 with comparison and offsets
3827 case Intrinsic::amdgcn_image_gather4_c_o:
3828 case Intrinsic::amdgcn_image_gather4_c_cl_o:
3829 case Intrinsic::amdgcn_image_gather4_c_l_o:
3830 case Intrinsic::amdgcn_image_gather4_c_b_o:
3831 case Intrinsic::amdgcn_image_gather4_c_b_cl_o:
3832 case Intrinsic::amdgcn_image_gather4_c_lz_o: {
3834 Op.getOperand(0), // Chain
3835 Op.getOperand(2), // vaddr
3836 Op.getOperand(3), // rsrc
3837 Op.getOperand(4), // sampler
3838 Op.getOperand(5), // dmask
3839 Op.getOperand(6), // unorm
3840 Op.getOperand(7), // glc
3841 Op.getOperand(8), // slc
3842 Op.getOperand(9), // lwe
3843 Op.getOperand(10) // da
3845 unsigned Opc = getImageOpcode(IID);
3846 Res = DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, M->getMemoryVT(),
3847 M->getMemOperand());
3848 Chain = Res.getValue(1);
3849 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked);
3856 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3857 SmallVectorImpl<SDValue> &Results,
3858 SelectionDAG &DAG) const {
3859 switch (N->getOpcode()) {
3860 case ISD::INSERT_VECTOR_ELT: {
3861 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3862 Results.push_back(Res);
3865 case ISD::EXTRACT_VECTOR_ELT: {
3866 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3867 Results.push_back(Res);
3870 case ISD::INTRINSIC_WO_CHAIN: {
3871 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3873 case Intrinsic::amdgcn_cvt_pkrtz: {
3874 SDValue Src0 = N->getOperand(1);
3875 SDValue Src1 = N->getOperand(2);
3877 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3879 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3882 case Intrinsic::amdgcn_cvt_pknorm_i16:
3883 case Intrinsic::amdgcn_cvt_pknorm_u16:
3884 case Intrinsic::amdgcn_cvt_pk_i16:
3885 case Intrinsic::amdgcn_cvt_pk_u16: {
3886 SDValue Src0 = N->getOperand(1);
3887 SDValue Src1 = N->getOperand(2);
3891 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3892 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
3893 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3894 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
3895 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3896 Opcode = AMDGPUISD::CVT_PK_I16_I32;
3898 Opcode = AMDGPUISD::CVT_PK_U16_U32;
3900 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
3901 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
3907 case ISD::INTRINSIC_W_CHAIN: {
3909 if (SDValue Res = lowerIntrinsicWChain_IllegalReturnType(SDValue(N, 0),
3911 Results.push_back(Res);
3912 Results.push_back(Chain);
3919 EVT VT = N->getValueType(0);
3920 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3921 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3922 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3924 EVT SelectVT = NewVT;
3925 if (NewVT.bitsLT(MVT::i32)) {
3926 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3927 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3928 SelectVT = MVT::i32;
3931 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3932 N->getOperand(0), LHS, RHS);
3934 if (NewVT != SelectVT)
3935 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3936 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3944 /// \brief Helper function for LowerBRCOND
3945 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3947 SDNode *Parent = Value.getNode();
3948 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3951 if (I.getUse().get() != Value)
3954 if (I->getOpcode() == Opcode)
3960 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3961 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3962 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3963 case Intrinsic::amdgcn_if:
3964 return AMDGPUISD::IF;
3965 case Intrinsic::amdgcn_else:
3966 return AMDGPUISD::ELSE;
3967 case Intrinsic::amdgcn_loop:
3968 return AMDGPUISD::LOOP;
3969 case Intrinsic::amdgcn_end_cf:
3970 llvm_unreachable("should not occur");
3976 // break, if_break, else_break are all only used as inputs to loop, not
3977 // directly as branch conditions.
3981 void SITargetLowering::createDebuggerPrologueStackObjects(
3982 MachineFunction &MF) const {
3983 // Create stack objects that are used for emitting debugger prologue.
3985 // Debugger prologue writes work group IDs and work item IDs to scratch memory
3986 // at fixed location in the following format:
3987 // offset 0: work group ID x
3988 // offset 4: work group ID y
3989 // offset 8: work group ID z
3990 // offset 16: work item ID x
3991 // offset 20: work item ID y
3992 // offset 24: work item ID z
3993 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3996 // For each dimension:
3997 for (unsigned i = 0; i < 3; ++i) {
3998 // Create fixed stack object for work group ID.
3999 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
4000 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
4001 // Create fixed stack object for work item ID.
4002 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
4003 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
4007 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4008 const Triple &TT = getTargetMachine().getTargetTriple();
4009 return (GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4010 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4011 AMDGPU::shouldEmitConstantsToTextSection(TT);
4014 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4015 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
4016 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4017 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4018 !shouldEmitFixup(GV) &&
4019 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4022 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4023 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4026 /// This transforms the control flow intrinsics to get the branch destination as
4027 /// last parameter, also switches branch target with BR if the need arise
4028 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4029 SelectionDAG &DAG) const {
4032 SDNode *Intr = BRCOND.getOperand(1).getNode();
4033 SDValue Target = BRCOND.getOperand(2);
4034 SDNode *BR = nullptr;
4035 SDNode *SetCC = nullptr;
4037 if (Intr->getOpcode() == ISD::SETCC) {
4038 // As long as we negate the condition everything is fine
4040 Intr = SetCC->getOperand(0).getNode();
4043 // Get the target from BR if we don't negate the condition
4044 BR = findUser(BRCOND, ISD::BR);
4045 Target = BR->getOperand(1);
4048 // FIXME: This changes the types of the intrinsics instead of introducing new
4049 // nodes with the correct types.
4050 // e.g. llvm.amdgcn.loop
4052 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4053 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4055 unsigned CFNode = isCFIntrinsic(Intr);
4057 // This is a uniform branch so we don't need to legalize.
4061 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4062 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4065 (SetCC->getConstantOperandVal(1) == 1 &&
4066 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4069 // operands of the new intrinsic call
4070 SmallVector<SDValue, 4> Ops;
4072 Ops.push_back(BRCOND.getOperand(0));
4074 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
4075 Ops.push_back(Target);
4077 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4079 // build the new intrinsic call
4080 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4085 BRCOND.getOperand(0)
4088 Result = DAG.getMergeValues(Ops, DL).getNode();
4092 // Give the branch instruction our target
4095 BRCOND.getOperand(2)
4097 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4098 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4099 BR = NewBR.getNode();
4102 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4104 // Copy the intrinsic results to registers
4105 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4106 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4110 Chain = DAG.getCopyToReg(
4112 CopyToReg->getOperand(1),
4113 SDValue(Result, i - 1),
4116 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4119 // Remove the old intrinsic from the chain
4120 DAG.ReplaceAllUsesOfValueWith(
4121 SDValue(Intr, Intr->getNumValues() - 1),
4122 Intr->getOperand(0));
4127 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4131 return Op.getValueType().bitsLE(VT) ?
4132 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4133 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4136 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4137 assert(Op.getValueType() == MVT::f16 &&
4138 "Do not know how to custom lower FP_ROUND for non-f16 type");
4140 SDValue Src = Op.getOperand(0);
4141 EVT SrcVT = Src.getValueType();
4142 if (SrcVT != MVT::f64)
4147 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4148 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4149 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4152 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4154 MachineFunction &MF = DAG.getMachineFunction();
4155 SDValue Chain = Op.getOperand(0);
4157 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ?
4158 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap;
4160 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
4161 Subtarget->isTrapHandlerEnabled()) {
4162 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4163 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4164 assert(UserSGPR != AMDGPU::NoRegister);
4166 SDValue QueuePtr = CreateLiveInRegister(
4167 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4169 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4171 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4172 QueuePtr, SDValue());
4176 DAG.getTargetConstant(TrapID, SL, MVT::i16),
4181 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4185 case SISubtarget::TrapIDLLVMTrap:
4186 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4187 case SISubtarget::TrapIDLLVMDebugTrap: {
4188 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4189 "debugtrap handler not supported",
4192 LLVMContext &Ctx = MF.getFunction().getContext();
4193 Ctx.diagnose(NoTrap);
4197 llvm_unreachable("unsupported trap handler type!");
4203 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4204 SelectionDAG &DAG) const {
4205 // FIXME: Use inline constants (src_{shared, private}_base) instead.
4206 if (Subtarget->hasApertureRegs()) {
4207 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
4208 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4209 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4210 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
4211 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4212 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4214 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4215 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4216 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4218 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4219 SDValue ApertureReg = SDValue(
4220 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4221 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4222 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4225 MachineFunction &MF = DAG.getMachineFunction();
4226 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4227 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4228 assert(UserSGPR != AMDGPU::NoRegister);
4230 SDValue QueuePtr = CreateLiveInRegister(
4231 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4233 // Offset into amd_queue_t for group_segment_aperture_base_hi /
4234 // private_segment_aperture_base_hi.
4235 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
4237 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4239 // TODO: Use custom target PseudoSourceValue.
4240 // TODO: We should use the value from the IR intrinsic call, but it might not
4241 // be available and how do we get it?
4242 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4243 AMDGPUASI.CONSTANT_ADDRESS));
4245 MachinePointerInfo PtrInfo(V, StructOffset);
4246 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4247 MinAlign(64, StructOffset),
4248 MachineMemOperand::MODereferenceable |
4249 MachineMemOperand::MOInvariant);
4252 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4253 SelectionDAG &DAG) const {
4255 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4257 SDValue Src = ASC->getOperand(0);
4258 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4260 const AMDGPUTargetMachine &TM =
4261 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4263 // flat -> local/private
4264 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4265 unsigned DestAS = ASC->getDestAddressSpace();
4267 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
4268 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
4269 unsigned NullVal = TM.getNullPointerValue(DestAS);
4270 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4271 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4272 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4274 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4275 NonNull, Ptr, SegmentNullPtr);
4279 // local/private -> flat
4280 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4281 unsigned SrcAS = ASC->getSrcAddressSpace();
4283 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
4284 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
4285 unsigned NullVal = TM.getNullPointerValue(SrcAS);
4286 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4289 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4291 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4293 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4295 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4296 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4301 // global <-> flat are no-ops and never emitted.
4303 const MachineFunction &MF = DAG.getMachineFunction();
4304 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4305 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4306 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4308 return DAG.getUNDEF(ASC->getValueType(0));
4311 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4312 SelectionDAG &DAG) const {
4313 SDValue Idx = Op.getOperand(2);
4314 if (isa<ConstantSDNode>(Idx))
4317 // Avoid stack access for dynamic indexing.
4319 SDValue Vec = Op.getOperand(0);
4320 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
4322 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4323 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
4325 // Convert vector index to bit-index.
4326 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
4327 DAG.getConstant(16, SL, MVT::i32));
4329 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
4331 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
4332 DAG.getConstant(0xffff, SL, MVT::i32),
4335 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
4336 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
4337 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
4339 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
4340 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
4343 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4344 SelectionDAG &DAG) const {
4347 EVT ResultVT = Op.getValueType();
4348 SDValue Vec = Op.getOperand(0);
4349 SDValue Idx = Op.getOperand(1);
4351 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4353 // Make sure we we do any optimizations that will make it easier to fold
4354 // source modifiers before obscuring it with bit operations.
4356 // XXX - Why doesn't this get called when vector_shuffle is expanded?
4357 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4360 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
4361 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
4363 if (CIdx->getZExtValue() == 1) {
4364 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
4365 DAG.getConstant(16, SL, MVT::i32));
4367 assert(CIdx->getZExtValue() == 0);
4370 if (ResultVT.bitsLT(MVT::i32))
4371 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
4372 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4375 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
4377 // Convert vector index to bit-index.
4378 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
4380 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
4381 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
4383 SDValue Result = Elt;
4384 if (ResultVT.bitsLT(MVT::i32))
4385 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
4387 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4391 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4392 // We can fold offsets for anything that doesn't require a GOT relocation.
4393 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
4394 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4395 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4396 !shouldEmitGOTReloc(GA->getGlobal());
4400 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4401 const SDLoc &DL, unsigned Offset, EVT PtrVT,
4402 unsigned GAFlags = SIInstrInfo::MO_NONE) {
4403 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4404 // lowered to the following code sequence:
4406 // For constant address space:
4407 // s_getpc_b64 s[0:1]
4408 // s_add_u32 s0, s0, $symbol
4409 // s_addc_u32 s1, s1, 0
4411 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4412 // a fixup or relocation is emitted to replace $symbol with a literal
4413 // constant, which is a pc-relative offset from the encoding of the $symbol
4414 // operand to the global variable.
4416 // For global address space:
4417 // s_getpc_b64 s[0:1]
4418 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4419 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4421 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4422 // fixups or relocations are emitted to replace $symbol@*@lo and
4423 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4424 // which is a 64-bit pc-relative offset from the encoding of the $symbol
4425 // operand to the global variable.
4427 // What we want here is an offset from the value returned by s_getpc
4428 // (which is the address of the s_add_u32 instruction) to the global
4429 // variable, but since the encoding of $symbol starts 4 bytes after the start
4430 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4431 // small. This requires us to add 4 to the global variable offset in order to
4432 // compute the correct address.
4433 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4435 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4436 GAFlags == SIInstrInfo::MO_NONE ?
4437 GAFlags : GAFlags + 1);
4438 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4441 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4443 SelectionDAG &DAG) const {
4444 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4445 const GlobalValue *GV = GSD->getGlobal();
4447 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
4448 GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
4449 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS &&
4450 // FIXME: It isn't correct to rely on the type of the pointer. This should
4451 // be removed when address space 0 is 64-bit.
4452 !GV->getType()->getElementType()->isFunctionTy())
4453 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4456 EVT PtrVT = Op.getValueType();
4458 if (shouldEmitFixup(GV))
4459 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4460 else if (shouldEmitPCReloc(GV))
4461 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4462 SIInstrInfo::MO_REL32);
4464 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4465 SIInstrInfo::MO_GOTPCREL32);
4467 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4468 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
4469 const DataLayout &DataLayout = DAG.getDataLayout();
4470 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4471 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
4472 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
4474 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4475 MachineMemOperand::MODereferenceable |
4476 MachineMemOperand::MOInvariant);
4479 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4480 const SDLoc &DL, SDValue V) const {
4481 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4482 // the destination register.
4484 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4485 // so we will end up with redundant moves to m0.
4487 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4489 // A Null SDValue creates a glue result.
4490 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4492 return SDValue(M0, 0);
4495 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4498 unsigned Offset) const {
4500 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4501 DAG.getEntryNode(), Offset, false);
4502 // The local size values will have the hi 16-bits as zero.
4503 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4504 DAG.getValueType(VT));
4507 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4509 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4510 "non-hsa intrinsic with hsa target",
4512 DAG.getContext()->diagnose(BadIntrin);
4513 return DAG.getUNDEF(VT);
4516 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4518 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4519 "intrinsic not supported on subtarget",
4521 DAG.getContext()->diagnose(BadIntrin);
4522 return DAG.getUNDEF(VT);
4525 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4526 SelectionDAG &DAG) const {
4527 MachineFunction &MF = DAG.getMachineFunction();
4528 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
4530 EVT VT = Op.getValueType();
4532 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4534 // TODO: Should this propagate fast-math-flags?
4536 switch (IntrinsicID) {
4537 case Intrinsic::amdgcn_implicit_buffer_ptr: {
4538 if (getSubtarget()->isAmdCodeObjectV2(MF))
4539 return emitNonHSAIntrinsicError(DAG, DL, VT);
4540 return getPreloadedValue(DAG, *MFI, VT,
4541 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
4543 case Intrinsic::amdgcn_dispatch_ptr:
4544 case Intrinsic::amdgcn_queue_ptr: {
4545 if (!Subtarget->isAmdCodeObjectV2(MF)) {
4546 DiagnosticInfoUnsupported BadIntrin(
4547 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
4549 DAG.getContext()->diagnose(BadIntrin);
4550 return DAG.getUNDEF(VT);
4553 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
4554 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
4555 return getPreloadedValue(DAG, *MFI, VT, RegID);
4557 case Intrinsic::amdgcn_implicitarg_ptr: {
4558 if (MFI->isEntryFunction())
4559 return getImplicitArgPtr(DAG, DL);
4560 return getPreloadedValue(DAG, *MFI, VT,
4561 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
4563 case Intrinsic::amdgcn_kernarg_segment_ptr: {
4564 return getPreloadedValue(DAG, *MFI, VT,
4565 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
4567 case Intrinsic::amdgcn_dispatch_id: {
4568 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
4570 case Intrinsic::amdgcn_rcp:
4571 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
4572 case Intrinsic::amdgcn_rsq:
4573 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4574 case Intrinsic::amdgcn_rsq_legacy:
4575 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4576 return emitRemovedIntrinsicError(DAG, DL, VT);
4578 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
4579 case Intrinsic::amdgcn_rcp_legacy:
4580 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4581 return emitRemovedIntrinsicError(DAG, DL, VT);
4582 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
4583 case Intrinsic::amdgcn_rsq_clamp: {
4584 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4585 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
4587 Type *Type = VT.getTypeForEVT(*DAG.getContext());
4588 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
4589 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
4591 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4592 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
4593 DAG.getConstantFP(Max, DL, VT));
4594 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
4595 DAG.getConstantFP(Min, DL, VT));
4597 case Intrinsic::r600_read_ngroups_x:
4598 if (Subtarget->isAmdHsaOS())
4599 return emitNonHSAIntrinsicError(DAG, DL, VT);
4601 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4602 SI::KernelInputOffsets::NGROUPS_X, false);
4603 case Intrinsic::r600_read_ngroups_y:
4604 if (Subtarget->isAmdHsaOS())
4605 return emitNonHSAIntrinsicError(DAG, DL, VT);
4607 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4608 SI::KernelInputOffsets::NGROUPS_Y, false);
4609 case Intrinsic::r600_read_ngroups_z:
4610 if (Subtarget->isAmdHsaOS())
4611 return emitNonHSAIntrinsicError(DAG, DL, VT);
4613 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4614 SI::KernelInputOffsets::NGROUPS_Z, false);
4615 case Intrinsic::r600_read_global_size_x:
4616 if (Subtarget->isAmdHsaOS())
4617 return emitNonHSAIntrinsicError(DAG, DL, VT);
4619 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4620 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
4621 case Intrinsic::r600_read_global_size_y:
4622 if (Subtarget->isAmdHsaOS())
4623 return emitNonHSAIntrinsicError(DAG, DL, VT);
4625 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4626 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
4627 case Intrinsic::r600_read_global_size_z:
4628 if (Subtarget->isAmdHsaOS())
4629 return emitNonHSAIntrinsicError(DAG, DL, VT);
4631 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4632 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
4633 case Intrinsic::r600_read_local_size_x:
4634 if (Subtarget->isAmdHsaOS())
4635 return emitNonHSAIntrinsicError(DAG, DL, VT);
4637 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4638 SI::KernelInputOffsets::LOCAL_SIZE_X);
4639 case Intrinsic::r600_read_local_size_y:
4640 if (Subtarget->isAmdHsaOS())
4641 return emitNonHSAIntrinsicError(DAG, DL, VT);
4643 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4644 SI::KernelInputOffsets::LOCAL_SIZE_Y);
4645 case Intrinsic::r600_read_local_size_z:
4646 if (Subtarget->isAmdHsaOS())
4647 return emitNonHSAIntrinsicError(DAG, DL, VT);
4649 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4650 SI::KernelInputOffsets::LOCAL_SIZE_Z);
4651 case Intrinsic::amdgcn_workgroup_id_x:
4652 case Intrinsic::r600_read_tgid_x:
4653 return getPreloadedValue(DAG, *MFI, VT,
4654 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
4655 case Intrinsic::amdgcn_workgroup_id_y:
4656 case Intrinsic::r600_read_tgid_y:
4657 return getPreloadedValue(DAG, *MFI, VT,
4658 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
4659 case Intrinsic::amdgcn_workgroup_id_z:
4660 case Intrinsic::r600_read_tgid_z:
4661 return getPreloadedValue(DAG, *MFI, VT,
4662 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
4663 case Intrinsic::amdgcn_workitem_id_x: {
4664 case Intrinsic::r600_read_tidig_x:
4665 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4666 SDLoc(DAG.getEntryNode()),
4667 MFI->getArgInfo().WorkItemIDX);
4669 case Intrinsic::amdgcn_workitem_id_y:
4670 case Intrinsic::r600_read_tidig_y:
4671 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4672 SDLoc(DAG.getEntryNode()),
4673 MFI->getArgInfo().WorkItemIDY);
4674 case Intrinsic::amdgcn_workitem_id_z:
4675 case Intrinsic::r600_read_tidig_z:
4676 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4677 SDLoc(DAG.getEntryNode()),
4678 MFI->getArgInfo().WorkItemIDZ);
4679 case AMDGPUIntrinsic::SI_load_const: {
4685 MachineMemOperand *MMO = MF.getMachineMemOperand(
4686 MachinePointerInfo(),
4687 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
4688 MachineMemOperand::MOInvariant,
4689 VT.getStoreSize(), 4);
4690 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
4691 Op->getVTList(), Ops, VT, MMO);
4693 case Intrinsic::amdgcn_fdiv_fast:
4694 return lowerFDIV_FAST(Op, DAG);
4695 case Intrinsic::amdgcn_interp_mov: {
4696 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4697 SDValue Glue = M0.getValue(1);
4698 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
4699 Op.getOperand(2), Op.getOperand(3), Glue);
4701 case Intrinsic::amdgcn_interp_p1: {
4702 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4703 SDValue Glue = M0.getValue(1);
4704 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
4705 Op.getOperand(2), Op.getOperand(3), Glue);
4707 case Intrinsic::amdgcn_interp_p2: {
4708 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
4709 SDValue Glue = SDValue(M0.getNode(), 1);
4710 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
4711 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
4714 case Intrinsic::amdgcn_sin:
4715 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
4717 case Intrinsic::amdgcn_cos:
4718 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
4720 case Intrinsic::amdgcn_log_clamp: {
4721 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4724 DiagnosticInfoUnsupported BadIntrin(
4725 MF.getFunction(), "intrinsic not supported on subtarget",
4727 DAG.getContext()->diagnose(BadIntrin);
4728 return DAG.getUNDEF(VT);
4730 case Intrinsic::amdgcn_ldexp:
4731 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
4732 Op.getOperand(1), Op.getOperand(2));
4734 case Intrinsic::amdgcn_fract:
4735 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
4737 case Intrinsic::amdgcn_class:
4738 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
4739 Op.getOperand(1), Op.getOperand(2));
4740 case Intrinsic::amdgcn_div_fmas:
4741 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
4742 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
4745 case Intrinsic::amdgcn_div_fixup:
4746 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
4747 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4749 case Intrinsic::amdgcn_trig_preop:
4750 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
4751 Op.getOperand(1), Op.getOperand(2));
4752 case Intrinsic::amdgcn_div_scale: {
4753 // 3rd parameter required to be a constant.
4754 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4756 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
4758 // Translate to the operands expected by the machine instruction. The
4759 // first parameter must be the same as the first instruction.
4760 SDValue Numerator = Op.getOperand(1);
4761 SDValue Denominator = Op.getOperand(2);
4763 // Note this order is opposite of the machine instruction's operations,
4764 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
4765 // intrinsic has the numerator as the first operand to match a normal
4766 // division operation.
4768 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
4770 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
4771 Denominator, Numerator);
4773 case Intrinsic::amdgcn_icmp: {
4774 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4776 return DAG.getUNDEF(VT);
4778 int CondCode = CD->getSExtValue();
4779 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4780 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4781 return DAG.getUNDEF(VT);
4783 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4784 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4785 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4786 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4788 case Intrinsic::amdgcn_fcmp: {
4789 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4791 return DAG.getUNDEF(VT);
4793 int CondCode = CD->getSExtValue();
4794 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4795 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
4796 return DAG.getUNDEF(VT);
4798 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4799 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4800 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4801 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4803 case Intrinsic::amdgcn_fmed3:
4804 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
4805 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4806 case Intrinsic::amdgcn_fmul_legacy:
4807 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
4808 Op.getOperand(1), Op.getOperand(2));
4809 case Intrinsic::amdgcn_sffbh:
4810 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
4811 case Intrinsic::amdgcn_sbfe:
4812 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
4813 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4814 case Intrinsic::amdgcn_ubfe:
4815 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
4816 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4817 case Intrinsic::amdgcn_cvt_pkrtz:
4818 case Intrinsic::amdgcn_cvt_pknorm_i16:
4819 case Intrinsic::amdgcn_cvt_pknorm_u16:
4820 case Intrinsic::amdgcn_cvt_pk_i16:
4821 case Intrinsic::amdgcn_cvt_pk_u16: {
4822 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
4823 EVT VT = Op.getValueType();
4826 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
4827 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
4828 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
4829 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4830 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
4831 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4832 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
4833 Opcode = AMDGPUISD::CVT_PK_I16_I32;
4835 Opcode = AMDGPUISD::CVT_PK_U16_U32;
4837 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
4838 Op.getOperand(1), Op.getOperand(2));
4839 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
4841 case Intrinsic::amdgcn_wqm: {
4842 SDValue Src = Op.getOperand(1);
4843 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
4846 case Intrinsic::amdgcn_wwm: {
4847 SDValue Src = Op.getOperand(1);
4848 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
4851 case Intrinsic::amdgcn_image_getlod:
4852 case Intrinsic::amdgcn_image_getresinfo: {
4853 unsigned Idx = (IntrinsicID == Intrinsic::amdgcn_image_getresinfo) ? 3 : 4;
4855 // Replace dmask with everything disabled with undef.
4856 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(Idx));
4857 if (!DMask || DMask->isNullValue())
4858 return DAG.getUNDEF(Op.getValueType());
4866 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4867 SelectionDAG &DAG) const {
4868 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4872 case Intrinsic::amdgcn_atomic_inc:
4873 case Intrinsic::amdgcn_atomic_dec:
4874 case Intrinsic::amdgcn_ds_fadd:
4875 case Intrinsic::amdgcn_ds_fmin:
4876 case Intrinsic::amdgcn_ds_fmax: {
4877 MemSDNode *M = cast<MemSDNode>(Op);
4880 case Intrinsic::amdgcn_atomic_inc:
4881 Opc = AMDGPUISD::ATOMIC_INC;
4883 case Intrinsic::amdgcn_atomic_dec:
4884 Opc = AMDGPUISD::ATOMIC_DEC;
4886 case Intrinsic::amdgcn_ds_fadd:
4887 Opc = AMDGPUISD::ATOMIC_LOAD_FADD;
4889 case Intrinsic::amdgcn_ds_fmin:
4890 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
4892 case Intrinsic::amdgcn_ds_fmax:
4893 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
4896 llvm_unreachable("Unknown intrinsic!");
4899 M->getOperand(0), // Chain
4900 M->getOperand(2), // Ptr
4901 M->getOperand(3) // Value
4904 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
4905 M->getMemoryVT(), M->getMemOperand());
4907 case Intrinsic::amdgcn_buffer_load:
4908 case Intrinsic::amdgcn_buffer_load_format: {
4910 Op.getOperand(0), // Chain
4911 Op.getOperand(2), // rsrc
4912 Op.getOperand(3), // vindex
4913 Op.getOperand(4), // offset
4914 Op.getOperand(5), // glc
4915 Op.getOperand(6) // slc
4918 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
4919 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
4920 EVT VT = Op.getValueType();
4921 EVT IntVT = VT.changeTypeToInteger();
4923 auto *M = cast<MemSDNode>(Op);
4924 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
4925 M->getMemOperand());
4927 case Intrinsic::amdgcn_tbuffer_load: {
4928 MemSDNode *M = cast<MemSDNode>(Op);
4930 Op.getOperand(0), // Chain
4931 Op.getOperand(2), // rsrc
4932 Op.getOperand(3), // vindex
4933 Op.getOperand(4), // voffset
4934 Op.getOperand(5), // soffset
4935 Op.getOperand(6), // offset
4936 Op.getOperand(7), // dfmt
4937 Op.getOperand(8), // nfmt
4938 Op.getOperand(9), // glc
4939 Op.getOperand(10) // slc
4942 EVT VT = Op.getValueType();
4944 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
4945 Op->getVTList(), Ops, VT, M->getMemOperand());
4947 case Intrinsic::amdgcn_buffer_atomic_swap:
4948 case Intrinsic::amdgcn_buffer_atomic_add:
4949 case Intrinsic::amdgcn_buffer_atomic_sub:
4950 case Intrinsic::amdgcn_buffer_atomic_smin:
4951 case Intrinsic::amdgcn_buffer_atomic_umin:
4952 case Intrinsic::amdgcn_buffer_atomic_smax:
4953 case Intrinsic::amdgcn_buffer_atomic_umax:
4954 case Intrinsic::amdgcn_buffer_atomic_and:
4955 case Intrinsic::amdgcn_buffer_atomic_or:
4956 case Intrinsic::amdgcn_buffer_atomic_xor: {
4958 Op.getOperand(0), // Chain
4959 Op.getOperand(2), // vdata
4960 Op.getOperand(3), // rsrc
4961 Op.getOperand(4), // vindex
4962 Op.getOperand(5), // offset
4963 Op.getOperand(6) // slc
4965 EVT VT = Op.getValueType();
4967 auto *M = cast<MemSDNode>(Op);
4968 unsigned Opcode = 0;
4971 case Intrinsic::amdgcn_buffer_atomic_swap:
4972 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
4974 case Intrinsic::amdgcn_buffer_atomic_add:
4975 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
4977 case Intrinsic::amdgcn_buffer_atomic_sub:
4978 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
4980 case Intrinsic::amdgcn_buffer_atomic_smin:
4981 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
4983 case Intrinsic::amdgcn_buffer_atomic_umin:
4984 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
4986 case Intrinsic::amdgcn_buffer_atomic_smax:
4987 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
4989 case Intrinsic::amdgcn_buffer_atomic_umax:
4990 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
4992 case Intrinsic::amdgcn_buffer_atomic_and:
4993 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
4995 case Intrinsic::amdgcn_buffer_atomic_or:
4996 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
4998 case Intrinsic::amdgcn_buffer_atomic_xor:
4999 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5002 llvm_unreachable("unhandled atomic opcode");
5005 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5006 M->getMemOperand());
5009 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
5011 Op.getOperand(0), // Chain
5012 Op.getOperand(2), // src
5013 Op.getOperand(3), // cmp
5014 Op.getOperand(4), // rsrc
5015 Op.getOperand(5), // vindex
5016 Op.getOperand(6), // offset
5017 Op.getOperand(7) // slc
5019 EVT VT = Op.getValueType();
5020 auto *M = cast<MemSDNode>(Op);
5022 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
5023 Op->getVTList(), Ops, VT, M->getMemOperand());
5027 case Intrinsic::amdgcn_image_sample:
5028 case Intrinsic::amdgcn_image_sample_cl:
5029 case Intrinsic::amdgcn_image_sample_d:
5030 case Intrinsic::amdgcn_image_sample_d_cl:
5031 case Intrinsic::amdgcn_image_sample_l:
5032 case Intrinsic::amdgcn_image_sample_b:
5033 case Intrinsic::amdgcn_image_sample_b_cl:
5034 case Intrinsic::amdgcn_image_sample_lz:
5035 case Intrinsic::amdgcn_image_sample_cd:
5036 case Intrinsic::amdgcn_image_sample_cd_cl:
5038 // Sample with comparison.
5039 case Intrinsic::amdgcn_image_sample_c:
5040 case Intrinsic::amdgcn_image_sample_c_cl:
5041 case Intrinsic::amdgcn_image_sample_c_d:
5042 case Intrinsic::amdgcn_image_sample_c_d_cl:
5043 case Intrinsic::amdgcn_image_sample_c_l:
5044 case Intrinsic::amdgcn_image_sample_c_b:
5045 case Intrinsic::amdgcn_image_sample_c_b_cl:
5046 case Intrinsic::amdgcn_image_sample_c_lz:
5047 case Intrinsic::amdgcn_image_sample_c_cd:
5048 case Intrinsic::amdgcn_image_sample_c_cd_cl:
5050 // Sample with offsets.
5051 case Intrinsic::amdgcn_image_sample_o:
5052 case Intrinsic::amdgcn_image_sample_cl_o:
5053 case Intrinsic::amdgcn_image_sample_d_o:
5054 case Intrinsic::amdgcn_image_sample_d_cl_o:
5055 case Intrinsic::amdgcn_image_sample_l_o:
5056 case Intrinsic::amdgcn_image_sample_b_o:
5057 case Intrinsic::amdgcn_image_sample_b_cl_o:
5058 case Intrinsic::amdgcn_image_sample_lz_o:
5059 case Intrinsic::amdgcn_image_sample_cd_o:
5060 case Intrinsic::amdgcn_image_sample_cd_cl_o:
5062 // Sample with comparison and offsets.
5063 case Intrinsic::amdgcn_image_sample_c_o:
5064 case Intrinsic::amdgcn_image_sample_c_cl_o:
5065 case Intrinsic::amdgcn_image_sample_c_d_o:
5066 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
5067 case Intrinsic::amdgcn_image_sample_c_l_o:
5068 case Intrinsic::amdgcn_image_sample_c_b_o:
5069 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
5070 case Intrinsic::amdgcn_image_sample_c_lz_o:
5071 case Intrinsic::amdgcn_image_sample_c_cd_o:
5072 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: {
5073 // Replace dmask with everything disabled with undef.
5074 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
5075 if (!DMask || DMask->isNullValue()) {
5076 SDValue Undef = DAG.getUNDEF(Op.getValueType());
5077 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
5087 SDValue SITargetLowering::handleD16VData(SDValue VData,
5088 SelectionDAG &DAG) const {
5089 EVT StoreVT = VData.getValueType();
5092 if (StoreVT.isVector()) {
5093 assert ((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
5094 if (!Subtarget->hasUnpackedD16VMem()) {
5095 if (!isTypeLegal(StoreVT)) {
5096 // If Target supports packed vmem, we just need to workaround
5097 // the illegal type by casting to an equivalent one.
5098 EVT EquivStoreVT = getEquivalentMemType(*DAG.getContext(), StoreVT);
5099 return DAG.getNode(ISD::BITCAST, DL, EquivStoreVT, VData);
5101 } else { // We need to unpack the packed data to store.
5102 EVT IntStoreVT = StoreVT.changeTypeToInteger();
5103 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
5104 EVT EquivStoreVT = (StoreVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32;
5105 return DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
5108 // No change for f16 and legal vector D16 types.
5112 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5113 SelectionDAG &DAG) const {
5115 SDValue Chain = Op.getOperand(0);
5116 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5117 MachineFunction &MF = DAG.getMachineFunction();
5119 switch (IntrinsicID) {
5120 case Intrinsic::amdgcn_exp: {
5121 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5122 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5123 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
5124 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
5126 const SDValue Ops[] = {
5128 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5129 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
5130 Op.getOperand(4), // src0
5131 Op.getOperand(5), // src1
5132 Op.getOperand(6), // src2
5133 Op.getOperand(7), // src3
5134 DAG.getTargetConstant(0, DL, MVT::i1), // compr
5135 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5138 unsigned Opc = Done->isNullValue() ?
5139 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5140 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5142 case Intrinsic::amdgcn_exp_compr: {
5143 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5144 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5145 SDValue Src0 = Op.getOperand(4);
5146 SDValue Src1 = Op.getOperand(5);
5147 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
5148 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
5150 SDValue Undef = DAG.getUNDEF(MVT::f32);
5151 const SDValue Ops[] = {
5153 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5154 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
5155 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
5156 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
5159 DAG.getTargetConstant(1, DL, MVT::i1), // compr
5160 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5163 unsigned Opc = Done->isNullValue() ?
5164 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5165 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5167 case Intrinsic::amdgcn_s_sendmsg:
5168 case Intrinsic::amdgcn_s_sendmsghalt: {
5169 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
5170 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
5171 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
5172 SDValue Glue = Chain.getValue(1);
5173 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
5174 Op.getOperand(2), Glue);
5176 case Intrinsic::amdgcn_init_exec: {
5177 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
5180 case Intrinsic::amdgcn_init_exec_from_input: {
5181 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
5182 Op.getOperand(2), Op.getOperand(3));
5184 case AMDGPUIntrinsic::AMDGPU_kill: {
5185 SDValue Src = Op.getOperand(2);
5186 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
5187 if (!K->isNegative())
5190 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
5191 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
5194 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
5195 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
5197 case Intrinsic::amdgcn_s_barrier: {
5198 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
5199 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
5200 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
5201 if (WGSize <= ST.getWavefrontSize())
5202 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
5203 Op.getOperand(0)), 0);
5207 case AMDGPUIntrinsic::SI_tbuffer_store: {
5209 // Extract vindex and voffset from vaddr as appropriate
5210 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10));
5211 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11));
5212 SDValue VAddr = Op.getOperand(5);
5214 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
5216 assert(!(OffEn->isOne() && IdxEn->isOne()) &&
5217 "Legacy intrinsic doesn't support both offset and index - use new version");
5219 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero;
5220 SDValue VOffset = OffEn->isOne() ? VAddr : Zero;
5222 // Deal with the vec-3 case
5223 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4));
5224 auto Opcode = NumChannels->getZExtValue() == 3 ?
5225 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT;
5229 Op.getOperand(3), // vdata
5230 Op.getOperand(2), // rsrc
5233 Op.getOperand(6), // soffset
5234 Op.getOperand(7), // inst_offset
5235 Op.getOperand(8), // dfmt
5236 Op.getOperand(9), // nfmt
5237 Op.getOperand(12), // glc
5238 Op.getOperand(13), // slc
5241 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 &&
5242 "Value of tfe other than zero is unsupported");
5244 EVT VT = Op.getOperand(3).getValueType();
5245 MachineMemOperand *MMO = MF.getMachineMemOperand(
5246 MachinePointerInfo(),
5247 MachineMemOperand::MOStore,
5248 VT.getStoreSize(), 4);
5249 return DAG.getMemIntrinsicNode(Opcode, DL,
5250 Op->getVTList(), Ops, VT, MMO);
5253 case Intrinsic::amdgcn_tbuffer_store: {
5254 SDValue VData = Op.getOperand(2);
5255 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5257 VData = handleD16VData(VData, DAG);
5261 Op.getOperand(3), // rsrc
5262 Op.getOperand(4), // vindex
5263 Op.getOperand(5), // voffset
5264 Op.getOperand(6), // soffset
5265 Op.getOperand(7), // offset
5266 Op.getOperand(8), // dfmt
5267 Op.getOperand(9), // nfmt
5268 Op.getOperand(10), // glc
5269 Op.getOperand(11) // slc
5271 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
5272 AMDGPUISD::TBUFFER_STORE_FORMAT;
5273 MemSDNode *M = cast<MemSDNode>(Op);
5274 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5275 M->getMemoryVT(), M->getMemOperand());
5278 case Intrinsic::amdgcn_buffer_store:
5279 case Intrinsic::amdgcn_buffer_store_format: {
5280 SDValue VData = Op.getOperand(2);
5281 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5283 VData = handleD16VData(VData, DAG);
5287 Op.getOperand(3), // rsrc
5288 Op.getOperand(4), // vindex
5289 Op.getOperand(5), // offset
5290 Op.getOperand(6), // glc
5291 Op.getOperand(7) // slc
5293 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
5294 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
5295 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
5296 MemSDNode *M = cast<MemSDNode>(Op);
5297 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5298 M->getMemoryVT(), M->getMemOperand());
5301 case Intrinsic::amdgcn_image_store:
5302 case Intrinsic::amdgcn_image_store_mip: {
5303 SDValue VData = Op.getOperand(2);
5304 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5306 VData = handleD16VData(VData, DAG);
5310 Op.getOperand(3), // vaddr
5311 Op.getOperand(4), // rsrc
5312 Op.getOperand(5), // dmask
5313 Op.getOperand(6), // glc
5314 Op.getOperand(7), // slc
5315 Op.getOperand(8), // lwe
5316 Op.getOperand(9) // da
5318 unsigned Opc = (IntrinsicID==Intrinsic::amdgcn_image_store) ?
5319 AMDGPUISD::IMAGE_STORE : AMDGPUISD::IMAGE_STORE_MIP;
5320 MemSDNode *M = cast<MemSDNode>(Op);
5321 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5322 M->getMemoryVT(), M->getMemOperand());
5330 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5332 LoadSDNode *Load = cast<LoadSDNode>(Op);
5333 ISD::LoadExtType ExtType = Load->getExtensionType();
5334 EVT MemVT = Load->getMemoryVT();
5336 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
5337 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
5340 // FIXME: Copied from PPC
5341 // First, load into 32 bits, then truncate to 1 bit.
5343 SDValue Chain = Load->getChain();
5344 SDValue BasePtr = Load->getBasePtr();
5345 MachineMemOperand *MMO = Load->getMemOperand();
5347 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
5349 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
5350 BasePtr, RealMemVT, MMO);
5353 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
5357 return DAG.getMergeValues(Ops, DL);
5360 if (!MemVT.isVector())
5363 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
5364 "Custom lowering for non-i32 vectors hasn't been implemented.");
5366 unsigned Alignment = Load->getAlignment();
5367 unsigned AS = Load->getAddressSpace();
5368 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
5371 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
5372 return DAG.getMergeValues(Ops, DL);
5375 MachineFunction &MF = DAG.getMachineFunction();
5376 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5377 // If there is a possibilty that flat instruction access scratch memory
5378 // then we need to use the same legalization rules we use for private.
5379 if (AS == AMDGPUASI.FLAT_ADDRESS)
5380 AS = MFI->hasFlatScratchInit() ?
5381 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5383 unsigned NumElements = MemVT.getVectorNumElements();
5385 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5386 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
5387 if (!Op->isDivergent() && Alignment >= 4)
5389 // Non-uniform loads will be selected to MUBUF instructions, so they
5390 // have the same legalization requirements as global and private
5395 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5396 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5397 AS == AMDGPUASI.GLOBAL_ADDRESS) {
5398 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
5399 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
5402 // Non-uniform loads will be selected to MUBUF instructions, so they
5403 // have the same legalization requirements as global and private
5407 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5408 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5409 AS == AMDGPUASI.GLOBAL_ADDRESS ||
5410 AS == AMDGPUASI.FLAT_ADDRESS) {
5411 if (NumElements > 4)
5412 return SplitVectorLoad(Op, DAG);
5413 // v4 loads are supported for private and global memory.
5416 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5417 // Depending on the setting of the private_element_size field in the
5418 // resource descriptor, we can only make private accesses up to a certain
5420 switch (Subtarget->getMaxPrivateElementSize()) {
5422 return scalarizeVectorLoad(Load, DAG);
5424 if (NumElements > 2)
5425 return SplitVectorLoad(Op, DAG);
5428 // Same as global/flat
5429 if (NumElements > 4)
5430 return SplitVectorLoad(Op, DAG);
5433 llvm_unreachable("unsupported private_element_size");
5435 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5436 // Use ds_read_b128 if possible.
5437 if (Subtarget->useDS128(EnableDS128) && Load->getAlignment() >= 16 &&
5438 MemVT.getStoreSize() == 16)
5441 if (NumElements > 2)
5442 return SplitVectorLoad(Op, DAG);
5447 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5448 if (Op.getValueType() != MVT::i64)
5452 SDValue Cond = Op.getOperand(0);
5454 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
5455 SDValue One = DAG.getConstant(1, DL, MVT::i32);
5457 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
5458 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
5460 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
5461 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
5463 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
5465 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
5466 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
5468 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
5470 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
5471 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
5474 // Catch division cases where we can use shortcuts with rcp and rsq
5476 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
5477 SelectionDAG &DAG) const {
5479 SDValue LHS = Op.getOperand(0);
5480 SDValue RHS = Op.getOperand(1);
5481 EVT VT = Op.getValueType();
5482 const SDNodeFlags Flags = Op->getFlags();
5483 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath ||
5484 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal();
5486 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
5489 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
5490 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
5491 if (CLHS->isExactlyValue(1.0)) {
5492 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
5493 // the CI documentation has a worst case error of 1 ulp.
5494 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
5495 // use it as long as we aren't trying to use denormals.
5497 // v_rcp_f16 and v_rsq_f16 DO support denormals.
5499 // 1.0 / sqrt(x) -> rsq(x)
5501 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
5502 // error seems really high at 2^29 ULP.
5503 if (RHS.getOpcode() == ISD::FSQRT)
5504 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
5506 // 1.0 / x -> rcp(x)
5507 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5510 // Same as for 1.0, but expand the sign out of the constant.
5511 if (CLHS->isExactlyValue(-1.0)) {
5512 // -1.0 / x -> rcp (fneg x)
5513 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
5514 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
5520 // Turn into multiply by the reciprocal.
5521 // x / y -> x * (1.0 / y)
5522 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5523 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
5529 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5530 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
5531 if (GlueChain->getNumValues() <= 1) {
5532 return DAG.getNode(Opcode, SL, VT, A, B);
5535 assert(GlueChain->getNumValues() == 3);
5537 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5539 default: llvm_unreachable("no chain equivalent for opcode");
5541 Opcode = AMDGPUISD::FMUL_W_CHAIN;
5545 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
5546 GlueChain.getValue(2));
5549 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5550 EVT VT, SDValue A, SDValue B, SDValue C,
5551 SDValue GlueChain) {
5552 if (GlueChain->getNumValues() <= 1) {
5553 return DAG.getNode(Opcode, SL, VT, A, B, C);
5556 assert(GlueChain->getNumValues() == 3);
5558 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5560 default: llvm_unreachable("no chain equivalent for opcode");
5562 Opcode = AMDGPUISD::FMA_W_CHAIN;
5566 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
5567 GlueChain.getValue(2));
5570 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
5571 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5575 SDValue Src0 = Op.getOperand(0);
5576 SDValue Src1 = Op.getOperand(1);
5578 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5579 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5581 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
5582 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
5584 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
5585 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
5587 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
5590 // Faster 2.5 ULP division that does not support denormals.
5591 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
5593 SDValue LHS = Op.getOperand(1);
5594 SDValue RHS = Op.getOperand(2);
5596 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
5598 const APFloat K0Val(BitsToFloat(0x6f800000));
5599 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
5601 const APFloat K1Val(BitsToFloat(0x2f800000));
5602 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
5604 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5607 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
5609 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
5611 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
5613 // TODO: Should this propagate fast-math-flags?
5614 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
5616 // rcp does not support denormals.
5617 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
5619 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
5621 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
5624 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
5625 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5629 SDValue LHS = Op.getOperand(0);
5630 SDValue RHS = Op.getOperand(1);
5632 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5634 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
5636 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5638 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5641 // Denominator is scaled to not be denormal, so using rcp is ok.
5642 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
5644 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
5647 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
5648 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
5649 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
5651 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
5653 if (!Subtarget->hasFP32Denormals()) {
5654 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
5655 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
5657 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
5659 EnableDenormValue, BitField);
5662 EnableDenorm.getValue(0),
5663 EnableDenorm.getValue(1)
5666 NegDivScale0 = DAG.getMergeValues(Ops, SL);
5669 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
5670 ApproxRcp, One, NegDivScale0);
5672 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
5675 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
5678 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
5679 NumeratorScaled, Mul);
5681 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
5683 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
5684 NumeratorScaled, Fma3);
5686 if (!Subtarget->hasFP32Denormals()) {
5687 const SDValue DisableDenormValue =
5688 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
5689 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
5695 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
5696 DisableDenorm, DAG.getRoot());
5697 DAG.setRoot(OutputChain);
5700 SDValue Scale = NumeratorScaled.getValue(1);
5701 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
5702 Fma4, Fma1, Fma3, Scale);
5704 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
5707 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
5708 if (DAG.getTarget().Options.UnsafeFPMath)
5709 return lowerFastUnsafeFDIV(Op, DAG);
5712 SDValue X = Op.getOperand(0);
5713 SDValue Y = Op.getOperand(1);
5715 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
5717 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
5719 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
5721 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
5723 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
5725 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
5727 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
5729 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
5731 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
5733 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
5734 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
5736 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
5737 NegDivScale0, Mul, DivScale1);
5741 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
5742 // Workaround a hardware bug on SI where the condition output from div_scale
5745 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
5747 // Figure out if the scale to use for div_fmas.
5748 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
5749 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
5750 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
5751 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
5753 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
5754 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
5757 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
5759 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
5761 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
5762 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
5763 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
5765 Scale = DivScale1.getValue(1);
5768 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
5769 Fma4, Fma3, Mul, Scale);
5771 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
5774 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
5775 EVT VT = Op.getValueType();
5778 return LowerFDIV32(Op, DAG);
5781 return LowerFDIV64(Op, DAG);
5784 return LowerFDIV16(Op, DAG);
5786 llvm_unreachable("Unexpected type for fdiv");
5789 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5791 StoreSDNode *Store = cast<StoreSDNode>(Op);
5792 EVT VT = Store->getMemoryVT();
5794 if (VT == MVT::i1) {
5795 return DAG.getTruncStore(Store->getChain(), DL,
5796 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
5797 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
5800 assert(VT.isVector() &&
5801 Store->getValue().getValueType().getScalarType() == MVT::i32);
5803 unsigned AS = Store->getAddressSpace();
5804 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
5805 AS, Store->getAlignment())) {
5806 return expandUnalignedStore(Store, DAG);
5809 MachineFunction &MF = DAG.getMachineFunction();
5810 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5811 // If there is a possibilty that flat instruction access scratch memory
5812 // then we need to use the same legalization rules we use for private.
5813 if (AS == AMDGPUASI.FLAT_ADDRESS)
5814 AS = MFI->hasFlatScratchInit() ?
5815 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5817 unsigned NumElements = VT.getVectorNumElements();
5818 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
5819 AS == AMDGPUASI.FLAT_ADDRESS) {
5820 if (NumElements > 4)
5821 return SplitVectorStore(Op, DAG);
5823 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5824 switch (Subtarget->getMaxPrivateElementSize()) {
5826 return scalarizeVectorStore(Store, DAG);
5828 if (NumElements > 2)
5829 return SplitVectorStore(Op, DAG);
5832 if (NumElements > 4)
5833 return SplitVectorStore(Op, DAG);
5836 llvm_unreachable("unsupported private_element_size");
5838 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5839 // Use ds_write_b128 if possible.
5840 if (Subtarget->useDS128(EnableDS128) && Store->getAlignment() >= 16 &&
5841 VT.getStoreSize() == 16)
5844 if (NumElements > 2)
5845 return SplitVectorStore(Op, DAG);
5848 llvm_unreachable("unhandled address space");
5852 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
5854 EVT VT = Op.getValueType();
5855 SDValue Arg = Op.getOperand(0);
5856 // TODO: Should this propagate fast-math-flags?
5857 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
5858 DAG.getNode(ISD::FMUL, DL, VT, Arg,
5859 DAG.getConstantFP(0.5/M_PI, DL,
5862 switch (Op.getOpcode()) {
5864 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
5866 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
5868 llvm_unreachable("Wrong trig opcode");
5872 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
5873 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
5874 assert(AtomicNode->isCompareAndSwap());
5875 unsigned AS = AtomicNode->getAddressSpace();
5877 // No custom lowering required for local address space
5878 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
5881 // Non-local address space requires custom lowering for atomic compare
5882 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
5884 SDValue ChainIn = Op.getOperand(0);
5885 SDValue Addr = Op.getOperand(1);
5886 SDValue Old = Op.getOperand(2);
5887 SDValue New = Op.getOperand(3);
5888 EVT VT = Op.getValueType();
5889 MVT SimpleVT = VT.getSimpleVT();
5890 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
5892 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
5893 SDValue Ops[] = { ChainIn, Addr, NewOld };
5895 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
5896 Ops, VT, AtomicNode->getMemOperand());
5899 //===----------------------------------------------------------------------===//
5900 // Custom DAG optimizations
5901 //===----------------------------------------------------------------------===//
5903 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
5904 DAGCombinerInfo &DCI) const {
5905 EVT VT = N->getValueType(0);
5906 EVT ScalarVT = VT.getScalarType();
5907 if (ScalarVT != MVT::f32)
5910 SelectionDAG &DAG = DCI.DAG;
5913 SDValue Src = N->getOperand(0);
5914 EVT SrcVT = Src.getValueType();
5916 // TODO: We could try to match extracting the higher bytes, which would be
5917 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
5918 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
5919 // about in practice.
5920 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
5921 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
5922 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
5923 DCI.AddToWorklist(Cvt.getNode());
5931 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
5933 // This is a variant of
5934 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
5936 // The normal DAG combiner will do this, but only if the add has one use since
5937 // that would increase the number of instructions.
5939 // This prevents us from seeing a constant offset that can be folded into a
5940 // memory instruction's addressing mode. If we know the resulting add offset of
5941 // a pointer can be folded into an addressing offset, we can replace the pointer
5942 // operand with the add of new constant offset. This eliminates one of the uses,
5943 // and may allow the remaining use to also be simplified.
5945 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
5948 DAGCombinerInfo &DCI) const {
5949 SDValue N0 = N->getOperand(0);
5950 SDValue N1 = N->getOperand(1);
5952 // We only do this to handle cases where it's profitable when there are
5953 // multiple uses of the add, so defer to the standard combine.
5954 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
5958 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
5962 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5966 // If the resulting offset is too large, we can't fold it into the addressing
5968 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
5969 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
5972 AM.HasBaseReg = true;
5973 AM.BaseOffs = Offset.getSExtValue();
5974 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
5977 SelectionDAG &DAG = DCI.DAG;
5979 EVT VT = N->getValueType(0);
5981 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
5982 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
5985 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
5986 (N0.getOpcode() == ISD::OR ||
5987 N0->getFlags().hasNoUnsignedWrap()));
5989 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
5992 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
5993 DAGCombinerInfo &DCI) const {
5994 SDValue Ptr = N->getBasePtr();
5995 SelectionDAG &DAG = DCI.DAG;
5998 // TODO: We could also do this for multiplies.
5999 if (Ptr.getOpcode() == ISD::SHL) {
6000 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
6001 N->getMemoryVT(), DCI);
6003 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
6005 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
6006 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
6013 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
6014 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
6015 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
6016 (Opc == ISD::XOR && Val == 0);
6019 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
6020 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
6021 // integer combine opportunities since most 64-bit operations are decomposed
6022 // this way. TODO: We won't want this for SALU especially if it is an inline
6024 SDValue SITargetLowering::splitBinaryBitConstantOp(
6025 DAGCombinerInfo &DCI,
6027 unsigned Opc, SDValue LHS,
6028 const ConstantSDNode *CRHS) const {
6029 uint64_t Val = CRHS->getZExtValue();
6030 uint32_t ValLo = Lo_32(Val);
6031 uint32_t ValHi = Hi_32(Val);
6032 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6034 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
6035 bitOpWithConstantIsReducible(Opc, ValHi)) ||
6036 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
6037 // If we need to materialize a 64-bit immediate, it will be split up later
6038 // anyway. Avoid creating the harder to understand 64-bit immediate
6040 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
6046 // Returns true if argument is a boolean value which is not serialized into
6047 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
6048 static bool isBoolSGPR(SDValue V) {
6049 if (V.getValueType() != MVT::i1)
6051 switch (V.getOpcode()) {
6057 case AMDGPUISD::FP_CLASS:
6063 SDValue SITargetLowering::performAndCombine(SDNode *N,
6064 DAGCombinerInfo &DCI) const {
6065 if (DCI.isBeforeLegalize())
6068 SelectionDAG &DAG = DCI.DAG;
6069 EVT VT = N->getValueType(0);
6070 SDValue LHS = N->getOperand(0);
6071 SDValue RHS = N->getOperand(1);
6074 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6075 if (VT == MVT::i64 && CRHS) {
6077 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
6081 if (CRHS && VT == MVT::i32) {
6082 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
6083 // nb = number of trailing zeroes in mask
6084 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
6085 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
6086 uint64_t Mask = CRHS->getZExtValue();
6087 unsigned Bits = countPopulation(Mask);
6088 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
6089 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
6090 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
6091 unsigned Shift = CShift->getZExtValue();
6092 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
6093 unsigned Offset = NB + Shift;
6094 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
6096 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
6098 DAG.getConstant(Offset, SL, MVT::i32),
6099 DAG.getConstant(Bits, SL, MVT::i32));
6100 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6101 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
6102 DAG.getValueType(NarrowVT));
6103 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
6104 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
6111 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
6112 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
6113 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
6114 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6115 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
6117 SDValue X = LHS.getOperand(0);
6118 SDValue Y = RHS.getOperand(0);
6119 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
6122 if (LCC == ISD::SETO) {
6123 if (X != LHS.getOperand(1))
6126 if (RCC == ISD::SETUNE) {
6127 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
6128 if (!C1 || !C1->isInfinity() || C1->isNegative())
6131 const uint32_t Mask = SIInstrFlags::N_NORMAL |
6132 SIInstrFlags::N_SUBNORMAL |
6133 SIInstrFlags::N_ZERO |
6134 SIInstrFlags::P_ZERO |
6135 SIInstrFlags::P_SUBNORMAL |
6136 SIInstrFlags::P_NORMAL;
6138 static_assert(((~(SIInstrFlags::S_NAN |
6139 SIInstrFlags::Q_NAN |
6140 SIInstrFlags::N_INFINITY |
6141 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
6145 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6146 X, DAG.getConstant(Mask, DL, MVT::i32));
6151 if (VT == MVT::i32 &&
6152 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
6153 // and x, (sext cc from i1) => select cc, x, 0
6154 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
6155 std::swap(LHS, RHS);
6156 if (isBoolSGPR(RHS.getOperand(0)))
6157 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
6158 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
6164 SDValue SITargetLowering::performOrCombine(SDNode *N,
6165 DAGCombinerInfo &DCI) const {
6166 SelectionDAG &DAG = DCI.DAG;
6167 SDValue LHS = N->getOperand(0);
6168 SDValue RHS = N->getOperand(1);
6170 EVT VT = N->getValueType(0);
6171 if (VT == MVT::i1) {
6172 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
6173 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
6174 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
6175 SDValue Src = LHS.getOperand(0);
6176 if (Src != RHS.getOperand(0))
6179 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6180 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6184 // Only 10 bits are used.
6185 static const uint32_t MaxMask = 0x3ff;
6187 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
6189 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6190 Src, DAG.getConstant(NewMask, DL, MVT::i32));
6199 // TODO: This could be a generic combine with a predicate for extracting the
6200 // high half of an integer being free.
6202 // (or i64:x, (zero_extend i32:y)) ->
6203 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
6204 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
6205 RHS.getOpcode() != ISD::ZERO_EXTEND)
6206 std::swap(LHS, RHS);
6208 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
6209 SDValue ExtSrc = RHS.getOperand(0);
6210 EVT SrcVT = ExtSrc.getValueType();
6211 if (SrcVT == MVT::i32) {
6213 SDValue LowLHS, HiBits;
6214 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
6215 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
6217 DCI.AddToWorklist(LowOr.getNode());
6218 DCI.AddToWorklist(HiBits.getNode());
6220 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
6222 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
6226 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
6229 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
6236 SDValue SITargetLowering::performXorCombine(SDNode *N,
6237 DAGCombinerInfo &DCI) const {
6238 EVT VT = N->getValueType(0);
6242 SDValue LHS = N->getOperand(0);
6243 SDValue RHS = N->getOperand(1);
6245 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6248 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
6255 // Instructions that will be lowered with a final instruction that zeros the
6256 // high result bits.
6257 // XXX - probably only need to list legal operations.
6258 static bool fp16SrcZerosHighBits(unsigned Opc) {
6267 case ISD::FCANONICALIZE:
6269 case ISD::UINT_TO_FP:
6270 case ISD::SINT_TO_FP:
6272 // Fabs is lowered to a bit operation, but it's an and which will clear the
6273 // high bits anyway.
6287 case ISD::FNEARBYINT:
6292 case AMDGPUISD::FRACT:
6293 case AMDGPUISD::CLAMP:
6294 case AMDGPUISD::COS_HW:
6295 case AMDGPUISD::SIN_HW:
6296 case AMDGPUISD::FMIN3:
6297 case AMDGPUISD::FMAX3:
6298 case AMDGPUISD::FMED3:
6299 case AMDGPUISD::FMAD_FTZ:
6300 case AMDGPUISD::RCP:
6301 case AMDGPUISD::RSQ:
6302 case AMDGPUISD::LDEXP:
6305 // fcopysign, select and others may be lowered to 32-bit bit operations
6306 // which don't zero the high bits.
6311 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
6312 DAGCombinerInfo &DCI) const {
6313 if (!Subtarget->has16BitInsts() ||
6314 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6317 EVT VT = N->getValueType(0);
6321 SDValue Src = N->getOperand(0);
6322 if (Src.getValueType() != MVT::i16)
6325 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
6326 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
6327 if (Src.getOpcode() == ISD::BITCAST) {
6328 SDValue BCSrc = Src.getOperand(0);
6329 if (BCSrc.getValueType() == MVT::f16 &&
6330 fp16SrcZerosHighBits(BCSrc.getOpcode()))
6331 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
6337 SDValue SITargetLowering::performClassCombine(SDNode *N,
6338 DAGCombinerInfo &DCI) const {
6339 SelectionDAG &DAG = DCI.DAG;
6340 SDValue Mask = N->getOperand(1);
6342 // fp_class x, 0 -> false
6343 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
6344 if (CMask->isNullValue())
6345 return DAG.getConstant(0, SDLoc(N), MVT::i1);
6348 if (N->getOperand(0).isUndef())
6349 return DAG.getUNDEF(MVT::i1);
6354 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
6355 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
6358 return DAG.isKnownNeverNaN(Op);
6361 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op,
6362 const SISubtarget *ST, unsigned MaxDepth=5) {
6363 // If source is a result of another standard FP operation it is already in
6366 switch (Op.getOpcode()) {
6370 // These will flush denorms if required.
6380 case ISD::FCANONICALIZE:
6384 return Op.getValueType().getScalarType() != MVT::f16 ||
6385 ST->hasFP16Denormals();
6387 case ISD::FP_EXTEND:
6388 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 ||
6389 ST->hasFP16Denormals();
6391 case ISD::FP16_TO_FP:
6392 case ISD::FP_TO_FP16:
6393 return ST->hasFP16Denormals();
6395 // It can/will be lowered or combined as a bit operation.
6396 // Need to check their input recursively to handle.
6399 return (MaxDepth > 0) &&
6400 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1);
6405 return Op.getValueType().getScalarType() != MVT::f16;
6407 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms.
6408 // For such targets need to check their input recursively.
6414 if (ST->supportsMinMaxDenormModes() &&
6415 DAG.isKnownNeverNaN(Op.getOperand(0)) &&
6416 DAG.isKnownNeverNaN(Op.getOperand(1)))
6419 return (MaxDepth > 0) &&
6420 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) &&
6421 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1);
6423 case ISD::ConstantFP: {
6424 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF();
6425 return !F.isDenormal() && !(F.isNaN() && F.isSignaling());
6431 // Constant fold canonicalize.
6432 SDValue SITargetLowering::performFCanonicalizeCombine(
6434 DAGCombinerInfo &DCI) const {
6435 SelectionDAG &DAG = DCI.DAG;
6436 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
6439 SDValue N0 = N->getOperand(0);
6440 EVT VT = N0.getValueType().getScalarType();
6441 auto ST = getSubtarget();
6443 if (((VT == MVT::f32 && ST->hasFP32Denormals()) ||
6444 (VT == MVT::f64 && ST->hasFP64Denormals()) ||
6445 (VT == MVT::f16 && ST->hasFP16Denormals())) &&
6446 DAG.isKnownNeverNaN(N0))
6449 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
6451 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) &&
6452 isCanonicalized(DAG, N0, ST))
6458 const APFloat &C = CFP->getValueAPF();
6460 // Flush denormals to 0 if not enabled.
6461 if (C.isDenormal()) {
6462 EVT VT = N->getValueType(0);
6463 EVT SVT = VT.getScalarType();
6464 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
6465 return DAG.getConstantFP(0.0, SDLoc(N), VT);
6467 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
6468 return DAG.getConstantFP(0.0, SDLoc(N), VT);
6470 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
6471 return DAG.getConstantFP(0.0, SDLoc(N), VT);
6475 EVT VT = N->getValueType(0);
6476 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
6477 if (C.isSignaling()) {
6478 // Quiet a signaling NaN.
6479 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6482 // Make sure it is the canonical NaN bitpattern.
6484 // TODO: Can we use -1 as the canonical NaN value since it's an inline
6486 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
6487 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6490 return N->getOperand(0);
6493 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
6496 return AMDGPUISD::FMAX3;
6498 return AMDGPUISD::SMAX3;
6500 return AMDGPUISD::UMAX3;
6502 return AMDGPUISD::FMIN3;
6504 return AMDGPUISD::SMIN3;
6506 return AMDGPUISD::UMIN3;
6508 llvm_unreachable("Not a min/max opcode");
6512 SDValue SITargetLowering::performIntMed3ImmCombine(
6513 SelectionDAG &DAG, const SDLoc &SL,
6514 SDValue Op0, SDValue Op1, bool Signed) const {
6515 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
6519 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
6524 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
6527 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
6531 EVT VT = K0->getValueType(0);
6532 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
6533 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
6534 return DAG.getNode(Med3Opc, SL, VT,
6535 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
6538 // If there isn't a 16-bit med3 operation, convert to 32-bit.
6540 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6542 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
6543 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
6544 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
6546 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
6547 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
6550 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
6551 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
6554 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
6555 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
6562 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
6565 SDValue Op1) const {
6566 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
6570 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
6574 // Ordered >= (although NaN inputs should have folded away by now).
6575 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
6576 if (Cmp == APFloat::cmpGreaterThan)
6579 // TODO: Check IEEE bit enabled?
6580 EVT VT = Op0.getValueType();
6581 if (Subtarget->enableDX10Clamp()) {
6582 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
6583 // hardware fmed3 behavior converting to a min.
6584 // FIXME: Should this be allowing -0.0?
6585 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
6586 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
6589 // med3 for f16 is only available on gfx9+, and not available for v2f16.
6590 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
6591 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
6592 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
6593 // then give the other result, which is different from med3 with a NaN
6595 SDValue Var = Op0.getOperand(0);
6596 if (!isKnownNeverSNan(DAG, Var))
6599 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
6600 Var, SDValue(K0, 0), SDValue(K1, 0));
6606 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
6607 DAGCombinerInfo &DCI) const {
6608 SelectionDAG &DAG = DCI.DAG;
6610 EVT VT = N->getValueType(0);
6611 unsigned Opc = N->getOpcode();
6612 SDValue Op0 = N->getOperand(0);
6613 SDValue Op1 = N->getOperand(1);
6615 // Only do this if the inner op has one use since this will just increases
6616 // register pressure for no benefit.
6619 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
6621 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
6622 // max(max(a, b), c) -> max3(a, b, c)
6623 // min(min(a, b), c) -> min3(a, b, c)
6624 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
6626 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
6635 // max(a, max(b, c)) -> max3(a, b, c)
6636 // min(a, min(b, c)) -> min3(a, b, c)
6637 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
6639 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
6648 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
6649 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
6650 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
6654 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
6655 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
6659 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
6660 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
6661 (Opc == AMDGPUISD::FMIN_LEGACY &&
6662 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
6663 (VT == MVT::f32 || VT == MVT::f64 ||
6664 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
6665 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
6667 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
6674 static bool isClampZeroToOne(SDValue A, SDValue B) {
6675 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
6676 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
6677 // FIXME: Should this be allowing -0.0?
6678 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
6679 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
6686 // FIXME: Should only worry about snans for version with chain.
6687 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
6688 DAGCombinerInfo &DCI) const {
6689 EVT VT = N->getValueType(0);
6690 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
6691 // NaNs. With a NaN input, the order of the operands may change the result.
6693 SelectionDAG &DAG = DCI.DAG;
6696 SDValue Src0 = N->getOperand(0);
6697 SDValue Src1 = N->getOperand(1);
6698 SDValue Src2 = N->getOperand(2);
6700 if (isClampZeroToOne(Src0, Src1)) {
6701 // const_a, const_b, x -> clamp is safe in all cases including signaling
6703 // FIXME: Should this be allowing -0.0?
6704 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
6707 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
6708 // handling no dx10-clamp?
6709 if (Subtarget->enableDX10Clamp()) {
6710 // If NaNs is clamped to 0, we are free to reorder the inputs.
6712 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6713 std::swap(Src0, Src1);
6715 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
6716 std::swap(Src1, Src2);
6718 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6719 std::swap(Src0, Src1);
6721 if (isClampZeroToOne(Src1, Src2))
6722 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
6728 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
6729 DAGCombinerInfo &DCI) const {
6730 SDValue Src0 = N->getOperand(0);
6731 SDValue Src1 = N->getOperand(1);
6732 if (Src0.isUndef() && Src1.isUndef())
6733 return DCI.DAG.getUNDEF(N->getValueType(0));
6737 SDValue SITargetLowering::performExtractVectorEltCombine(
6738 SDNode *N, DAGCombinerInfo &DCI) const {
6739 SDValue Vec = N->getOperand(0);
6741 SelectionDAG &DAG = DCI.DAG;
6742 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) {
6744 EVT EltVT = N->getValueType(0);
6745 SDValue Idx = N->getOperand(1);
6746 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6747 Vec.getOperand(0), Idx);
6748 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt);
6754 static bool convertBuildVectorCastElt(SelectionDAG &DAG,
6755 SDValue &Lo, SDValue &Hi) {
6756 if (Hi.getOpcode() == ISD::BITCAST &&
6757 Hi.getOperand(0).getValueType() == MVT::f16 &&
6758 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) {
6759 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo);
6760 Hi = Hi.getOperand(0);
6767 SDValue SITargetLowering::performBuildVectorCombine(
6768 SDNode *N, DAGCombinerInfo &DCI) const {
6771 if (!isTypeLegal(MVT::v2i16))
6773 SelectionDAG &DAG = DCI.DAG;
6774 EVT VT = N->getValueType(0);
6776 if (VT == MVT::v2i16) {
6777 SDValue Lo = N->getOperand(0);
6778 SDValue Hi = N->getOperand(1);
6780 // v2i16 build_vector (const|undef), (bitcast f16:$x)
6781 // -> bitcast (v2f16 build_vector const|undef, $x
6782 if (convertBuildVectorCastElt(DAG, Lo, Hi)) {
6783 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi });
6784 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6787 if (convertBuildVectorCastElt(DAG, Hi, Lo)) {
6788 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo });
6789 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6796 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
6798 const SDNode *N1) const {
6799 EVT VT = N0->getValueType(0);
6801 // Only do this if we are not trying to support denormals. v_mad_f32 does not
6802 // support denormals ever.
6803 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
6804 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
6807 const TargetOptions &Options = DAG.getTarget().Options;
6808 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
6809 (N0->getFlags().hasUnsafeAlgebra() &&
6810 N1->getFlags().hasUnsafeAlgebra())) &&
6811 isFMAFasterThanFMulAndFAdd(VT)) {
6818 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
6820 SDValue N0, SDValue N1, SDValue N2,
6822 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
6823 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
6824 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
6825 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
6828 SDValue SITargetLowering::performAddCombine(SDNode *N,
6829 DAGCombinerInfo &DCI) const {
6830 SelectionDAG &DAG = DCI.DAG;
6831 EVT VT = N->getValueType(0);
6833 SDValue LHS = N->getOperand(0);
6834 SDValue RHS = N->getOperand(1);
6836 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
6837 && Subtarget->hasMad64_32() &&
6838 !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
6839 VT.getScalarSizeInBits() <= 64) {
6840 if (LHS.getOpcode() != ISD::MUL)
6841 std::swap(LHS, RHS);
6843 SDValue MulLHS = LHS.getOperand(0);
6844 SDValue MulRHS = LHS.getOperand(1);
6845 SDValue AddRHS = RHS;
6847 // TODO: Maybe restrict if SGPR inputs.
6848 if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
6849 numBitsUnsigned(MulRHS, DAG) <= 32) {
6850 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
6851 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
6852 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
6853 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
6856 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
6857 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
6858 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
6859 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
6860 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
6869 // add x, zext (setcc) => addcarry x, 0, setcc
6870 // add x, sext (setcc) => subcarry x, 0, setcc
6871 unsigned Opc = LHS.getOpcode();
6872 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
6873 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
6874 std::swap(RHS, LHS);
6876 Opc = RHS.getOpcode();
6879 case ISD::ZERO_EXTEND:
6880 case ISD::SIGN_EXTEND:
6881 case ISD::ANY_EXTEND: {
6882 auto Cond = RHS.getOperand(0);
6883 if (!isBoolSGPR(Cond))
6885 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
6886 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
6887 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
6888 return DAG.getNode(Opc, SL, VTList, Args);
6890 case ISD::ADDCARRY: {
6891 // add x, (addcarry y, 0, cc) => addcarry x, y, cc
6892 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6893 if (!C || C->getZExtValue() != 0) break;
6894 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
6895 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
6901 SDValue SITargetLowering::performSubCombine(SDNode *N,
6902 DAGCombinerInfo &DCI) const {
6903 SelectionDAG &DAG = DCI.DAG;
6904 EVT VT = N->getValueType(0);
6910 SDValue LHS = N->getOperand(0);
6911 SDValue RHS = N->getOperand(1);
6913 unsigned Opc = LHS.getOpcode();
6914 if (Opc != ISD::SUBCARRY)
6915 std::swap(RHS, LHS);
6917 if (LHS.getOpcode() == ISD::SUBCARRY) {
6918 // sub (subcarry x, 0, cc), y => subcarry x, y, cc
6919 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6920 if (!C || C->getZExtValue() != 0)
6922 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
6923 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
6928 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
6929 DAGCombinerInfo &DCI) const {
6931 if (N->getValueType(0) != MVT::i32)
6934 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6935 if (!C || C->getZExtValue() != 0)
6938 SelectionDAG &DAG = DCI.DAG;
6939 SDValue LHS = N->getOperand(0);
6941 // addcarry (add x, y), 0, cc => addcarry x, y, cc
6942 // subcarry (sub x, y), 0, cc => subcarry x, y, cc
6943 unsigned LHSOpc = LHS.getOpcode();
6944 unsigned Opc = N->getOpcode();
6945 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
6946 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
6947 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
6948 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
6953 SDValue SITargetLowering::performFAddCombine(SDNode *N,
6954 DAGCombinerInfo &DCI) const {
6955 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6958 SelectionDAG &DAG = DCI.DAG;
6959 EVT VT = N->getValueType(0);
6962 SDValue LHS = N->getOperand(0);
6963 SDValue RHS = N->getOperand(1);
6965 // These should really be instruction patterns, but writing patterns with
6966 // source modiifiers is a pain.
6968 // fadd (fadd (a, a), b) -> mad 2.0, a, b
6969 if (LHS.getOpcode() == ISD::FADD) {
6970 SDValue A = LHS.getOperand(0);
6971 if (A == LHS.getOperand(1)) {
6972 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
6974 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6975 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
6980 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
6981 if (RHS.getOpcode() == ISD::FADD) {
6982 SDValue A = RHS.getOperand(0);
6983 if (A == RHS.getOperand(1)) {
6984 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
6986 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6987 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
6995 SDValue SITargetLowering::performFSubCombine(SDNode *N,
6996 DAGCombinerInfo &DCI) const {
6997 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7000 SelectionDAG &DAG = DCI.DAG;
7002 EVT VT = N->getValueType(0);
7003 assert(!VT.isVector());
7005 // Try to get the fneg to fold into the source modifier. This undoes generic
7006 // DAG combines and folds them into the mad.
7008 // Only do this if we are not trying to support denormals. v_mad_f32 does
7009 // not support denormals ever.
7010 SDValue LHS = N->getOperand(0);
7011 SDValue RHS = N->getOperand(1);
7012 if (LHS.getOpcode() == ISD::FADD) {
7013 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
7014 SDValue A = LHS.getOperand(0);
7015 if (A == LHS.getOperand(1)) {
7016 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7018 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7019 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7021 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
7026 if (RHS.getOpcode() == ISD::FADD) {
7027 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
7029 SDValue A = RHS.getOperand(0);
7030 if (A == RHS.getOperand(1)) {
7031 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7033 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
7034 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
7042 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
7043 DAGCombinerInfo &DCI) const {
7044 SelectionDAG &DAG = DCI.DAG;
7047 SDValue LHS = N->getOperand(0);
7048 SDValue RHS = N->getOperand(1);
7049 EVT VT = LHS.getValueType();
7050 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
7052 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
7054 CRHS = dyn_cast<ConstantSDNode>(LHS);
7056 std::swap(LHS, RHS);
7057 CC = getSetCCSwappedOperands(CC);
7061 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
7062 isBoolSGPR(LHS.getOperand(0))) {
7063 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
7064 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
7065 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
7066 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
7067 if ((CRHS->isAllOnesValue() &&
7068 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
7069 (CRHS->isNullValue() &&
7070 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
7071 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7072 DAG.getConstant(-1, SL, MVT::i1));
7073 if ((CRHS->isAllOnesValue() &&
7074 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
7075 (CRHS->isNullValue() &&
7076 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
7077 return LHS.getOperand(0);
7080 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
7084 // Match isinf pattern
7085 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
7086 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
7087 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
7091 const APFloat &APF = CRHS->getValueAPF();
7092 if (APF.isInfinity() && !APF.isNegative()) {
7093 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
7094 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
7095 DAG.getConstant(Mask, SL, MVT::i32));
7102 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
7103 DAGCombinerInfo &DCI) const {
7104 SelectionDAG &DAG = DCI.DAG;
7106 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
7108 SDValue Src = N->getOperand(0);
7109 SDValue Srl = N->getOperand(0);
7110 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
7111 Srl = Srl.getOperand(0);
7113 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
7114 if (Srl.getOpcode() == ISD::SRL) {
7115 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
7116 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
7117 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
7119 if (const ConstantSDNode *C =
7120 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
7121 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
7124 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
7125 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
7126 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
7132 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
7135 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
7136 !DCI.isBeforeLegalizeOps());
7137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7138 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
7139 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
7140 DCI.CommitTargetLoweringOpt(TLO);
7146 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
7147 DAGCombinerInfo &DCI) const {
7148 switch (N->getOpcode()) {
7150 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7152 return performAddCombine(N, DCI);
7154 return performSubCombine(N, DCI);
7157 return performAddCarrySubCarryCombine(N, DCI);
7159 return performFAddCombine(N, DCI);
7161 return performFSubCombine(N, DCI);
7163 return performSetCCCombine(N, DCI);
7170 case AMDGPUISD::FMIN_LEGACY:
7171 case AMDGPUISD::FMAX_LEGACY: {
7172 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
7173 getTargetMachine().getOptLevel() > CodeGenOpt::None)
7174 return performMinMaxCombine(N, DCI);
7179 case ISD::ATOMIC_LOAD:
7180 case ISD::ATOMIC_STORE:
7181 case ISD::ATOMIC_CMP_SWAP:
7182 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
7183 case ISD::ATOMIC_SWAP:
7184 case ISD::ATOMIC_LOAD_ADD:
7185 case ISD::ATOMIC_LOAD_SUB:
7186 case ISD::ATOMIC_LOAD_AND:
7187 case ISD::ATOMIC_LOAD_OR:
7188 case ISD::ATOMIC_LOAD_XOR:
7189 case ISD::ATOMIC_LOAD_NAND:
7190 case ISD::ATOMIC_LOAD_MIN:
7191 case ISD::ATOMIC_LOAD_MAX:
7192 case ISD::ATOMIC_LOAD_UMIN:
7193 case ISD::ATOMIC_LOAD_UMAX:
7194 case AMDGPUISD::ATOMIC_INC:
7195 case AMDGPUISD::ATOMIC_DEC:
7196 case AMDGPUISD::ATOMIC_LOAD_FADD:
7197 case AMDGPUISD::ATOMIC_LOAD_FMIN:
7198 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
7199 if (DCI.isBeforeLegalize())
7201 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
7203 return performAndCombine(N, DCI);
7205 return performOrCombine(N, DCI);
7207 return performXorCombine(N, DCI);
7208 case ISD::ZERO_EXTEND:
7209 return performZeroExtendCombine(N, DCI);
7210 case AMDGPUISD::FP_CLASS:
7211 return performClassCombine(N, DCI);
7212 case ISD::FCANONICALIZE:
7213 return performFCanonicalizeCombine(N, DCI);
7214 case AMDGPUISD::FRACT:
7215 case AMDGPUISD::RCP:
7216 case AMDGPUISD::RSQ:
7217 case AMDGPUISD::RCP_LEGACY:
7218 case AMDGPUISD::RSQ_LEGACY:
7219 case AMDGPUISD::RSQ_CLAMP:
7220 case AMDGPUISD::LDEXP: {
7221 SDValue Src = N->getOperand(0);
7226 case ISD::SINT_TO_FP:
7227 case ISD::UINT_TO_FP:
7228 return performUCharToFloatCombine(N, DCI);
7229 case AMDGPUISD::CVT_F32_UBYTE0:
7230 case AMDGPUISD::CVT_F32_UBYTE1:
7231 case AMDGPUISD::CVT_F32_UBYTE2:
7232 case AMDGPUISD::CVT_F32_UBYTE3:
7233 return performCvtF32UByteNCombine(N, DCI);
7234 case AMDGPUISD::FMED3:
7235 return performFMed3Combine(N, DCI);
7236 case AMDGPUISD::CVT_PKRTZ_F16_F32:
7237 return performCvtPkRTZCombine(N, DCI);
7238 case ISD::SCALAR_TO_VECTOR: {
7239 SelectionDAG &DAG = DCI.DAG;
7240 EVT VT = N->getValueType(0);
7242 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
7243 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
7245 SDValue Src = N->getOperand(0);
7246 EVT EltVT = Src.getValueType();
7247 if (EltVT == MVT::f16)
7248 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
7250 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
7251 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
7256 case ISD::EXTRACT_VECTOR_ELT:
7257 return performExtractVectorEltCombine(N, DCI);
7258 case ISD::BUILD_VECTOR:
7259 return performBuildVectorCombine(N, DCI);
7261 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7264 /// \brief Helper function for adjustWritemask
7265 static unsigned SubIdx2Lane(unsigned Idx) {
7268 case AMDGPU::sub0: return 0;
7269 case AMDGPU::sub1: return 1;
7270 case AMDGPU::sub2: return 2;
7271 case AMDGPU::sub3: return 3;
7275 /// \brief Adjust the writemask of MIMG instructions
7276 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
7277 SelectionDAG &DAG) const {
7278 SDNode *Users[4] = { nullptr };
7280 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
7281 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
7282 unsigned NewDmask = 0;
7283 bool HasChain = Node->getNumValues() > 1;
7285 if (OldDmask == 0) {
7286 // These are folded out, but on the chance it happens don't assert.
7290 // Try to figure out the used register components
7291 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
7294 // Don't look at users of the chain.
7295 if (I.getUse().getResNo() != 0)
7298 // Abort if we can't understand the usage
7299 if (!I->isMachineOpcode() ||
7300 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
7303 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
7304 // Note that subregs are packed, i.e. Lane==0 is the first bit set
7305 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
7307 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
7309 // Set which texture component corresponds to the lane.
7311 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
7312 Comp = countTrailingZeros(Dmask);
7313 Dmask &= ~(1 << Comp);
7316 // Abort if we have more than one user per component
7321 NewDmask |= 1 << Comp;
7324 // Abort if there's no change
7325 if (NewDmask == OldDmask)
7328 unsigned BitsSet = countPopulation(NewDmask);
7330 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7331 int NewOpcode = AMDGPU::getMaskedMIMGOp(*TII,
7332 Node->getMachineOpcode(), BitsSet);
7333 assert(NewOpcode != -1 &&
7334 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
7335 "failed to find equivalent MIMG op");
7337 // Adjust the writemask in the node
7338 SmallVector<SDValue, 12> Ops;
7339 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
7340 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
7341 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
7343 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
7345 MVT ResultVT = BitsSet == 1 ?
7346 SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet);
7347 SDVTList NewVTList = HasChain ?
7348 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
7351 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
7356 NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end());
7357 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
7361 assert(Node->hasNUsesOfValue(1, 0));
7362 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
7363 SDLoc(Node), Users[Lane]->getValueType(0),
7364 SDValue(NewNode, 0));
7365 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
7369 // Update the users of the node with the new indices
7370 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
7371 SDNode *User = Users[i];
7375 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
7376 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
7380 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
7381 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
7382 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
7386 DAG.RemoveDeadNode(Node);
7390 static bool isFrameIndexOp(SDValue Op) {
7391 if (Op.getOpcode() == ISD::AssertZext)
7392 Op = Op.getOperand(0);
7394 return isa<FrameIndexSDNode>(Op);
7397 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
7398 /// with frame index operands.
7399 /// LLVM assumes that inputs are to these instructions are registers.
7400 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
7401 SelectionDAG &DAG) const {
7402 if (Node->getOpcode() == ISD::CopyToReg) {
7403 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
7404 SDValue SrcVal = Node->getOperand(2);
7406 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
7407 // to try understanding copies to physical registers.
7408 if (SrcVal.getValueType() == MVT::i1 &&
7409 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
7411 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
7412 SDValue VReg = DAG.getRegister(
7413 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
7415 SDNode *Glued = Node->getGluedNode();
7417 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
7418 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
7420 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
7421 VReg, ToVReg.getValue(1));
7422 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
7423 DAG.RemoveDeadNode(Node);
7424 return ToResultReg.getNode();
7428 SmallVector<SDValue, 8> Ops;
7429 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
7430 if (!isFrameIndexOp(Node->getOperand(i))) {
7431 Ops.push_back(Node->getOperand(i));
7436 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
7437 Node->getOperand(i).getValueType(),
7438 Node->getOperand(i)), 0));
7441 return DAG.UpdateNodeOperands(Node, Ops);
7444 /// \brief Fold the instructions after selecting them.
7445 /// Returns null if users were already updated.
7446 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
7447 SelectionDAG &DAG) const {
7448 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7449 unsigned Opcode = Node->getMachineOpcode();
7451 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
7452 !TII->isGather4(Opcode) && !TII->isD16(Opcode)) {
7453 return adjustWritemask(Node, DAG);
7456 if (Opcode == AMDGPU::INSERT_SUBREG ||
7457 Opcode == AMDGPU::REG_SEQUENCE) {
7458 legalizeTargetIndependentNode(Node, DAG);
7463 case AMDGPU::V_DIV_SCALE_F32:
7464 case AMDGPU::V_DIV_SCALE_F64: {
7465 // Satisfy the operand register constraint when one of the inputs is
7466 // undefined. Ordinarily each undef value will have its own implicit_def of
7467 // a vreg, so force these to use a single register.
7468 SDValue Src0 = Node->getOperand(0);
7469 SDValue Src1 = Node->getOperand(1);
7470 SDValue Src2 = Node->getOperand(2);
7472 if ((Src0.isMachineOpcode() &&
7473 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
7474 (Src0 == Src1 || Src0 == Src2))
7477 MVT VT = Src0.getValueType().getSimpleVT();
7478 const TargetRegisterClass *RC = getRegClassFor(VT);
7480 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
7481 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
7483 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
7484 UndefReg, Src0, SDValue());
7486 // src0 must be the same register as src1 or src2, even if the value is
7487 // undefined, so make sure we don't violate this constraint.
7488 if (Src0.isMachineOpcode() &&
7489 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
7490 if (Src1.isMachineOpcode() &&
7491 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
7493 else if (Src2.isMachineOpcode() &&
7494 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
7497 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
7504 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
7505 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
7506 Ops.push_back(Node->getOperand(I));
7508 Ops.push_back(ImpDef.getValue(1));
7509 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
7518 /// \brief Assign the register class depending on the number of
7519 /// bits set in the writemask
7520 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
7521 SDNode *Node) const {
7522 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7524 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7526 if (TII->isVOP3(MI.getOpcode())) {
7527 // Make sure constant bus requirements are respected.
7528 TII->legalizeOperandsVOP3(MRI, MI);
7532 // Replace unused atomics with the no return version.
7533 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
7534 if (NoRetAtomicOp != -1) {
7535 if (!Node->hasAnyUseOfValue(0)) {
7536 MI.setDesc(TII->get(NoRetAtomicOp));
7537 MI.RemoveOperand(0);
7541 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
7542 // instruction, because the return type of these instructions is a vec2 of
7543 // the memory type, so it can be tied to the input operand.
7544 // This means these instructions always have a use, so we need to add a
7545 // special case to check if the atomic has only one extract_subreg use,
7546 // which itself has no uses.
7547 if ((Node->hasNUsesOfValue(1, 0) &&
7548 Node->use_begin()->isMachineOpcode() &&
7549 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
7550 !Node->use_begin()->hasAnyUseOfValue(0))) {
7551 unsigned Def = MI.getOperand(0).getReg();
7553 // Change this into a noret atomic.
7554 MI.setDesc(TII->get(NoRetAtomicOp));
7555 MI.RemoveOperand(0);
7557 // If we only remove the def operand from the atomic instruction, the
7558 // extract_subreg will be left with a use of a vreg without a def.
7559 // So we need to insert an implicit_def to avoid machine verifier
7561 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
7562 TII->get(AMDGPU::IMPLICIT_DEF), Def);
7568 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
7570 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
7571 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
7574 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
7576 SDValue Ptr) const {
7577 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7579 // Build the half of the subregister with the constants before building the
7580 // full 128-bit register. If we are building multiple resource descriptors,
7581 // this will allow CSEing of the 2-component register.
7582 const SDValue Ops0[] = {
7583 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
7584 buildSMovImm32(DAG, DL, 0),
7585 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
7586 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
7587 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
7590 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
7591 MVT::v2i32, Ops0), 0);
7593 // Combine the constants and the pointer.
7594 const SDValue Ops1[] = {
7595 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
7597 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
7599 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
7602 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
7605 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
7606 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
7607 /// of the resource descriptor) to create an offset, which is added to
7608 /// the resource pointer.
7609 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
7610 SDValue Ptr, uint32_t RsrcDword1,
7611 uint64_t RsrcDword2And3) const {
7612 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
7613 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
7615 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
7616 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
7620 SDValue DataLo = buildSMovImm32(DAG, DL,
7621 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
7622 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
7624 const SDValue Ops[] = {
7625 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
7627 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
7629 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
7631 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
7633 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
7636 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
7639 //===----------------------------------------------------------------------===//
7640 // SI Inline Assembly Support
7641 //===----------------------------------------------------------------------===//
7643 std::pair<unsigned, const TargetRegisterClass *>
7644 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
7645 StringRef Constraint,
7647 if (!isTypeLegal(VT))
7648 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7650 if (Constraint.size() == 1) {
7651 switch (Constraint[0]) {
7654 switch (VT.getSizeInBits()) {
7656 return std::make_pair(0U, nullptr);
7659 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
7661 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
7663 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
7665 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
7667 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
7671 switch (VT.getSizeInBits()) {
7673 return std::make_pair(0U, nullptr);
7676 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
7678 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
7680 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
7682 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
7684 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
7686 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
7691 if (Constraint.size() > 1) {
7692 const TargetRegisterClass *RC = nullptr;
7693 if (Constraint[1] == 'v') {
7694 RC = &AMDGPU::VGPR_32RegClass;
7695 } else if (Constraint[1] == 's') {
7696 RC = &AMDGPU::SGPR_32RegClass;
7701 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
7702 if (!Failed && Idx < RC->getNumRegs())
7703 return std::make_pair(RC->getRegister(Idx), RC);
7706 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7709 SITargetLowering::ConstraintType
7710 SITargetLowering::getConstraintType(StringRef Constraint) const {
7711 if (Constraint.size() == 1) {
7712 switch (Constraint[0]) {
7716 return C_RegisterClass;
7719 return TargetLowering::getConstraintType(Constraint);
7722 // Figure out which registers should be reserved for stack access. Only after
7723 // the function is legalized do we know all of the non-spill stack objects or if
7724 // calls are present.
7725 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
7726 MachineRegisterInfo &MRI = MF.getRegInfo();
7727 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
7728 const MachineFrameInfo &MFI = MF.getFrameInfo();
7729 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
7730 const SIRegisterInfo *TRI = ST.getRegisterInfo();
7732 if (Info->isEntryFunction()) {
7733 // Callable functions have fixed registers used for stack access.
7734 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
7737 // We have to assume the SP is needed in case there are calls in the function
7738 // during lowering. Calls are only detected after the function is
7739 // lowered. We're about to reserve registers, so don't bother using it if we
7740 // aren't really going to use it.
7741 bool NeedSP = !Info->isEntryFunction() ||
7742 MFI.hasVarSizedObjects() ||
7746 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
7747 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
7749 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
7750 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
7751 Info->getStackPtrOffsetReg()));
7752 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
7755 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
7756 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
7757 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
7758 Info->getScratchWaveOffsetReg());
7760 TargetLoweringBase::finalizeLowering(MF);
7763 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
7765 const APInt &DemandedElts,
7766 const SelectionDAG &DAG,
7767 unsigned Depth) const {
7768 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
7771 if (getSubtarget()->enableHugePrivateBuffer())
7774 // Technically it may be possible to have a dispatch with a single workitem
7775 // that uses the full private memory size, but that's not really useful. We
7776 // can't use vaddr in MUBUF instructions if we don't know the address
7777 // calculation won't overflow, so assume the sign bit is never set.
7778 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);