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/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/CallingConvLower.h"
40 #include "llvm/CodeGen/DAGCombine.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/MachineValueType.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/ValueTypes.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/DiagnosticInfo.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/KnownBits.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Target/TargetCallingConv.h"
74 #include "llvm/Target/TargetOptions.h"
75 #include "llvm/Target/TargetRegisterInfo.h"
86 static cl::opt<bool> EnableVGPRIndexMode(
87 "amdgpu-vgpr-index-mode",
88 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
91 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
92 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
93 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
94 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
95 return AMDGPU::SGPR0 + Reg;
98 llvm_unreachable("Cannot allocate sgpr");
101 SITargetLowering::SITargetLowering(const TargetMachine &TM,
102 const SISubtarget &STI)
103 : AMDGPUTargetLowering(TM, STI) {
104 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
105 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
107 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
108 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
110 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
111 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
112 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
114 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
115 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
117 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
118 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
120 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
121 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
123 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
124 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
126 if (Subtarget->has16BitInsts()) {
127 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
128 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
131 if (Subtarget->hasVOP3PInsts()) {
132 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
133 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
136 computeRegisterProperties(STI.getRegisterInfo());
138 // We need to custom lower vector stores from local memory
139 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
140 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
141 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
142 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
143 setOperationAction(ISD::LOAD, MVT::i1, Custom);
145 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
146 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
147 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
148 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
149 setOperationAction(ISD::STORE, MVT::i1, Custom);
151 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
152 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
153 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
154 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
155 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
156 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
157 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
158 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
159 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
160 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
162 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
163 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
164 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
166 setOperationAction(ISD::SELECT, MVT::i1, Promote);
167 setOperationAction(ISD::SELECT, MVT::i64, Custom);
168 setOperationAction(ISD::SELECT, MVT::f64, Promote);
169 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
171 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
172 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
173 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
174 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
175 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
177 setOperationAction(ISD::SETCC, MVT::i1, Promote);
178 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
179 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
180 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
182 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
183 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
185 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
186 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
187 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
188 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
190 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
193 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
194 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
195 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
196 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
198 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
200 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
201 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
202 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
204 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
205 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
206 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
207 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
208 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
209 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
211 setOperationAction(ISD::UADDO, MVT::i32, Legal);
212 setOperationAction(ISD::USUBO, MVT::i32, Legal);
214 // We only support LOAD/STORE and vector manipulation ops for vectors
215 // with > 4 elements.
216 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
217 MVT::v2i64, MVT::v2f64}) {
218 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
222 case ISD::BUILD_VECTOR:
224 case ISD::EXTRACT_VECTOR_ELT:
225 case ISD::INSERT_VECTOR_ELT:
226 case ISD::INSERT_SUBVECTOR:
227 case ISD::EXTRACT_SUBVECTOR:
228 case ISD::SCALAR_TO_VECTOR:
230 case ISD::CONCAT_VECTORS:
231 setOperationAction(Op, VT, Custom);
234 setOperationAction(Op, VT, Expand);
240 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
241 // is expanded to avoid having two separate loops in case the index is a VGPR.
243 // Most operations are naturally 32-bit vector operations. We only support
244 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
245 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
246 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
247 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
249 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
250 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
252 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
253 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
255 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
256 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
259 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
260 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
261 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
262 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
264 // Avoid stack access for these.
265 // TODO: Generalize to more vector types.
266 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
267 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
268 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
269 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
271 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
272 // and output demarshalling
273 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
274 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
276 // We can't return success/failure, only the old value,
277 // let LLVM add the comparison
278 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
279 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
281 if (getSubtarget()->hasFlatAddressSpace()) {
282 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
283 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
286 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
287 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
289 // On SI this is s_memtime and s_memrealtime on VI.
290 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
291 setOperationAction(ISD::TRAP, MVT::Other, Custom);
292 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
294 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
295 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
297 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
298 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
299 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
300 setOperationAction(ISD::FRINT, MVT::f64, Legal);
303 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
305 setOperationAction(ISD::FSIN, MVT::f32, Custom);
306 setOperationAction(ISD::FCOS, MVT::f32, Custom);
307 setOperationAction(ISD::FDIV, MVT::f32, Custom);
308 setOperationAction(ISD::FDIV, MVT::f64, Custom);
310 if (Subtarget->has16BitInsts()) {
311 setOperationAction(ISD::Constant, MVT::i16, Legal);
313 setOperationAction(ISD::SMIN, MVT::i16, Legal);
314 setOperationAction(ISD::SMAX, MVT::i16, Legal);
316 setOperationAction(ISD::UMIN, MVT::i16, Legal);
317 setOperationAction(ISD::UMAX, MVT::i16, Legal);
319 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
320 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
322 setOperationAction(ISD::ROTR, MVT::i16, Promote);
323 setOperationAction(ISD::ROTL, MVT::i16, Promote);
325 setOperationAction(ISD::SDIV, MVT::i16, Promote);
326 setOperationAction(ISD::UDIV, MVT::i16, Promote);
327 setOperationAction(ISD::SREM, MVT::i16, Promote);
328 setOperationAction(ISD::UREM, MVT::i16, Promote);
330 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
331 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
333 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
334 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
335 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
336 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
338 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
340 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
342 setOperationAction(ISD::LOAD, MVT::i16, Custom);
344 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
346 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
347 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
348 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
349 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
351 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
352 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
353 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
354 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
356 // F16 - Constant Actions.
357 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
359 // F16 - Load/Store Actions.
360 setOperationAction(ISD::LOAD, MVT::f16, Promote);
361 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
362 setOperationAction(ISD::STORE, MVT::f16, Promote);
363 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
365 // F16 - VOP1 Actions.
366 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
367 setOperationAction(ISD::FCOS, MVT::f16, Promote);
368 setOperationAction(ISD::FSIN, MVT::f16, Promote);
369 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
370 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
371 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
372 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
373 setOperationAction(ISD::FROUND, MVT::f16, Custom);
375 // F16 - VOP2 Actions.
376 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
377 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
378 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
379 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
380 setOperationAction(ISD::FDIV, MVT::f16, Custom);
382 // F16 - VOP3 Actions.
383 setOperationAction(ISD::FMA, MVT::f16, Legal);
384 if (!Subtarget->hasFP16Denormals())
385 setOperationAction(ISD::FMAD, MVT::f16, Legal);
388 if (Subtarget->hasVOP3PInsts()) {
389 for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
390 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
394 case ISD::BUILD_VECTOR:
396 case ISD::EXTRACT_VECTOR_ELT:
397 case ISD::INSERT_VECTOR_ELT:
398 case ISD::INSERT_SUBVECTOR:
399 case ISD::EXTRACT_SUBVECTOR:
400 case ISD::SCALAR_TO_VECTOR:
402 case ISD::CONCAT_VECTORS:
403 setOperationAction(Op, VT, Custom);
406 setOperationAction(Op, VT, Expand);
412 // XXX - Do these do anything? Vector constants turn into build_vector.
413 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
414 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
416 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
417 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
418 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
419 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
421 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
422 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
423 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
424 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
426 setOperationAction(ISD::AND, MVT::v2i16, Promote);
427 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
428 setOperationAction(ISD::OR, MVT::v2i16, Promote);
429 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
430 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
431 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
432 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
433 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
434 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
435 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
437 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
438 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
439 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
440 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
441 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
442 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
443 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
444 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
445 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
446 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
448 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
449 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
450 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
451 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
452 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
453 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
455 // This isn't really legal, but this avoids the legalizer unrolling it (and
456 // allows matching fneg (fabs x) patterns)
457 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
459 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
460 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
462 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
463 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
464 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
466 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
467 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
470 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
471 setOperationAction(ISD::SELECT, VT, Custom);
474 setTargetDAGCombine(ISD::FADD);
475 setTargetDAGCombine(ISD::FSUB);
476 setTargetDAGCombine(ISD::FMINNUM);
477 setTargetDAGCombine(ISD::FMAXNUM);
478 setTargetDAGCombine(ISD::SMIN);
479 setTargetDAGCombine(ISD::SMAX);
480 setTargetDAGCombine(ISD::UMIN);
481 setTargetDAGCombine(ISD::UMAX);
482 setTargetDAGCombine(ISD::SETCC);
483 setTargetDAGCombine(ISD::AND);
484 setTargetDAGCombine(ISD::OR);
485 setTargetDAGCombine(ISD::XOR);
486 setTargetDAGCombine(ISD::SINT_TO_FP);
487 setTargetDAGCombine(ISD::UINT_TO_FP);
488 setTargetDAGCombine(ISD::FCANONICALIZE);
489 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
490 setTargetDAGCombine(ISD::ZERO_EXTEND);
491 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
493 // All memory operations. Some folding on the pointer operand is done to help
494 // matching the constant offsets in the addressing modes.
495 setTargetDAGCombine(ISD::LOAD);
496 setTargetDAGCombine(ISD::STORE);
497 setTargetDAGCombine(ISD::ATOMIC_LOAD);
498 setTargetDAGCombine(ISD::ATOMIC_STORE);
499 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
500 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
501 setTargetDAGCombine(ISD::ATOMIC_SWAP);
502 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
503 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
504 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
505 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
506 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
507 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
508 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
509 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
510 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
511 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
513 setSchedulingPreference(Sched::RegPressure);
516 const SISubtarget *SITargetLowering::getSubtarget() const {
517 return static_cast<const SISubtarget *>(Subtarget);
520 //===----------------------------------------------------------------------===//
521 // TargetLowering queries
522 //===----------------------------------------------------------------------===//
524 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
526 // SI has some legal vector types, but no legal vector operations. Say no
527 // shuffles are legal in order to prefer scalarizing some vector operations.
531 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
533 unsigned IntrID) const {
535 case Intrinsic::amdgcn_atomic_inc:
536 case Intrinsic::amdgcn_atomic_dec: {
537 Info.opc = ISD::INTRINSIC_W_CHAIN;
538 Info.memVT = MVT::getVT(CI.getType());
539 Info.ptrVal = CI.getOperand(0);
542 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
543 Info.vol = !Vol || !Vol->isNullValue();
545 Info.writeMem = true;
553 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
554 SmallVectorImpl<Value*> &Ops,
555 Type *&AccessTy) const {
556 switch (II->getIntrinsicID()) {
557 case Intrinsic::amdgcn_atomic_inc:
558 case Intrinsic::amdgcn_atomic_dec: {
559 Value *Ptr = II->getArgOperand(0);
560 AccessTy = II->getType();
569 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
570 // Flat instructions do not have offsets, and only have the register
572 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
575 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
576 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
577 // additionally can do r + r + i with addr64. 32-bit has more addressing
578 // mode options. Depending on the resource constant, it can also do
579 // (i64 r0) + (i32 r1) * (i14 i).
581 // Private arrays end up using a scratch buffer most of the time, so also
582 // assume those use MUBUF instructions. Scratch loads / stores are currently
583 // implemented as mubuf instructions with offen bit set, so slightly
584 // different than the normal addr64.
585 if (!isUInt<12>(AM.BaseOffs))
588 // FIXME: Since we can split immediate into soffset and immediate offset,
589 // would it make sense to allow any immediate?
592 case 0: // r + i or just i, depending on HasBaseReg.
595 return true; // We have r + r or r + i.
602 // Allow 2 * r as r + r
603 // Or 2 * r + i is allowed as r + r + i.
605 default: // Don't allow n * r
610 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
611 const AddrMode &AM, Type *Ty,
613 // No global is ever allowed as a base.
617 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
618 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
619 // Assume the we will use FLAT for all global memory accesses
621 // FIXME: This assumption is currently wrong. On VI we still use
622 // MUBUF instructions for the r + i addressing mode. As currently
623 // implemented, the MUBUF instructions only work on buffer < 4GB.
624 // It may be possible to support > 4GB buffers with MUBUF instructions,
625 // by setting the stride value in the resource descriptor which would
626 // increase the size limit to (stride * 4GB). However, this is risky,
627 // because it has never been validated.
628 return isLegalFlatAddressingMode(AM);
631 return isLegalMUBUFAddressingMode(AM);
632 } else if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
633 // If the offset isn't a multiple of 4, it probably isn't going to be
634 // correctly aligned.
635 // FIXME: Can we get the real alignment here?
636 if (AM.BaseOffs % 4 != 0)
637 return isLegalMUBUFAddressingMode(AM);
639 // There are no SMRD extloads, so if we have to do a small type access we
640 // will use a MUBUF load.
641 // FIXME?: We also need to do this if unaligned, but we don't know the
643 if (DL.getTypeStoreSize(Ty) < 4)
644 return isLegalMUBUFAddressingMode(AM);
646 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
647 // SMRD instructions have an 8-bit, dword offset on SI.
648 if (!isUInt<8>(AM.BaseOffs / 4))
650 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
651 // On CI+, this can also be a 32-bit literal constant offset. If it fits
652 // in 8-bits, it can use a smaller encoding.
653 if (!isUInt<32>(AM.BaseOffs / 4))
655 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
656 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
657 if (!isUInt<20>(AM.BaseOffs))
660 llvm_unreachable("unhandled generation");
662 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
665 if (AM.Scale == 1 && AM.HasBaseReg)
670 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
671 return isLegalMUBUFAddressingMode(AM);
672 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
673 AS == AMDGPUASI.REGION_ADDRESS) {
674 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
676 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
677 // an 8-bit dword offset but we don't know the alignment here.
678 if (!isUInt<16>(AM.BaseOffs))
681 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
684 if (AM.Scale == 1 && AM.HasBaseReg)
688 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
689 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
690 // For an unknown address space, this usually means that this is for some
691 // reason being used for pure arithmetic, and not based on some addressing
692 // computation. We don't have instructions that compute pointers with any
693 // addressing modes, so treat them as having no offset like flat
695 return isLegalFlatAddressingMode(AM);
697 llvm_unreachable("unhandled address space");
701 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT) const {
702 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
703 return (MemVT.getSizeInBits() <= 4 * 32);
704 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
705 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
706 return (MemVT.getSizeInBits() <= MaxPrivateBits);
707 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
708 return (MemVT.getSizeInBits() <= 2 * 32);
713 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
716 bool *IsFast) const {
720 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
721 // which isn't a simple VT.
722 // Until MVT is extended to handle this, simply check for the size and
723 // rely on the condition below: allow accesses if the size is a multiple of 4.
724 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
725 VT.getStoreSize() > 16)) {
729 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
730 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
731 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
732 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
733 // with adjacent offsets.
734 bool AlignedBy4 = (Align % 4 == 0);
736 *IsFast = AlignedBy4;
741 // FIXME: We have to be conservative here and assume that flat operations
742 // will access scratch. If we had access to the IR function, then we
743 // could determine if any private memory was used in the function.
744 if (!Subtarget->hasUnalignedScratchAccess() &&
745 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
746 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
750 if (Subtarget->hasUnalignedBufferAccess()) {
751 // If we have an uniform constant load, it still requires using a slow
752 // buffer instruction if unaligned.
754 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ?
755 (Align % 4 == 0) : true;
761 // Smaller than dword value must be aligned.
762 if (VT.bitsLT(MVT::i32))
765 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
766 // byte-address are ignored, thus forcing Dword alignment.
767 // This applies to private, global, and constant memory.
771 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
774 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
775 unsigned SrcAlign, bool IsMemset,
778 MachineFunction &MF) const {
779 // FIXME: Should account for address space here.
781 // The default fallback uses the private pointer size as a guess for a type to
782 // use. Make sure we switch these to 64-bit accesses.
784 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
787 if (Size >= 8 && DstAlign >= 4)
794 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
795 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
796 AS == AMDGPUASI.FLAT_ADDRESS ||
797 AS == AMDGPUASI.CONSTANT_ADDRESS;
800 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
801 unsigned DestAS) const {
802 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
803 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
806 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
807 const MemSDNode *MemNode = cast<MemSDNode>(N);
808 const Value *Ptr = MemNode->getMemOperand()->getValue();
809 const Instruction *I = dyn_cast<Instruction>(Ptr);
810 return I && I->getMetadata("amdgpu.noclobber");
813 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
814 unsigned DestAS) const {
815 // Flat -> private/local is a simple truncate.
816 // Flat -> global is no-op
817 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
820 return isNoopAddrSpaceCast(SrcAS, DestAS);
823 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
824 const MemSDNode *MemNode = cast<MemSDNode>(N);
826 return AMDGPU::isUniformMMO(MemNode->getMemOperand());
829 TargetLoweringBase::LegalizeTypeAction
830 SITargetLowering::getPreferredVectorAction(EVT VT) const {
831 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
832 return TypeSplitVector;
834 return TargetLoweringBase::getPreferredVectorAction(VT);
837 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
839 // FIXME: Could be smarter if called for vector constants.
843 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
844 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
849 // These operations are done with 32-bit instructions anyway.
861 // SimplifySetCC uses this function to determine whether or not it should
862 // create setcc with i1 operands. We don't have instructions for i1 setcc.
863 if (VT == MVT::i1 && Op == ISD::SETCC)
866 return TargetLowering::isTypeDesirableForOp(Op, VT);
869 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
872 uint64_t Offset) const {
873 const DataLayout &DL = DAG.getDataLayout();
874 MachineFunction &MF = DAG.getMachineFunction();
875 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
876 unsigned InputPtrReg = TRI->getPreloadedValue(MF,
877 SIRegisterInfo::KERNARG_SEGMENT_PTR);
879 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
880 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
881 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
882 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
883 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
884 DAG.getConstant(Offset, SL, PtrVT));
887 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
888 const SDLoc &SL, SDValue Val,
890 const ISD::InputArg *Arg) const {
891 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
893 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
894 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
897 if (MemVT.isFloatingPoint())
898 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
900 Val = DAG.getSExtOrTrunc(Val, SL, VT);
902 Val = DAG.getZExtOrTrunc(Val, SL, VT);
907 SDValue SITargetLowering::lowerKernargMemParameter(
908 SelectionDAG &DAG, EVT VT, EVT MemVT,
909 const SDLoc &SL, SDValue Chain,
910 uint64_t Offset, bool Signed,
911 const ISD::InputArg *Arg) const {
912 const DataLayout &DL = DAG.getDataLayout();
913 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
914 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
915 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
917 unsigned Align = DL.getABITypeAlignment(Ty);
919 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
920 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
921 MachineMemOperand::MONonTemporal |
922 MachineMemOperand::MODereferenceable |
923 MachineMemOperand::MOInvariant);
925 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
926 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
929 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
930 const SDLoc &SL, SDValue Chain,
931 const ISD::InputArg &Arg) const {
932 MachineFunction &MF = DAG.getMachineFunction();
933 MachineFrameInfo &MFI = MF.getFrameInfo();
935 if (Arg.Flags.isByVal()) {
936 unsigned Size = Arg.Flags.getByValSize();
937 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
938 return DAG.getFrameIndex(FrameIdx, MVT::i32);
941 unsigned ArgOffset = VA.getLocMemOffset();
942 unsigned ArgSize = VA.getValVT().getStoreSize();
944 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
946 // Create load nodes to retrieve arguments from the stack.
947 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
950 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
951 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
952 MVT MemVT = VA.getValVT();
954 switch (VA.getLocInfo()) {
957 case CCValAssign::BCvt:
958 MemVT = VA.getLocVT();
960 case CCValAssign::SExt:
961 ExtType = ISD::SEXTLOAD;
963 case CCValAssign::ZExt:
964 ExtType = ISD::ZEXTLOAD;
966 case CCValAssign::AExt:
967 ExtType = ISD::EXTLOAD;
971 ArgValue = DAG.getExtLoad(
972 ExtType, SL, VA.getLocVT(), Chain, FIN,
973 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
978 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
979 CallingConv::ID CallConv,
980 ArrayRef<ISD::InputArg> Ins,
983 SIMachineFunctionInfo *Info) {
984 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
985 const ISD::InputArg &Arg = Ins[I];
987 // First check if it's a PS input addr.
988 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
989 !Arg.Flags.isByVal() && PSInputNum <= 15) {
991 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
992 // We can safely skip PS inputs.
998 Info->markPSInputAllocated(PSInputNum);
1000 Info->markPSInputEnabled(PSInputNum);
1005 // Second split vertices into their elements.
1006 if (Arg.VT.isVector()) {
1007 ISD::InputArg NewArg = Arg;
1008 NewArg.Flags.setSplit();
1009 NewArg.VT = Arg.VT.getVectorElementType();
1011 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1012 // three or five element vertex only needs three or five registers,
1013 // NOT four or eight.
1014 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1015 unsigned NumElements = ParamType->getVectorNumElements();
1017 for (unsigned J = 0; J != NumElements; ++J) {
1018 Splits.push_back(NewArg);
1019 NewArg.PartOffset += NewArg.VT.getStoreSize();
1022 Splits.push_back(Arg);
1027 // Allocate special inputs passed in VGPRs.
1028 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1029 MachineFunction &MF,
1030 const SIRegisterInfo &TRI,
1031 SIMachineFunctionInfo &Info) {
1032 if (Info.hasWorkItemIDX()) {
1033 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
1034 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1035 CCInfo.AllocateReg(Reg);
1038 if (Info.hasWorkItemIDY()) {
1039 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
1040 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1041 CCInfo.AllocateReg(Reg);
1044 if (Info.hasWorkItemIDZ()) {
1045 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
1046 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1047 CCInfo.AllocateReg(Reg);
1051 // Allocate special inputs passed in user SGPRs.
1052 static void allocateHSAUserSGPRs(CCState &CCInfo,
1053 MachineFunction &MF,
1054 const SIRegisterInfo &TRI,
1055 SIMachineFunctionInfo &Info) {
1056 if (Info.hasPrivateMemoryInputPtr()) {
1057 unsigned PrivateMemoryPtrReg = Info.addPrivateMemoryPtr(TRI);
1058 MF.addLiveIn(PrivateMemoryPtrReg, &AMDGPU::SGPR_64RegClass);
1059 CCInfo.AllocateReg(PrivateMemoryPtrReg);
1062 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1063 if (Info.hasPrivateSegmentBuffer()) {
1064 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1065 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1066 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1069 if (Info.hasDispatchPtr()) {
1070 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1071 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1072 CCInfo.AllocateReg(DispatchPtrReg);
1075 if (Info.hasQueuePtr()) {
1076 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1077 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1078 CCInfo.AllocateReg(QueuePtrReg);
1081 if (Info.hasKernargSegmentPtr()) {
1082 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1083 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1084 CCInfo.AllocateReg(InputPtrReg);
1087 if (Info.hasDispatchID()) {
1088 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1089 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1090 CCInfo.AllocateReg(DispatchIDReg);
1093 if (Info.hasFlatScratchInit()) {
1094 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1095 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1096 CCInfo.AllocateReg(FlatScratchInitReg);
1099 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1100 // these from the dispatch pointer.
1103 // Allocate special input registers that are initialized per-wave.
1104 static void allocateSystemSGPRs(CCState &CCInfo,
1105 MachineFunction &MF,
1106 SIMachineFunctionInfo &Info,
1107 CallingConv::ID CallConv,
1109 if (Info.hasWorkGroupIDX()) {
1110 unsigned Reg = Info.addWorkGroupIDX();
1111 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1112 CCInfo.AllocateReg(Reg);
1115 if (Info.hasWorkGroupIDY()) {
1116 unsigned Reg = Info.addWorkGroupIDY();
1117 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1118 CCInfo.AllocateReg(Reg);
1121 if (Info.hasWorkGroupIDZ()) {
1122 unsigned Reg = Info.addWorkGroupIDZ();
1123 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1124 CCInfo.AllocateReg(Reg);
1127 if (Info.hasWorkGroupInfo()) {
1128 unsigned Reg = Info.addWorkGroupInfo();
1129 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1130 CCInfo.AllocateReg(Reg);
1133 if (Info.hasPrivateSegmentWaveByteOffset()) {
1134 // Scratch wave offset passed in system SGPR.
1135 unsigned PrivateSegmentWaveByteOffsetReg;
1138 PrivateSegmentWaveByteOffsetReg =
1139 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1141 // This is true if the scratch wave byte offset doesn't have a fixed
1143 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1144 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1145 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1148 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1150 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1151 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1155 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1156 MachineFunction &MF,
1157 const SIRegisterInfo &TRI,
1158 SIMachineFunctionInfo &Info,
1160 // Now that we've figured out where the scratch register inputs are, see if
1161 // should reserve the arguments and use them directly.
1162 MachineFrameInfo &MFI = MF.getFrameInfo();
1163 bool HasStackObjects = MFI.hasStackObjects();
1165 // Record that we know we have non-spill stack objects so we don't need to
1166 // check all stack objects later.
1167 if (HasStackObjects)
1168 Info.setHasNonSpillStackObjects(true);
1170 // Everything live out of a block is spilled with fast regalloc, so it's
1171 // almost certain that spilling will be required.
1172 if (TM.getOptLevel() == CodeGenOpt::None)
1173 HasStackObjects = true;
1175 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1176 if (ST.isAmdCodeObjectV2(MF)) {
1177 if (HasStackObjects) {
1178 // If we have stack objects, we unquestionably need the private buffer
1179 // resource. For the Code Object V2 ABI, this will be the first 4 user
1180 // SGPR inputs. We can reserve those and use them directly.
1182 unsigned PrivateSegmentBufferReg = TRI.getPreloadedValue(
1183 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1184 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1186 unsigned PrivateSegmentWaveByteOffsetReg = TRI.getPreloadedValue(
1187 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1188 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1190 unsigned ReservedBufferReg
1191 = TRI.reservedPrivateSegmentBufferReg(MF);
1192 unsigned ReservedOffsetReg
1193 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1195 // We tentatively reserve the last registers (skipping the last two
1196 // which may contain VCC). After register allocation, we'll replace
1197 // these with the ones immediately after those which were really
1198 // allocated. In the prologue copies will be inserted from the argument
1199 // to these reserved registers.
1200 Info.setScratchRSrcReg(ReservedBufferReg);
1201 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1204 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1206 // Without HSA, relocations are used for the scratch pointer and the
1207 // buffer resource setup is always inserted in the prologue. Scratch wave
1208 // offset is still in an input SGPR.
1209 Info.setScratchRSrcReg(ReservedBufferReg);
1211 if (HasStackObjects) {
1212 unsigned ScratchWaveOffsetReg = TRI.getPreloadedValue(
1213 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1214 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1216 unsigned ReservedOffsetReg
1217 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1218 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1223 unsigned ReservedStackPtrOffsetReg = TRI.reservedStackPtrOffsetReg(MF);
1224 Info.setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
1226 assert(Info.getStackPtrOffsetReg() != Info.getFrameOffsetReg());
1227 assert(!TRI.isSubRegister(Info.getScratchRSrcReg(),
1228 Info.getStackPtrOffsetReg()));
1232 SDValue SITargetLowering::LowerFormalArguments(
1233 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1234 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1235 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1236 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1238 MachineFunction &MF = DAG.getMachineFunction();
1239 FunctionType *FType = MF.getFunction()->getFunctionType();
1240 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1241 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1243 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1244 const Function *Fn = MF.getFunction();
1245 DiagnosticInfoUnsupported NoGraphicsHSA(
1246 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1247 DAG.getContext()->diagnose(NoGraphicsHSA);
1248 return DAG.getEntryNode();
1251 // Create stack objects that are used for emitting debugger prologue if
1252 // "amdgpu-debugger-emit-prologue" attribute was specified.
1253 if (ST.debuggerEmitPrologue())
1254 createDebuggerPrologueStackObjects(MF);
1256 SmallVector<ISD::InputArg, 16> Splits;
1257 SmallVector<CCValAssign, 16> ArgLocs;
1258 BitVector Skipped(Ins.size());
1259 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1262 bool IsShader = AMDGPU::isShader(CallConv);
1263 bool IsKernel = AMDGPU::isKernel(CallConv);
1264 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1267 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1269 // At least one interpolation mode must be enabled or else the GPU will
1272 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1273 // set PSInputAddr, the user wants to enable some bits after the compilation
1274 // based on run-time states. Since we can't know what the final PSInputEna
1275 // will look like, so we shouldn't do anything here and the user should take
1276 // responsibility for the correct programming.
1278 // Otherwise, the following restrictions apply:
1279 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1280 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1282 if (CallConv == CallingConv::AMDGPU_PS &&
1283 ((Info->getPSInputAddr() & 0x7F) == 0 ||
1284 ((Info->getPSInputAddr() & 0xF) == 0 &&
1285 Info->isPSInputAllocated(11)))) {
1286 CCInfo.AllocateReg(AMDGPU::VGPR0);
1287 CCInfo.AllocateReg(AMDGPU::VGPR1);
1288 Info->markPSInputAllocated(0);
1289 Info->markPSInputEnabled(0);
1292 assert(!Info->hasDispatchPtr() &&
1293 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1294 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1295 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1296 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1297 !Info->hasWorkItemIDZ());
1298 } else if (IsKernel) {
1299 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1301 Splits.append(Ins.begin(), Ins.end());
1305 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1306 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1310 analyzeFormalArgumentsCompute(CCInfo, Ins);
1312 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1313 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1316 SmallVector<SDValue, 16> Chains;
1318 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1319 const ISD::InputArg &Arg = Ins[i];
1321 InVals.push_back(DAG.getUNDEF(Arg.VT));
1325 CCValAssign &VA = ArgLocs[ArgIdx++];
1326 MVT VT = VA.getLocVT();
1328 if (IsEntryFunc && VA.isMemLoc()) {
1330 EVT MemVT = VA.getLocVT();
1332 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1333 VA.getLocMemOffset();
1334 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1336 // The first 36 bytes of the input buffer contains information about
1337 // thread group and global sizes.
1338 SDValue Arg = lowerKernargMemParameter(
1339 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1340 Chains.push_back(Arg.getValue(1));
1343 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1344 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1345 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1346 // On SI local pointers are just offsets into LDS, so they are always
1347 // less than 16-bits. On CI and newer they could potentially be
1348 // real pointers, so we can't guarantee their size.
1349 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1350 DAG.getValueType(MVT::i16));
1353 InVals.push_back(Arg);
1355 } else if (!IsEntryFunc && VA.isMemLoc()) {
1356 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1357 InVals.push_back(Val);
1358 if (!Arg.Flags.isByVal())
1359 Chains.push_back(Val.getValue(1));
1363 assert(VA.isRegLoc() && "Parameter must be in a register!");
1365 unsigned Reg = VA.getLocReg();
1366 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1368 Reg = MF.addLiveIn(Reg, RC);
1369 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1371 if (IsShader && Arg.VT.isVector()) {
1372 // Build a vector from the registers
1373 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1374 unsigned NumElements = ParamType->getVectorNumElements();
1376 SmallVector<SDValue, 4> Regs;
1377 Regs.push_back(Val);
1378 for (unsigned j = 1; j != NumElements; ++j) {
1379 Reg = ArgLocs[ArgIdx++].getLocReg();
1380 Reg = MF.addLiveIn(Reg, RC);
1382 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1383 Regs.push_back(Copy);
1386 // Fill up the missing vector elements
1387 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1388 Regs.append(NumElements, DAG.getUNDEF(VT));
1390 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1394 InVals.push_back(Val);
1397 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1399 // TODO: Could maybe omit SP if only tail calls?
1400 bool NeedSP = FrameInfo.hasCalls() || FrameInfo.hasVarSizedObjects();
1402 // Start adding system SGPRs.
1404 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1405 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info, NeedSP);
1407 CCInfo.AllocateReg(Info->getScratchRSrcReg());
1408 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1409 CCInfo.AllocateReg(Info->getFrameOffsetReg());
1412 unsigned StackPtrReg = findFirstFreeSGPR(CCInfo);
1413 CCInfo.AllocateReg(StackPtrReg);
1414 Info->setStackPtrOffsetReg(StackPtrReg);
1418 return Chains.empty() ? Chain :
1419 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1422 // TODO: If return values can't fit in registers, we should return as many as
1423 // possible in registers before passing on stack.
1424 bool SITargetLowering::CanLowerReturn(
1425 CallingConv::ID CallConv,
1426 MachineFunction &MF, bool IsVarArg,
1427 const SmallVectorImpl<ISD::OutputArg> &Outs,
1428 LLVMContext &Context) const {
1429 // Replacing returns with sret/stack usage doesn't make sense for shaders.
1430 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1431 // for shaders. Vector types should be explicitly handled by CC.
1432 if (AMDGPU::isEntryFunctionCC(CallConv))
1435 SmallVector<CCValAssign, 16> RVLocs;
1436 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1437 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1441 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1443 const SmallVectorImpl<ISD::OutputArg> &Outs,
1444 const SmallVectorImpl<SDValue> &OutVals,
1445 const SDLoc &DL, SelectionDAG &DAG) const {
1446 MachineFunction &MF = DAG.getMachineFunction();
1447 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1449 if (AMDGPU::isKernel(CallConv)) {
1450 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1454 bool IsShader = AMDGPU::isShader(CallConv);
1456 Info->setIfReturnsVoid(Outs.size() == 0);
1457 bool IsWaveEnd = Info->returnsVoid() && IsShader;
1459 SmallVector<ISD::OutputArg, 48> Splits;
1460 SmallVector<SDValue, 48> SplitVals;
1462 // Split vectors into their elements.
1463 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1464 const ISD::OutputArg &Out = Outs[i];
1466 if (IsShader && Out.VT.isVector()) {
1467 MVT VT = Out.VT.getVectorElementType();
1468 ISD::OutputArg NewOut = Out;
1469 NewOut.Flags.setSplit();
1472 // We want the original number of vector elements here, e.g.
1473 // three or five, not four or eight.
1474 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1476 for (unsigned j = 0; j != NumElements; ++j) {
1477 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1478 DAG.getConstant(j, DL, MVT::i32));
1479 SplitVals.push_back(Elem);
1480 Splits.push_back(NewOut);
1481 NewOut.PartOffset += NewOut.VT.getStoreSize();
1484 SplitVals.push_back(OutVals[i]);
1485 Splits.push_back(Out);
1489 // CCValAssign - represent the assignment of the return value to a location.
1490 SmallVector<CCValAssign, 48> RVLocs;
1492 // CCState - Info about the registers and stack slots.
1493 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1496 // Analyze outgoing return values.
1497 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
1500 SmallVector<SDValue, 48> RetOps;
1501 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1503 // Add return address for callable functions.
1504 if (!Info->isEntryFunction()) {
1505 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1506 SDValue ReturnAddrReg = CreateLiveInRegister(
1507 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
1509 // FIXME: Should be able to use a vreg here, but need a way to prevent it
1510 // from being allcoated to a CSR.
1512 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
1515 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
1516 Flag = Chain.getValue(1);
1518 RetOps.push_back(PhysReturnAddrReg);
1521 // Copy the result values into the output registers.
1522 for (unsigned i = 0, realRVLocIdx = 0;
1524 ++i, ++realRVLocIdx) {
1525 CCValAssign &VA = RVLocs[i];
1526 assert(VA.isRegLoc() && "Can only return in registers!");
1527 // TODO: Partially return in registers if return values don't fit.
1529 SDValue Arg = SplitVals[realRVLocIdx];
1531 // Copied from other backends.
1532 switch (VA.getLocInfo()) {
1533 case CCValAssign::Full:
1535 case CCValAssign::BCvt:
1536 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1538 case CCValAssign::SExt:
1539 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
1541 case CCValAssign::ZExt:
1542 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
1544 case CCValAssign::AExt:
1545 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
1548 llvm_unreachable("Unknown loc info!");
1551 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1552 Flag = Chain.getValue(1);
1553 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1556 // FIXME: Does sret work properly?
1558 // Update chain and glue.
1561 RetOps.push_back(Flag);
1563 unsigned Opc = AMDGPUISD::ENDPGM;
1565 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
1566 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1569 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1570 SelectionDAG &DAG) const {
1571 unsigned Reg = StringSwitch<unsigned>(RegName)
1572 .Case("m0", AMDGPU::M0)
1573 .Case("exec", AMDGPU::EXEC)
1574 .Case("exec_lo", AMDGPU::EXEC_LO)
1575 .Case("exec_hi", AMDGPU::EXEC_HI)
1576 .Case("flat_scratch", AMDGPU::FLAT_SCR)
1577 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1578 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1579 .Default(AMDGPU::NoRegister);
1581 if (Reg == AMDGPU::NoRegister) {
1582 report_fatal_error(Twine("invalid register name \""
1583 + StringRef(RegName) + "\"."));
1587 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1588 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1589 report_fatal_error(Twine("invalid register \""
1590 + StringRef(RegName) + "\" for subtarget."));
1595 case AMDGPU::EXEC_LO:
1596 case AMDGPU::EXEC_HI:
1597 case AMDGPU::FLAT_SCR_LO:
1598 case AMDGPU::FLAT_SCR_HI:
1599 if (VT.getSizeInBits() == 32)
1603 case AMDGPU::FLAT_SCR:
1604 if (VT.getSizeInBits() == 64)
1608 llvm_unreachable("missing register type checking");
1611 report_fatal_error(Twine("invalid type for register \""
1612 + StringRef(RegName) + "\"."));
1615 // If kill is not the last instruction, split the block so kill is always a
1616 // proper terminator.
1617 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1618 MachineBasicBlock *BB) const {
1619 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1621 MachineBasicBlock::iterator SplitPoint(&MI);
1624 if (SplitPoint == BB->end()) {
1625 // Don't bother with a new block.
1626 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1630 MachineFunction *MF = BB->getParent();
1631 MachineBasicBlock *SplitBB
1632 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1634 MF->insert(++MachineFunction::iterator(BB), SplitBB);
1635 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1637 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1638 BB->addSuccessor(SplitBB);
1640 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1644 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1645 // wavefront. If the value is uniform and just happens to be in a VGPR, this
1646 // will only do one iteration. In the worst case, this will loop 64 times.
1648 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1649 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1650 const SIInstrInfo *TII,
1651 MachineRegisterInfo &MRI,
1652 MachineBasicBlock &OrigBB,
1653 MachineBasicBlock &LoopBB,
1655 const MachineOperand &IdxReg,
1659 unsigned InitSaveExecReg,
1661 bool UseGPRIdxMode) {
1662 MachineBasicBlock::iterator I = LoopBB.begin();
1664 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1665 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1666 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1667 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1669 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1675 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1676 .addReg(InitSaveExecReg)
1681 // Read the next variant <- also loop target.
1682 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1683 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1685 // Compare the just read M0 value to all possible Idx values.
1686 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1687 .addReg(CurrentIdxReg)
1688 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1690 if (UseGPRIdxMode) {
1693 IdxReg = CurrentIdxReg;
1695 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1696 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1697 .addReg(CurrentIdxReg, RegState::Kill)
1701 MachineInstr *SetIdx =
1702 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1703 .addReg(IdxReg, RegState::Kill);
1704 SetIdx->getOperand(2).setIsUndef();
1706 // Move index from VCC into M0
1708 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1709 .addReg(CurrentIdxReg, RegState::Kill);
1711 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1712 .addReg(CurrentIdxReg, RegState::Kill)
1717 // Update EXEC, save the original EXEC value to VCC.
1718 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1719 .addReg(CondReg, RegState::Kill);
1721 MRI.setSimpleHint(NewExec, CondReg);
1723 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1724 MachineInstr *InsertPt =
1725 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1726 .addReg(AMDGPU::EXEC)
1729 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1732 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1733 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1736 return InsertPt->getIterator();
1739 // This has slightly sub-optimal regalloc when the source vector is killed by
1740 // the read. The register allocator does not understand that the kill is
1741 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
1742 // subregister from it, using 1 more VGPR than necessary. This was saved when
1743 // this was expanded after register allocation.
1744 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1745 MachineBasicBlock &MBB,
1747 unsigned InitResultReg,
1750 bool UseGPRIdxMode) {
1751 MachineFunction *MF = MBB.getParent();
1752 MachineRegisterInfo &MRI = MF->getRegInfo();
1753 const DebugLoc &DL = MI.getDebugLoc();
1754 MachineBasicBlock::iterator I(&MI);
1756 unsigned DstReg = MI.getOperand(0).getReg();
1757 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1758 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1760 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1762 // Save the EXEC mask
1763 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1764 .addReg(AMDGPU::EXEC);
1766 // To insert the loop we need to split the block. Move everything after this
1767 // point to a new block, and insert a new empty block between the two.
1768 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1769 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1770 MachineFunction::iterator MBBI(MBB);
1773 MF->insert(MBBI, LoopBB);
1774 MF->insert(MBBI, RemainderBB);
1776 LoopBB->addSuccessor(LoopBB);
1777 LoopBB->addSuccessor(RemainderBB);
1779 // Move the rest of the block into a new block.
1780 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1781 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1783 MBB.addSuccessor(LoopBB);
1785 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1787 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1788 InitResultReg, DstReg, PhiReg, TmpExec,
1789 Offset, UseGPRIdxMode);
1791 MachineBasicBlock::iterator First = RemainderBB->begin();
1792 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1798 // Returns subreg index, offset
1799 static std::pair<unsigned, int>
1800 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1801 const TargetRegisterClass *SuperRC,
1804 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
1806 // Skip out of bounds offsets, or else we would end up using an undefined
1808 if (Offset >= NumElts || Offset < 0)
1809 return std::make_pair(AMDGPU::sub0, Offset);
1811 return std::make_pair(AMDGPU::sub0 + Offset, 0);
1814 // Return true if the index is an SGPR and was set.
1815 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1816 MachineRegisterInfo &MRI,
1820 bool IsIndirectSrc) {
1821 MachineBasicBlock *MBB = MI.getParent();
1822 const DebugLoc &DL = MI.getDebugLoc();
1823 MachineBasicBlock::iterator I(&MI);
1825 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1826 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1828 assert(Idx->getReg() != AMDGPU::NoRegister);
1830 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1833 if (UseGPRIdxMode) {
1834 unsigned IdxMode = IsIndirectSrc ?
1835 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1837 MachineInstr *SetOn =
1838 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1842 SetOn->getOperand(3).setIsUndef();
1844 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1845 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1848 MachineInstr *SetOn =
1849 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1850 .addReg(Tmp, RegState::Kill)
1853 SetOn->getOperand(3).setIsUndef();
1860 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1863 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1871 // Control flow needs to be inserted if indexing with a VGPR.
1872 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1873 MachineBasicBlock &MBB,
1874 const SISubtarget &ST) {
1875 const SIInstrInfo *TII = ST.getInstrInfo();
1876 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1877 MachineFunction *MF = MBB.getParent();
1878 MachineRegisterInfo &MRI = MF->getRegInfo();
1880 unsigned Dst = MI.getOperand(0).getReg();
1881 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1882 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1884 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1887 std::tie(SubReg, Offset)
1888 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1890 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1892 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1893 MachineBasicBlock::iterator I(&MI);
1894 const DebugLoc &DL = MI.getDebugLoc();
1896 if (UseGPRIdxMode) {
1897 // TODO: Look at the uses to avoid the copy. This may require rescheduling
1898 // to avoid interfering with other uses, so probably requires a new
1899 // optimization pass.
1900 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1901 .addReg(SrcReg, RegState::Undef, SubReg)
1902 .addReg(SrcReg, RegState::Implicit)
1903 .addReg(AMDGPU::M0, RegState::Implicit);
1904 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1906 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1907 .addReg(SrcReg, RegState::Undef, SubReg)
1908 .addReg(SrcReg, RegState::Implicit);
1911 MI.eraseFromParent();
1916 const DebugLoc &DL = MI.getDebugLoc();
1917 MachineBasicBlock::iterator I(&MI);
1919 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1920 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1922 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1924 if (UseGPRIdxMode) {
1925 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1926 .addImm(0) // Reset inside loop.
1927 .addImm(VGPRIndexMode::SRC0_ENABLE);
1928 SetOn->getOperand(3).setIsUndef();
1930 // Disable again after the loop.
1931 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1934 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1935 MachineBasicBlock *LoopBB = InsPt->getParent();
1937 if (UseGPRIdxMode) {
1938 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1939 .addReg(SrcReg, RegState::Undef, SubReg)
1940 .addReg(SrcReg, RegState::Implicit)
1941 .addReg(AMDGPU::M0, RegState::Implicit);
1943 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1944 .addReg(SrcReg, RegState::Undef, SubReg)
1945 .addReg(SrcReg, RegState::Implicit);
1948 MI.eraseFromParent();
1953 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
1954 const TargetRegisterClass *VecRC) {
1955 switch (TRI.getRegSizeInBits(*VecRC)) {
1957 return AMDGPU::V_MOVRELD_B32_V1;
1959 return AMDGPU::V_MOVRELD_B32_V2;
1960 case 128: // 16 bytes
1961 return AMDGPU::V_MOVRELD_B32_V4;
1962 case 256: // 32 bytes
1963 return AMDGPU::V_MOVRELD_B32_V8;
1964 case 512: // 64 bytes
1965 return AMDGPU::V_MOVRELD_B32_V16;
1967 llvm_unreachable("unsupported size for MOVRELD pseudos");
1971 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1972 MachineBasicBlock &MBB,
1973 const SISubtarget &ST) {
1974 const SIInstrInfo *TII = ST.getInstrInfo();
1975 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1976 MachineFunction *MF = MBB.getParent();
1977 MachineRegisterInfo &MRI = MF->getRegInfo();
1979 unsigned Dst = MI.getOperand(0).getReg();
1980 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1981 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1982 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1983 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1984 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1986 // This can be an immediate, but will be folded later.
1987 assert(Val->getReg());
1990 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1993 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1995 if (Idx->getReg() == AMDGPU::NoRegister) {
1996 MachineBasicBlock::iterator I(&MI);
1997 const DebugLoc &DL = MI.getDebugLoc();
1999 assert(Offset == 0);
2001 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
2006 MI.eraseFromParent();
2010 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
2011 MachineBasicBlock::iterator I(&MI);
2012 const DebugLoc &DL = MI.getDebugLoc();
2014 if (UseGPRIdxMode) {
2015 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
2016 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
2018 .addReg(Dst, RegState::ImplicitDefine)
2019 .addReg(SrcVec->getReg(), RegState::Implicit)
2020 .addReg(AMDGPU::M0, RegState::Implicit);
2022 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2024 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
2026 BuildMI(MBB, I, DL, MovRelDesc)
2027 .addReg(Dst, RegState::Define)
2028 .addReg(SrcVec->getReg())
2030 .addImm(SubReg - AMDGPU::sub0);
2033 MI.eraseFromParent();
2038 MRI.clearKillFlags(Val->getReg());
2040 const DebugLoc &DL = MI.getDebugLoc();
2042 if (UseGPRIdxMode) {
2043 MachineBasicBlock::iterator I(&MI);
2045 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2046 .addImm(0) // Reset inside loop.
2047 .addImm(VGPRIndexMode::DST_ENABLE);
2048 SetOn->getOperand(3).setIsUndef();
2050 // Disable again after the loop.
2051 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2054 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
2056 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
2057 Offset, UseGPRIdxMode);
2058 MachineBasicBlock *LoopBB = InsPt->getParent();
2060 if (UseGPRIdxMode) {
2061 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
2062 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
2064 .addReg(Dst, RegState::ImplicitDefine)
2065 .addReg(PhiReg, RegState::Implicit)
2066 .addReg(AMDGPU::M0, RegState::Implicit);
2068 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
2070 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
2071 .addReg(Dst, RegState::Define)
2074 .addImm(SubReg - AMDGPU::sub0);
2077 MI.eraseFromParent();
2082 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
2083 MachineInstr &MI, MachineBasicBlock *BB) const {
2085 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2086 MachineFunction *MF = BB->getParent();
2087 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
2089 if (TII->isMIMG(MI)) {
2090 if (!MI.memoperands_empty())
2092 // Add a memoperand for mimg instructions so that they aren't assumed to
2093 // be ordered memory instuctions.
2095 MachinePointerInfo PtrInfo(MFI->getImagePSV());
2096 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
2098 Flags |= MachineMemOperand::MOStore;
2101 Flags |= MachineMemOperand::MOLoad;
2103 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
2104 MI.addMemOperand(*MF, MMO);
2108 switch (MI.getOpcode()) {
2109 case AMDGPU::SI_INIT_M0:
2110 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
2111 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2112 .add(MI.getOperand(0));
2113 MI.eraseFromParent();
2116 case AMDGPU::SI_INIT_EXEC:
2117 // This should be before all vector instructions.
2118 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
2120 .addImm(MI.getOperand(0).getImm());
2121 MI.eraseFromParent();
2124 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
2125 // Extract the thread count from an SGPR input and set EXEC accordingly.
2126 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
2128 // S_BFE_U32 count, input, {shift, 7}
2129 // S_BFM_B64 exec, count, 0
2130 // S_CMP_EQ_U32 count, 64
2131 // S_CMOV_B64 exec, -1
2132 MachineInstr *FirstMI = &*BB->begin();
2133 MachineRegisterInfo &MRI = MF->getRegInfo();
2134 unsigned InputReg = MI.getOperand(0).getReg();
2135 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2138 // Move the COPY of the input reg to the beginning, so that we can use it.
2139 for (auto I = BB->begin(); I != &MI; I++) {
2140 if (I->getOpcode() != TargetOpcode::COPY ||
2141 I->getOperand(0).getReg() != InputReg)
2145 FirstMI = &*++BB->begin();
2147 I->removeFromParent();
2148 BB->insert(FirstMI, &*I);
2156 // This should be before all vector instructions.
2157 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
2159 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
2160 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
2164 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
2165 .addReg(CountReg, RegState::Kill)
2167 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
2170 MI.eraseFromParent();
2174 case AMDGPU::GET_GROUPSTATICSIZE: {
2175 DebugLoc DL = MI.getDebugLoc();
2176 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
2177 .add(MI.getOperand(0))
2178 .addImm(MFI->getLDSSize());
2179 MI.eraseFromParent();
2182 case AMDGPU::SI_INDIRECT_SRC_V1:
2183 case AMDGPU::SI_INDIRECT_SRC_V2:
2184 case AMDGPU::SI_INDIRECT_SRC_V4:
2185 case AMDGPU::SI_INDIRECT_SRC_V8:
2186 case AMDGPU::SI_INDIRECT_SRC_V16:
2187 return emitIndirectSrc(MI, *BB, *getSubtarget());
2188 case AMDGPU::SI_INDIRECT_DST_V1:
2189 case AMDGPU::SI_INDIRECT_DST_V2:
2190 case AMDGPU::SI_INDIRECT_DST_V4:
2191 case AMDGPU::SI_INDIRECT_DST_V8:
2192 case AMDGPU::SI_INDIRECT_DST_V16:
2193 return emitIndirectDst(MI, *BB, *getSubtarget());
2194 case AMDGPU::SI_KILL:
2195 return splitKillBlock(MI, BB);
2196 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
2197 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2199 unsigned Dst = MI.getOperand(0).getReg();
2200 unsigned Src0 = MI.getOperand(1).getReg();
2201 unsigned Src1 = MI.getOperand(2).getReg();
2202 const DebugLoc &DL = MI.getDebugLoc();
2203 unsigned SrcCond = MI.getOperand(3).getReg();
2205 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2206 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2208 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
2209 .addReg(Src0, 0, AMDGPU::sub0)
2210 .addReg(Src1, 0, AMDGPU::sub0)
2212 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
2213 .addReg(Src0, 0, AMDGPU::sub1)
2214 .addReg(Src1, 0, AMDGPU::sub1)
2217 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
2219 .addImm(AMDGPU::sub0)
2221 .addImm(AMDGPU::sub1);
2222 MI.eraseFromParent();
2225 case AMDGPU::SI_BR_UNDEF: {
2226 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2227 const DebugLoc &DL = MI.getDebugLoc();
2228 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
2229 .add(MI.getOperand(0));
2230 Br->getOperand(1).setIsUndef(true); // read undef SCC
2231 MI.eraseFromParent();
2235 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
2239 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
2240 // This currently forces unfolding various combinations of fsub into fma with
2241 // free fneg'd operands. As long as we have fast FMA (controlled by
2242 // isFMAFasterThanFMulAndFAdd), we should perform these.
2244 // When fma is quarter rate, for f64 where add / sub are at best half rate,
2245 // most of these combines appear to be cycle neutral but save on instruction
2246 // count / code size.
2250 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
2252 if (!VT.isVector()) {
2255 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
2258 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
2259 // TODO: Should i16 be used always if legal? For now it would force VALU
2261 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
2264 // Answering this is somewhat tricky and depends on the specific device which
2265 // have different rates for fma or all f64 operations.
2267 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
2268 // regardless of which device (although the number of cycles differs between
2269 // devices), so it is always profitable for f64.
2271 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
2272 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
2273 // which we can always do even without fused FP ops since it returns the same
2274 // result as the separate operations and since it is always full
2275 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
2276 // however does not support denormals, so we do report fma as faster if we have
2277 // a fast fma device and require denormals.
2279 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
2280 VT = VT.getScalarType();
2282 switch (VT.getSimpleVT().SimpleTy) {
2284 // This is as fast on some subtargets. However, we always have full rate f32
2285 // mad available which returns the same result as the separate operations
2286 // which we should prefer over fma. We can't use this if we want to support
2287 // denormals, so only report this in these cases.
2288 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
2292 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
2300 //===----------------------------------------------------------------------===//
2301 // Custom DAG Lowering Operations
2302 //===----------------------------------------------------------------------===//
2304 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2305 switch (Op.getOpcode()) {
2306 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2307 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2309 SDValue Result = LowerLOAD(Op, DAG);
2310 assert((!Result.getNode() ||
2311 Result.getNode()->getNumValues() == 2) &&
2312 "Load should return a value and a chain");
2318 return LowerTrig(Op, DAG);
2319 case ISD::SELECT: return LowerSELECT(Op, DAG);
2320 case ISD::FDIV: return LowerFDIV(Op, DAG);
2321 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
2322 case ISD::STORE: return LowerSTORE(Op, DAG);
2323 case ISD::GlobalAddress: {
2324 MachineFunction &MF = DAG.getMachineFunction();
2325 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2326 return LowerGlobalAddress(MFI, Op, DAG);
2328 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2329 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2330 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
2331 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
2332 case ISD::INSERT_VECTOR_ELT:
2333 return lowerINSERT_VECTOR_ELT(Op, DAG);
2334 case ISD::EXTRACT_VECTOR_ELT:
2335 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2337 return lowerFP_ROUND(Op, DAG);
2340 case ISD::DEBUGTRAP:
2341 return lowerTRAP(Op, DAG);
2346 void SITargetLowering::ReplaceNodeResults(SDNode *N,
2347 SmallVectorImpl<SDValue> &Results,
2348 SelectionDAG &DAG) const {
2349 switch (N->getOpcode()) {
2350 case ISD::INSERT_VECTOR_ELT: {
2351 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
2352 Results.push_back(Res);
2355 case ISD::EXTRACT_VECTOR_ELT: {
2356 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
2357 Results.push_back(Res);
2360 case ISD::INTRINSIC_WO_CHAIN: {
2361 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2363 case Intrinsic::amdgcn_cvt_pkrtz: {
2364 SDValue Src0 = N->getOperand(1);
2365 SDValue Src1 = N->getOperand(2);
2367 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
2370 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
2379 EVT VT = N->getValueType(0);
2380 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2381 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
2382 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
2384 EVT SelectVT = NewVT;
2385 if (NewVT.bitsLT(MVT::i32)) {
2386 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
2387 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
2388 SelectVT = MVT::i32;
2391 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
2392 N->getOperand(0), LHS, RHS);
2394 if (NewVT != SelectVT)
2395 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
2396 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
2404 /// \brief Helper function for LowerBRCOND
2405 static SDNode *findUser(SDValue Value, unsigned Opcode) {
2407 SDNode *Parent = Value.getNode();
2408 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
2411 if (I.getUse().get() != Value)
2414 if (I->getOpcode() == Opcode)
2420 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
2421 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
2422 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
2423 case Intrinsic::amdgcn_if:
2424 return AMDGPUISD::IF;
2425 case Intrinsic::amdgcn_else:
2426 return AMDGPUISD::ELSE;
2427 case Intrinsic::amdgcn_loop:
2428 return AMDGPUISD::LOOP;
2429 case Intrinsic::amdgcn_end_cf:
2430 llvm_unreachable("should not occur");
2436 // break, if_break, else_break are all only used as inputs to loop, not
2437 // directly as branch conditions.
2441 void SITargetLowering::createDebuggerPrologueStackObjects(
2442 MachineFunction &MF) const {
2443 // Create stack objects that are used for emitting debugger prologue.
2445 // Debugger prologue writes work group IDs and work item IDs to scratch memory
2446 // at fixed location in the following format:
2447 // offset 0: work group ID x
2448 // offset 4: work group ID y
2449 // offset 8: work group ID z
2450 // offset 16: work item ID x
2451 // offset 20: work item ID y
2452 // offset 24: work item ID z
2453 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2456 // For each dimension:
2457 for (unsigned i = 0; i < 3; ++i) {
2458 // Create fixed stack object for work group ID.
2459 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
2460 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
2461 // Create fixed stack object for work item ID.
2462 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
2463 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
2467 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
2468 const Triple &TT = getTargetMachine().getTargetTriple();
2469 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
2470 AMDGPU::shouldEmitConstantsToTextSection(TT);
2473 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
2474 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2475 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2476 !shouldEmitFixup(GV) &&
2477 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2480 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2481 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2484 /// This transforms the control flow intrinsics to get the branch destination as
2485 /// last parameter, also switches branch target with BR if the need arise
2486 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2487 SelectionDAG &DAG) const {
2490 SDNode *Intr = BRCOND.getOperand(1).getNode();
2491 SDValue Target = BRCOND.getOperand(2);
2492 SDNode *BR = nullptr;
2493 SDNode *SetCC = nullptr;
2495 if (Intr->getOpcode() == ISD::SETCC) {
2496 // As long as we negate the condition everything is fine
2498 Intr = SetCC->getOperand(0).getNode();
2501 // Get the target from BR if we don't negate the condition
2502 BR = findUser(BRCOND, ISD::BR);
2503 Target = BR->getOperand(1);
2506 // FIXME: This changes the types of the intrinsics instead of introducing new
2507 // nodes with the correct types.
2508 // e.g. llvm.amdgcn.loop
2510 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2511 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2513 unsigned CFNode = isCFIntrinsic(Intr);
2515 // This is a uniform branch so we don't need to legalize.
2519 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2520 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2523 (SetCC->getConstantOperandVal(1) == 1 &&
2524 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
2527 // operands of the new intrinsic call
2528 SmallVector<SDValue, 4> Ops;
2530 Ops.push_back(BRCOND.getOperand(0));
2532 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
2533 Ops.push_back(Target);
2535 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2537 // build the new intrinsic call
2538 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
2543 BRCOND.getOperand(0)
2546 Result = DAG.getMergeValues(Ops, DL).getNode();
2550 // Give the branch instruction our target
2553 BRCOND.getOperand(2)
2555 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2556 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2557 BR = NewBR.getNode();
2560 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2562 // Copy the intrinsic results to registers
2563 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2564 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2568 Chain = DAG.getCopyToReg(
2570 CopyToReg->getOperand(1),
2571 SDValue(Result, i - 1),
2574 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2577 // Remove the old intrinsic from the chain
2578 DAG.ReplaceAllUsesOfValueWith(
2579 SDValue(Intr, Intr->getNumValues() - 1),
2580 Intr->getOperand(0));
2585 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2589 return Op.getValueType().bitsLE(VT) ?
2590 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2591 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2594 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2595 assert(Op.getValueType() == MVT::f16 &&
2596 "Do not know how to custom lower FP_ROUND for non-f16 type");
2598 SDValue Src = Op.getOperand(0);
2599 EVT SrcVT = Src.getValueType();
2600 if (SrcVT != MVT::f64)
2605 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2606 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2607 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
2610 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
2612 MachineFunction &MF = DAG.getMachineFunction();
2613 SDValue Chain = Op.getOperand(0);
2615 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ?
2616 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap;
2618 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
2619 Subtarget->isTrapHandlerEnabled()) {
2620 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2621 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2622 assert(UserSGPR != AMDGPU::NoRegister);
2624 SDValue QueuePtr = CreateLiveInRegister(
2625 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2627 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
2629 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
2630 QueuePtr, SDValue());
2634 DAG.getTargetConstant(TrapID, SL, MVT::i16),
2639 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
2643 case SISubtarget::TrapIDLLVMTrap:
2644 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
2645 case SISubtarget::TrapIDLLVMDebugTrap: {
2646 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(),
2647 "debugtrap handler not supported",
2650 LLVMContext &Ctx = MF.getFunction()->getContext();
2651 Ctx.diagnose(NoTrap);
2655 llvm_unreachable("unsupported trap handler type!");
2661 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
2662 SelectionDAG &DAG) const {
2663 // FIXME: Use inline constants (src_{shared, private}_base) instead.
2664 if (Subtarget->hasApertureRegs()) {
2665 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
2666 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
2667 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
2668 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
2669 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
2670 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
2672 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
2673 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
2674 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
2676 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
2677 SDValue ApertureReg = SDValue(
2678 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
2679 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
2680 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
2683 MachineFunction &MF = DAG.getMachineFunction();
2684 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2685 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2686 assert(UserSGPR != AMDGPU::NoRegister);
2688 SDValue QueuePtr = CreateLiveInRegister(
2689 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2691 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2692 // private_segment_aperture_base_hi.
2693 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
2695 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr,
2696 DAG.getConstant(StructOffset, DL, MVT::i64));
2698 // TODO: Use custom target PseudoSourceValue.
2699 // TODO: We should use the value from the IR intrinsic call, but it might not
2700 // be available and how do we get it?
2701 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2702 AMDGPUASI.CONSTANT_ADDRESS));
2704 MachinePointerInfo PtrInfo(V, StructOffset);
2705 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
2706 MinAlign(64, StructOffset),
2707 MachineMemOperand::MODereferenceable |
2708 MachineMemOperand::MOInvariant);
2711 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2712 SelectionDAG &DAG) const {
2714 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2716 SDValue Src = ASC->getOperand(0);
2717 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2719 const AMDGPUTargetMachine &TM =
2720 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
2722 // flat -> local/private
2723 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2724 unsigned DestAS = ASC->getDestAddressSpace();
2726 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
2727 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
2728 unsigned NullVal = TM.getNullPointerValue(DestAS);
2729 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2730 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2731 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2733 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2734 NonNull, Ptr, SegmentNullPtr);
2738 // local/private -> flat
2739 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2740 unsigned SrcAS = ASC->getSrcAddressSpace();
2742 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
2743 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
2744 unsigned NullVal = TM.getNullPointerValue(SrcAS);
2745 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2748 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2750 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
2752 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2754 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2755 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2760 // global <-> flat are no-ops and never emitted.
2762 const MachineFunction &MF = DAG.getMachineFunction();
2763 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2764 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2765 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2767 return DAG.getUNDEF(ASC->getValueType(0));
2770 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2771 SelectionDAG &DAG) const {
2772 SDValue Idx = Op.getOperand(2);
2773 if (isa<ConstantSDNode>(Idx))
2776 // Avoid stack access for dynamic indexing.
2778 SDValue Vec = Op.getOperand(0);
2779 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
2781 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
2782 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
2784 // Convert vector index to bit-index.
2785 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
2786 DAG.getConstant(16, SL, MVT::i32));
2788 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2790 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
2791 DAG.getConstant(0xffff, SL, MVT::i32),
2794 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
2795 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
2796 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
2798 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
2799 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
2802 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2803 SelectionDAG &DAG) const {
2806 EVT ResultVT = Op.getValueType();
2807 SDValue Vec = Op.getOperand(0);
2808 SDValue Idx = Op.getOperand(1);
2810 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
2812 // Make sure we we do any optimizations that will make it easier to fold
2813 // source modifiers before obscuring it with bit operations.
2815 // XXX - Why doesn't this get called when vector_shuffle is expanded?
2816 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
2819 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
2820 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2822 if (CIdx->getZExtValue() == 1) {
2823 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
2824 DAG.getConstant(16, SL, MVT::i32));
2826 assert(CIdx->getZExtValue() == 0);
2829 if (ResultVT.bitsLT(MVT::i32))
2830 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2831 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2834 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
2836 // Convert vector index to bit-index.
2837 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
2839 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2840 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
2842 SDValue Result = Elt;
2843 if (ResultVT.bitsLT(MVT::i32))
2844 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2846 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2850 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2851 // We can fold offsets for anything that doesn't require a GOT relocation.
2852 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2853 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2854 !shouldEmitGOTReloc(GA->getGlobal());
2858 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2859 const SDLoc &DL, unsigned Offset, EVT PtrVT,
2860 unsigned GAFlags = SIInstrInfo::MO_NONE) {
2861 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2862 // lowered to the following code sequence:
2864 // For constant address space:
2865 // s_getpc_b64 s[0:1]
2866 // s_add_u32 s0, s0, $symbol
2867 // s_addc_u32 s1, s1, 0
2869 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2870 // a fixup or relocation is emitted to replace $symbol with a literal
2871 // constant, which is a pc-relative offset from the encoding of the $symbol
2872 // operand to the global variable.
2874 // For global address space:
2875 // s_getpc_b64 s[0:1]
2876 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2877 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2879 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2880 // fixups or relocations are emitted to replace $symbol@*@lo and
2881 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2882 // which is a 64-bit pc-relative offset from the encoding of the $symbol
2883 // operand to the global variable.
2885 // What we want here is an offset from the value returned by s_getpc
2886 // (which is the address of the s_add_u32 instruction) to the global
2887 // variable, but since the encoding of $symbol starts 4 bytes after the start
2888 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2889 // small. This requires us to add 4 to the global variable offset in order to
2890 // compute the correct address.
2891 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2893 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2894 GAFlags == SIInstrInfo::MO_NONE ?
2895 GAFlags : GAFlags + 1);
2896 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2899 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2901 SelectionDAG &DAG) const {
2902 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2904 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
2905 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS)
2906 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2909 const GlobalValue *GV = GSD->getGlobal();
2910 EVT PtrVT = Op.getValueType();
2912 if (shouldEmitFixup(GV))
2913 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2914 else if (shouldEmitPCReloc(GV))
2915 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2916 SIInstrInfo::MO_REL32);
2918 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2919 SIInstrInfo::MO_GOTPCREL32);
2921 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2922 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
2923 const DataLayout &DataLayout = DAG.getDataLayout();
2924 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2925 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2926 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2928 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2929 MachineMemOperand::MODereferenceable |
2930 MachineMemOperand::MOInvariant);
2933 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2934 const SDLoc &DL, SDValue V) const {
2935 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2936 // the destination register.
2938 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2939 // so we will end up with redundant moves to m0.
2941 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2943 // A Null SDValue creates a glue result.
2944 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2946 return SDValue(M0, 0);
2949 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2952 unsigned Offset) const {
2954 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
2955 DAG.getEntryNode(), Offset, false);
2956 // The local size values will have the hi 16-bits as zero.
2957 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2958 DAG.getValueType(VT));
2961 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2963 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2964 "non-hsa intrinsic with hsa target",
2966 DAG.getContext()->diagnose(BadIntrin);
2967 return DAG.getUNDEF(VT);
2970 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2972 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2973 "intrinsic not supported on subtarget",
2975 DAG.getContext()->diagnose(BadIntrin);
2976 return DAG.getUNDEF(VT);
2979 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2980 SelectionDAG &DAG) const {
2981 MachineFunction &MF = DAG.getMachineFunction();
2982 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2983 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2985 EVT VT = Op.getValueType();
2987 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2989 // TODO: Should this propagate fast-math-flags?
2991 switch (IntrinsicID) {
2992 case Intrinsic::amdgcn_implicit_buffer_ptr: {
2993 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2994 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2996 case Intrinsic::amdgcn_dispatch_ptr:
2997 case Intrinsic::amdgcn_queue_ptr: {
2998 if (!Subtarget->isAmdCodeObjectV2(MF)) {
2999 DiagnosticInfoUnsupported BadIntrin(
3000 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
3002 DAG.getContext()->diagnose(BadIntrin);
3003 return DAG.getUNDEF(VT);
3006 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
3007 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
3008 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
3009 TRI->getPreloadedValue(MF, Reg), VT);
3011 case Intrinsic::amdgcn_implicitarg_ptr: {
3012 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
3013 return lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
3015 case Intrinsic::amdgcn_kernarg_segment_ptr: {
3017 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
3018 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
3020 case Intrinsic::amdgcn_dispatch_id: {
3021 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
3022 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
3024 case Intrinsic::amdgcn_rcp:
3025 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
3026 case Intrinsic::amdgcn_rsq:
3027 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
3028 case Intrinsic::amdgcn_rsq_legacy:
3029 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3030 return emitRemovedIntrinsicError(DAG, DL, VT);
3032 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
3033 case Intrinsic::amdgcn_rcp_legacy:
3034 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3035 return emitRemovedIntrinsicError(DAG, DL, VT);
3036 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
3037 case Intrinsic::amdgcn_rsq_clamp: {
3038 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
3039 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
3041 Type *Type = VT.getTypeForEVT(*DAG.getContext());
3042 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
3043 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
3045 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
3046 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
3047 DAG.getConstantFP(Max, DL, VT));
3048 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
3049 DAG.getConstantFP(Min, DL, VT));
3051 case Intrinsic::r600_read_ngroups_x:
3052 if (Subtarget->isAmdHsaOS())
3053 return emitNonHSAIntrinsicError(DAG, DL, VT);
3055 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3056 SI::KernelInputOffsets::NGROUPS_X, false);
3057 case Intrinsic::r600_read_ngroups_y:
3058 if (Subtarget->isAmdHsaOS())
3059 return emitNonHSAIntrinsicError(DAG, DL, VT);
3061 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3062 SI::KernelInputOffsets::NGROUPS_Y, false);
3063 case Intrinsic::r600_read_ngroups_z:
3064 if (Subtarget->isAmdHsaOS())
3065 return emitNonHSAIntrinsicError(DAG, DL, VT);
3067 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3068 SI::KernelInputOffsets::NGROUPS_Z, false);
3069 case Intrinsic::r600_read_global_size_x:
3070 if (Subtarget->isAmdHsaOS())
3071 return emitNonHSAIntrinsicError(DAG, DL, VT);
3073 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3074 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
3075 case Intrinsic::r600_read_global_size_y:
3076 if (Subtarget->isAmdHsaOS())
3077 return emitNonHSAIntrinsicError(DAG, DL, VT);
3079 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3080 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
3081 case Intrinsic::r600_read_global_size_z:
3082 if (Subtarget->isAmdHsaOS())
3083 return emitNonHSAIntrinsicError(DAG, DL, VT);
3085 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3086 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
3087 case Intrinsic::r600_read_local_size_x:
3088 if (Subtarget->isAmdHsaOS())
3089 return emitNonHSAIntrinsicError(DAG, DL, VT);
3091 return lowerImplicitZextParam(DAG, Op, MVT::i16,
3092 SI::KernelInputOffsets::LOCAL_SIZE_X);
3093 case Intrinsic::r600_read_local_size_y:
3094 if (Subtarget->isAmdHsaOS())
3095 return emitNonHSAIntrinsicError(DAG, DL, VT);
3097 return lowerImplicitZextParam(DAG, Op, MVT::i16,
3098 SI::KernelInputOffsets::LOCAL_SIZE_Y);
3099 case Intrinsic::r600_read_local_size_z:
3100 if (Subtarget->isAmdHsaOS())
3101 return emitNonHSAIntrinsicError(DAG, DL, VT);
3103 return lowerImplicitZextParam(DAG, Op, MVT::i16,
3104 SI::KernelInputOffsets::LOCAL_SIZE_Z);
3105 case Intrinsic::amdgcn_workgroup_id_x:
3106 case Intrinsic::r600_read_tgid_x:
3107 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
3108 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
3109 case Intrinsic::amdgcn_workgroup_id_y:
3110 case Intrinsic::r600_read_tgid_y:
3111 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
3112 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
3113 case Intrinsic::amdgcn_workgroup_id_z:
3114 case Intrinsic::r600_read_tgid_z:
3115 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
3116 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
3117 case Intrinsic::amdgcn_workitem_id_x:
3118 case Intrinsic::r600_read_tidig_x:
3119 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
3120 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
3121 case Intrinsic::amdgcn_workitem_id_y:
3122 case Intrinsic::r600_read_tidig_y:
3123 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
3124 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
3125 case Intrinsic::amdgcn_workitem_id_z:
3126 case Intrinsic::r600_read_tidig_z:
3127 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
3128 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
3129 case AMDGPUIntrinsic::SI_load_const: {
3135 MachineMemOperand *MMO = MF.getMachineMemOperand(
3136 MachinePointerInfo(),
3137 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3138 MachineMemOperand::MOInvariant,
3139 VT.getStoreSize(), 4);
3140 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
3141 Op->getVTList(), Ops, VT, MMO);
3143 case Intrinsic::amdgcn_fdiv_fast:
3144 return lowerFDIV_FAST(Op, DAG);
3145 case Intrinsic::amdgcn_interp_mov: {
3146 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
3147 SDValue Glue = M0.getValue(1);
3148 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
3149 Op.getOperand(2), Op.getOperand(3), Glue);
3151 case Intrinsic::amdgcn_interp_p1: {
3152 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
3153 SDValue Glue = M0.getValue(1);
3154 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
3155 Op.getOperand(2), Op.getOperand(3), Glue);
3157 case Intrinsic::amdgcn_interp_p2: {
3158 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
3159 SDValue Glue = SDValue(M0.getNode(), 1);
3160 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
3161 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
3164 case Intrinsic::amdgcn_sin:
3165 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
3167 case Intrinsic::amdgcn_cos:
3168 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
3170 case Intrinsic::amdgcn_log_clamp: {
3171 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
3174 DiagnosticInfoUnsupported BadIntrin(
3175 *MF.getFunction(), "intrinsic not supported on subtarget",
3177 DAG.getContext()->diagnose(BadIntrin);
3178 return DAG.getUNDEF(VT);
3180 case Intrinsic::amdgcn_ldexp:
3181 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
3182 Op.getOperand(1), Op.getOperand(2));
3184 case Intrinsic::amdgcn_fract:
3185 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
3187 case Intrinsic::amdgcn_class:
3188 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
3189 Op.getOperand(1), Op.getOperand(2));
3190 case Intrinsic::amdgcn_div_fmas:
3191 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
3192 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
3195 case Intrinsic::amdgcn_div_fixup:
3196 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
3197 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3199 case Intrinsic::amdgcn_trig_preop:
3200 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
3201 Op.getOperand(1), Op.getOperand(2));
3202 case Intrinsic::amdgcn_div_scale: {
3203 // 3rd parameter required to be a constant.
3204 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3206 return DAG.getUNDEF(VT);
3208 // Translate to the operands expected by the machine instruction. The
3209 // first parameter must be the same as the first instruction.
3210 SDValue Numerator = Op.getOperand(1);
3211 SDValue Denominator = Op.getOperand(2);
3213 // Note this order is opposite of the machine instruction's operations,
3214 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
3215 // intrinsic has the numerator as the first operand to match a normal
3216 // division operation.
3218 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
3220 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
3221 Denominator, Numerator);
3223 case Intrinsic::amdgcn_icmp: {
3224 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3226 return DAG.getUNDEF(VT);
3228 int CondCode = CD->getSExtValue();
3229 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
3230 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
3231 return DAG.getUNDEF(VT);
3233 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
3234 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
3235 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3236 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3238 case Intrinsic::amdgcn_fcmp: {
3239 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3241 return DAG.getUNDEF(VT);
3243 int CondCode = CD->getSExtValue();
3244 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
3245 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
3246 return DAG.getUNDEF(VT);
3248 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
3249 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
3250 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3251 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3253 case Intrinsic::amdgcn_fmed3:
3254 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
3255 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3256 case Intrinsic::amdgcn_fmul_legacy:
3257 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
3258 Op.getOperand(1), Op.getOperand(2));
3259 case Intrinsic::amdgcn_sffbh:
3260 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
3261 case Intrinsic::amdgcn_sbfe:
3262 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
3263 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3264 case Intrinsic::amdgcn_ubfe:
3265 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
3266 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3267 case Intrinsic::amdgcn_cvt_pkrtz: {
3268 // FIXME: Stop adding cast if v2f16 legal.
3269 EVT VT = Op.getValueType();
3270 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
3271 Op.getOperand(1), Op.getOperand(2));
3272 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
3279 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3280 SelectionDAG &DAG) const {
3281 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3284 case Intrinsic::amdgcn_atomic_inc:
3285 case Intrinsic::amdgcn_atomic_dec: {
3286 MemSDNode *M = cast<MemSDNode>(Op);
3287 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
3288 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
3290 M->getOperand(0), // Chain
3291 M->getOperand(2), // Ptr
3292 M->getOperand(3) // Value
3295 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
3296 M->getMemoryVT(), M->getMemOperand());
3298 case Intrinsic::amdgcn_buffer_load:
3299 case Intrinsic::amdgcn_buffer_load_format: {
3301 Op.getOperand(0), // Chain
3302 Op.getOperand(2), // rsrc
3303 Op.getOperand(3), // vindex
3304 Op.getOperand(4), // offset
3305 Op.getOperand(5), // glc
3306 Op.getOperand(6) // slc
3308 MachineFunction &MF = DAG.getMachineFunction();
3309 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3311 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
3312 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
3313 EVT VT = Op.getValueType();
3314 EVT IntVT = VT.changeTypeToInteger();
3316 MachineMemOperand *MMO = MF.getMachineMemOperand(
3317 MachinePointerInfo(MFI->getBufferPSV()),
3318 MachineMemOperand::MOLoad,
3319 VT.getStoreSize(), VT.getStoreSize());
3321 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
3324 case Intrinsic::amdgcn_image_sample:
3325 case Intrinsic::amdgcn_image_sample_cl:
3326 case Intrinsic::amdgcn_image_sample_d:
3327 case Intrinsic::amdgcn_image_sample_d_cl:
3328 case Intrinsic::amdgcn_image_sample_l:
3329 case Intrinsic::amdgcn_image_sample_b:
3330 case Intrinsic::amdgcn_image_sample_b_cl:
3331 case Intrinsic::amdgcn_image_sample_lz:
3332 case Intrinsic::amdgcn_image_sample_cd:
3333 case Intrinsic::amdgcn_image_sample_cd_cl:
3335 // Sample with comparison.
3336 case Intrinsic::amdgcn_image_sample_c:
3337 case Intrinsic::amdgcn_image_sample_c_cl:
3338 case Intrinsic::amdgcn_image_sample_c_d:
3339 case Intrinsic::amdgcn_image_sample_c_d_cl:
3340 case Intrinsic::amdgcn_image_sample_c_l:
3341 case Intrinsic::amdgcn_image_sample_c_b:
3342 case Intrinsic::amdgcn_image_sample_c_b_cl:
3343 case Intrinsic::amdgcn_image_sample_c_lz:
3344 case Intrinsic::amdgcn_image_sample_c_cd:
3345 case Intrinsic::amdgcn_image_sample_c_cd_cl:
3347 // Sample with offsets.
3348 case Intrinsic::amdgcn_image_sample_o:
3349 case Intrinsic::amdgcn_image_sample_cl_o:
3350 case Intrinsic::amdgcn_image_sample_d_o:
3351 case Intrinsic::amdgcn_image_sample_d_cl_o:
3352 case Intrinsic::amdgcn_image_sample_l_o:
3353 case Intrinsic::amdgcn_image_sample_b_o:
3354 case Intrinsic::amdgcn_image_sample_b_cl_o:
3355 case Intrinsic::amdgcn_image_sample_lz_o:
3356 case Intrinsic::amdgcn_image_sample_cd_o:
3357 case Intrinsic::amdgcn_image_sample_cd_cl_o:
3359 // Sample with comparison and offsets.
3360 case Intrinsic::amdgcn_image_sample_c_o:
3361 case Intrinsic::amdgcn_image_sample_c_cl_o:
3362 case Intrinsic::amdgcn_image_sample_c_d_o:
3363 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3364 case Intrinsic::amdgcn_image_sample_c_l_o:
3365 case Intrinsic::amdgcn_image_sample_c_b_o:
3366 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3367 case Intrinsic::amdgcn_image_sample_c_lz_o:
3368 case Intrinsic::amdgcn_image_sample_c_cd_o:
3369 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3371 case Intrinsic::amdgcn_image_getlod: {
3372 // Replace dmask with everything disabled with undef.
3373 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
3374 if (!DMask || DMask->isNullValue()) {
3375 SDValue Undef = DAG.getUNDEF(Op.getValueType());
3376 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
3386 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
3387 SelectionDAG &DAG) const {
3388 MachineFunction &MF = DAG.getMachineFunction();
3390 SDValue Chain = Op.getOperand(0);
3391 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3393 switch (IntrinsicID) {
3394 case Intrinsic::amdgcn_exp: {
3395 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3396 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3397 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
3398 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
3400 const SDValue Ops[] = {
3402 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3403 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3404 Op.getOperand(4), // src0
3405 Op.getOperand(5), // src1
3406 Op.getOperand(6), // src2
3407 Op.getOperand(7), // src3
3408 DAG.getTargetConstant(0, DL, MVT::i1), // compr
3409 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3412 unsigned Opc = Done->isNullValue() ?
3413 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3414 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3416 case Intrinsic::amdgcn_exp_compr: {
3417 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3418 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3419 SDValue Src0 = Op.getOperand(4);
3420 SDValue Src1 = Op.getOperand(5);
3421 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
3422 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
3424 SDValue Undef = DAG.getUNDEF(MVT::f32);
3425 const SDValue Ops[] = {
3427 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3428 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3429 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
3430 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
3433 DAG.getTargetConstant(1, DL, MVT::i1), // compr
3434 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3437 unsigned Opc = Done->isNullValue() ?
3438 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3439 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3441 case Intrinsic::amdgcn_s_sendmsg:
3442 case Intrinsic::amdgcn_s_sendmsghalt: {
3443 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
3444 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
3445 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
3446 SDValue Glue = Chain.getValue(1);
3447 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
3448 Op.getOperand(2), Glue);
3450 case Intrinsic::amdgcn_init_exec: {
3451 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
3454 case Intrinsic::amdgcn_init_exec_from_input: {
3455 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
3456 Op.getOperand(2), Op.getOperand(3));
3458 case AMDGPUIntrinsic::SI_tbuffer_store: {
3476 EVT VT = Op.getOperand(3).getValueType();
3478 MachineMemOperand *MMO = MF.getMachineMemOperand(
3479 MachinePointerInfo(),
3480 MachineMemOperand::MOStore,
3481 VT.getStoreSize(), 4);
3482 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
3483 Op->getVTList(), Ops, VT, MMO);
3485 case AMDGPUIntrinsic::AMDGPU_kill: {
3486 SDValue Src = Op.getOperand(2);
3487 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
3488 if (!K->isNegative())
3491 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
3492 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
3495 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
3496 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
3498 case Intrinsic::amdgcn_s_barrier: {
3499 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
3500 const MachineFunction &MF = DAG.getMachineFunction();
3501 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
3502 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second;
3503 if (WGSize <= ST.getWavefrontSize())
3504 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
3505 Op.getOperand(0)), 0);
3514 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3516 LoadSDNode *Load = cast<LoadSDNode>(Op);
3517 ISD::LoadExtType ExtType = Load->getExtensionType();
3518 EVT MemVT = Load->getMemoryVT();
3520 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
3521 // FIXME: Copied from PPC
3522 // First, load into 32 bits, then truncate to 1 bit.
3524 SDValue Chain = Load->getChain();
3525 SDValue BasePtr = Load->getBasePtr();
3526 MachineMemOperand *MMO = Load->getMemOperand();
3528 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
3530 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
3531 BasePtr, RealMemVT, MMO);
3534 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
3538 return DAG.getMergeValues(Ops, DL);
3541 if (!MemVT.isVector())
3544 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
3545 "Custom lowering for non-i32 vectors hasn't been implemented.");
3547 unsigned AS = Load->getAddressSpace();
3548 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
3549 AS, Load->getAlignment())) {
3551 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3552 return DAG.getMergeValues(Ops, DL);
3555 MachineFunction &MF = DAG.getMachineFunction();
3556 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3557 // If there is a possibilty that flat instruction access scratch memory
3558 // then we need to use the same legalization rules we use for private.
3559 if (AS == AMDGPUASI.FLAT_ADDRESS)
3560 AS = MFI->hasFlatScratchInit() ?
3561 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3563 unsigned NumElements = MemVT.getVectorNumElements();
3564 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3565 if (isMemOpUniform(Load))
3567 // Non-uniform loads will be selected to MUBUF instructions, so they
3568 // have the same legalization requirements as global and private
3572 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
3573 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
3574 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load))
3576 // Non-uniform loads will be selected to MUBUF instructions, so they
3577 // have the same legalization requirements as global and private
3581 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
3582 AS == AMDGPUASI.FLAT_ADDRESS) {
3583 if (NumElements > 4)
3584 return SplitVectorLoad(Op, DAG);
3585 // v4 loads are supported for private and global memory.
3588 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3589 // Depending on the setting of the private_element_size field in the
3590 // resource descriptor, we can only make private accesses up to a certain
3592 switch (Subtarget->getMaxPrivateElementSize()) {
3594 return scalarizeVectorLoad(Load, DAG);
3596 if (NumElements > 2)
3597 return SplitVectorLoad(Op, DAG);
3600 // Same as global/flat
3601 if (NumElements > 4)
3602 return SplitVectorLoad(Op, DAG);
3605 llvm_unreachable("unsupported private_element_size");
3607 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3608 if (NumElements > 2)
3609 return SplitVectorLoad(Op, DAG);
3611 if (NumElements == 2)
3614 // If properly aligned, if we split we might be able to use ds_read_b64.
3615 return SplitVectorLoad(Op, DAG);
3620 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3621 if (Op.getValueType() != MVT::i64)
3625 SDValue Cond = Op.getOperand(0);
3627 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
3628 SDValue One = DAG.getConstant(1, DL, MVT::i32);
3630 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
3631 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
3633 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
3634 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
3636 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
3638 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
3639 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
3641 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
3643 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
3644 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
3647 // Catch division cases where we can use shortcuts with rcp and rsq
3649 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
3650 SelectionDAG &DAG) const {
3652 SDValue LHS = Op.getOperand(0);
3653 SDValue RHS = Op.getOperand(1);
3654 EVT VT = Op.getValueType();
3655 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
3657 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
3660 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
3661 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
3662 if (CLHS->isExactlyValue(1.0)) {
3663 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
3664 // the CI documentation has a worst case error of 1 ulp.
3665 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
3666 // use it as long as we aren't trying to use denormals.
3668 // v_rcp_f16 and v_rsq_f16 DO support denormals.
3670 // 1.0 / sqrt(x) -> rsq(x)
3672 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
3673 // error seems really high at 2^29 ULP.
3674 if (RHS.getOpcode() == ISD::FSQRT)
3675 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
3677 // 1.0 / x -> rcp(x)
3678 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3681 // Same as for 1.0, but expand the sign out of the constant.
3682 if (CLHS->isExactlyValue(-1.0)) {
3683 // -1.0 / x -> rcp (fneg x)
3684 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3685 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
3690 const SDNodeFlags Flags = Op->getFlags();
3692 if (Unsafe || Flags.hasAllowReciprocal()) {
3693 // Turn into multiply by the reciprocal.
3694 // x / y -> x * (1.0 / y)
3695 SDNodeFlags NewFlags;
3696 NewFlags.setUnsafeAlgebra(true);
3697 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3698 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, NewFlags);
3704 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3705 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3706 if (GlueChain->getNumValues() <= 1) {
3707 return DAG.getNode(Opcode, SL, VT, A, B);
3710 assert(GlueChain->getNumValues() == 3);
3712 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3714 default: llvm_unreachable("no chain equivalent for opcode");
3716 Opcode = AMDGPUISD::FMUL_W_CHAIN;
3720 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3721 GlueChain.getValue(2));
3724 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3725 EVT VT, SDValue A, SDValue B, SDValue C,
3726 SDValue GlueChain) {
3727 if (GlueChain->getNumValues() <= 1) {
3728 return DAG.getNode(Opcode, SL, VT, A, B, C);
3731 assert(GlueChain->getNumValues() == 3);
3733 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3735 default: llvm_unreachable("no chain equivalent for opcode");
3737 Opcode = AMDGPUISD::FMA_W_CHAIN;
3741 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3742 GlueChain.getValue(2));
3745 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3746 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3750 SDValue Src0 = Op.getOperand(0);
3751 SDValue Src1 = Op.getOperand(1);
3753 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3754 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3756 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3757 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3759 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3760 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3762 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3765 // Faster 2.5 ULP division that does not support denormals.
3766 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3768 SDValue LHS = Op.getOperand(1);
3769 SDValue RHS = Op.getOperand(2);
3771 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3773 const APFloat K0Val(BitsToFloat(0x6f800000));
3774 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3776 const APFloat K1Val(BitsToFloat(0x2f800000));
3777 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3779 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3782 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3784 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3786 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3788 // TODO: Should this propagate fast-math-flags?
3789 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3791 // rcp does not support denormals.
3792 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3794 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3796 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3799 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3800 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3804 SDValue LHS = Op.getOperand(0);
3805 SDValue RHS = Op.getOperand(1);
3807 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3809 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3811 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3813 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3816 // Denominator is scaled to not be denormal, so using rcp is ok.
3817 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3819 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3822 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3823 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3824 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3826 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3828 if (!Subtarget->hasFP32Denormals()) {
3829 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3830 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
3832 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3834 EnableDenormValue, BitField);
3837 EnableDenorm.getValue(0),
3838 EnableDenorm.getValue(1)
3841 NegDivScale0 = DAG.getMergeValues(Ops, SL);
3844 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3845 ApproxRcp, One, NegDivScale0);
3847 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3850 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3853 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3854 NumeratorScaled, Mul);
3856 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3858 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3859 NumeratorScaled, Fma3);
3861 if (!Subtarget->hasFP32Denormals()) {
3862 const SDValue DisableDenormValue =
3863 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
3864 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3870 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3871 DisableDenorm, DAG.getRoot());
3872 DAG.setRoot(OutputChain);
3875 SDValue Scale = NumeratorScaled.getValue(1);
3876 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3877 Fma4, Fma1, Fma3, Scale);
3879 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3882 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3883 if (DAG.getTarget().Options.UnsafeFPMath)
3884 return lowerFastUnsafeFDIV(Op, DAG);
3887 SDValue X = Op.getOperand(0);
3888 SDValue Y = Op.getOperand(1);
3890 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3892 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3894 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3896 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3898 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3900 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3902 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3904 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3906 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3908 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3909 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3911 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3912 NegDivScale0, Mul, DivScale1);
3916 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3917 // Workaround a hardware bug on SI where the condition output from div_scale
3920 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3922 // Figure out if the scale to use for div_fmas.
3923 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3924 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3925 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3926 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3928 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3929 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3932 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3934 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3936 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3937 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3938 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3940 Scale = DivScale1.getValue(1);
3943 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3944 Fma4, Fma3, Mul, Scale);
3946 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3949 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3950 EVT VT = Op.getValueType();
3953 return LowerFDIV32(Op, DAG);
3956 return LowerFDIV64(Op, DAG);
3959 return LowerFDIV16(Op, DAG);
3961 llvm_unreachable("Unexpected type for fdiv");
3964 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3966 StoreSDNode *Store = cast<StoreSDNode>(Op);
3967 EVT VT = Store->getMemoryVT();
3969 if (VT == MVT::i1) {
3970 return DAG.getTruncStore(Store->getChain(), DL,
3971 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3972 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3975 assert(VT.isVector() &&
3976 Store->getValue().getValueType().getScalarType() == MVT::i32);
3978 unsigned AS = Store->getAddressSpace();
3979 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3980 AS, Store->getAlignment())) {
3981 return expandUnalignedStore(Store, DAG);
3984 MachineFunction &MF = DAG.getMachineFunction();
3985 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3986 // If there is a possibilty that flat instruction access scratch memory
3987 // then we need to use the same legalization rules we use for private.
3988 if (AS == AMDGPUASI.FLAT_ADDRESS)
3989 AS = MFI->hasFlatScratchInit() ?
3990 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3992 unsigned NumElements = VT.getVectorNumElements();
3993 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
3994 AS == AMDGPUASI.FLAT_ADDRESS) {
3995 if (NumElements > 4)
3996 return SplitVectorStore(Op, DAG);
3998 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3999 switch (Subtarget->getMaxPrivateElementSize()) {
4001 return scalarizeVectorStore(Store, DAG);
4003 if (NumElements > 2)
4004 return SplitVectorStore(Op, DAG);
4007 if (NumElements > 4)
4008 return SplitVectorStore(Op, DAG);
4011 llvm_unreachable("unsupported private_element_size");
4013 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
4014 if (NumElements > 2)
4015 return SplitVectorStore(Op, DAG);
4017 if (NumElements == 2)
4020 // If properly aligned, if we split we might be able to use ds_write_b64.
4021 return SplitVectorStore(Op, DAG);
4023 llvm_unreachable("unhandled address space");
4027 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
4029 EVT VT = Op.getValueType();
4030 SDValue Arg = Op.getOperand(0);
4031 // TODO: Should this propagate fast-math-flags?
4032 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
4033 DAG.getNode(ISD::FMUL, DL, VT, Arg,
4034 DAG.getConstantFP(0.5/M_PI, DL,
4037 switch (Op.getOpcode()) {
4039 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
4041 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
4043 llvm_unreachable("Wrong trig opcode");
4047 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
4048 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
4049 assert(AtomicNode->isCompareAndSwap());
4050 unsigned AS = AtomicNode->getAddressSpace();
4052 // No custom lowering required for local address space
4053 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
4056 // Non-local address space requires custom lowering for atomic compare
4057 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
4059 SDValue ChainIn = Op.getOperand(0);
4060 SDValue Addr = Op.getOperand(1);
4061 SDValue Old = Op.getOperand(2);
4062 SDValue New = Op.getOperand(3);
4063 EVT VT = Op.getValueType();
4064 MVT SimpleVT = VT.getSimpleVT();
4065 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
4067 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
4068 SDValue Ops[] = { ChainIn, Addr, NewOld };
4070 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
4071 Ops, VT, AtomicNode->getMemOperand());
4074 //===----------------------------------------------------------------------===//
4075 // Custom DAG optimizations
4076 //===----------------------------------------------------------------------===//
4078 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
4079 DAGCombinerInfo &DCI) const {
4080 EVT VT = N->getValueType(0);
4081 EVT ScalarVT = VT.getScalarType();
4082 if (ScalarVT != MVT::f32)
4085 SelectionDAG &DAG = DCI.DAG;
4088 SDValue Src = N->getOperand(0);
4089 EVT SrcVT = Src.getValueType();
4091 // TODO: We could try to match extracting the higher bytes, which would be
4092 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
4093 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
4094 // about in practice.
4095 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
4096 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
4097 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
4098 DCI.AddToWorklist(Cvt.getNode());
4106 /// \brief Return true if the given offset Size in bytes can be folded into
4107 /// the immediate offsets of a memory instruction for the given address space.
4108 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
4109 const SISubtarget &STI) {
4110 auto AMDGPUASI = STI.getAMDGPUAS();
4111 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
4112 // MUBUF instructions a 12-bit offset in bytes.
4113 return isUInt<12>(OffsetSize);
4115 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
4116 // SMRD instructions have an 8-bit offset in dwords on SI and
4117 // a 20-bit offset in bytes on VI.
4118 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4119 return isUInt<20>(OffsetSize);
4121 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
4123 if (AS == AMDGPUASI.LOCAL_ADDRESS ||
4124 AS == AMDGPUASI.REGION_ADDRESS) {
4125 // The single offset versions have a 16-bit offset in bytes.
4126 return isUInt<16>(OffsetSize);
4128 // Indirect register addressing does not use any offsets.
4132 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
4134 // This is a variant of
4135 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
4137 // The normal DAG combiner will do this, but only if the add has one use since
4138 // that would increase the number of instructions.
4140 // This prevents us from seeing a constant offset that can be folded into a
4141 // memory instruction's addressing mode. If we know the resulting add offset of
4142 // a pointer can be folded into an addressing offset, we can replace the pointer
4143 // operand with the add of new constant offset. This eliminates one of the uses,
4144 // and may allow the remaining use to also be simplified.
4146 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
4148 DAGCombinerInfo &DCI) const {
4149 SDValue N0 = N->getOperand(0);
4150 SDValue N1 = N->getOperand(1);
4152 if (N0.getOpcode() != ISD::ADD)
4155 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
4159 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4163 // If the resulting offset is too large, we can't fold it into the addressing
4165 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
4166 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
4169 SelectionDAG &DAG = DCI.DAG;
4171 EVT VT = N->getValueType(0);
4173 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
4174 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
4176 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
4179 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
4180 DAGCombinerInfo &DCI) const {
4181 SDValue Ptr = N->getBasePtr();
4182 SelectionDAG &DAG = DCI.DAG;
4185 // TODO: We could also do this for multiplies.
4186 unsigned AS = N->getAddressSpace();
4187 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) {
4188 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
4190 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
4192 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
4193 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
4200 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
4201 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
4202 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
4203 (Opc == ISD::XOR && Val == 0);
4206 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
4207 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
4208 // integer combine opportunities since most 64-bit operations are decomposed
4209 // this way. TODO: We won't want this for SALU especially if it is an inline
4211 SDValue SITargetLowering::splitBinaryBitConstantOp(
4212 DAGCombinerInfo &DCI,
4214 unsigned Opc, SDValue LHS,
4215 const ConstantSDNode *CRHS) const {
4216 uint64_t Val = CRHS->getZExtValue();
4217 uint32_t ValLo = Lo_32(Val);
4218 uint32_t ValHi = Hi_32(Val);
4219 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4221 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
4222 bitOpWithConstantIsReducible(Opc, ValHi)) ||
4223 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
4224 // If we need to materialize a 64-bit immediate, it will be split up later
4225 // anyway. Avoid creating the harder to understand 64-bit immediate
4227 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
4233 SDValue SITargetLowering::performAndCombine(SDNode *N,
4234 DAGCombinerInfo &DCI) const {
4235 if (DCI.isBeforeLegalize())
4238 SelectionDAG &DAG = DCI.DAG;
4239 EVT VT = N->getValueType(0);
4240 SDValue LHS = N->getOperand(0);
4241 SDValue RHS = N->getOperand(1);
4244 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4245 if (VT == MVT::i64 && CRHS) {
4247 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
4251 if (CRHS && VT == MVT::i32) {
4252 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
4253 // nb = number of trailing zeroes in mask
4254 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
4255 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
4256 uint64_t Mask = CRHS->getZExtValue();
4257 unsigned Bits = countPopulation(Mask);
4258 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
4259 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
4260 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
4261 unsigned Shift = CShift->getZExtValue();
4262 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
4263 unsigned Offset = NB + Shift;
4264 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
4266 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
4268 DAG.getConstant(Offset, SL, MVT::i32),
4269 DAG.getConstant(Bits, SL, MVT::i32));
4270 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
4271 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
4272 DAG.getValueType(NarrowVT));
4273 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
4274 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
4281 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
4282 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
4283 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
4284 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
4285 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
4287 SDValue X = LHS.getOperand(0);
4288 SDValue Y = RHS.getOperand(0);
4289 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
4292 if (LCC == ISD::SETO) {
4293 if (X != LHS.getOperand(1))
4296 if (RCC == ISD::SETUNE) {
4297 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
4298 if (!C1 || !C1->isInfinity() || C1->isNegative())
4301 const uint32_t Mask = SIInstrFlags::N_NORMAL |
4302 SIInstrFlags::N_SUBNORMAL |
4303 SIInstrFlags::N_ZERO |
4304 SIInstrFlags::P_ZERO |
4305 SIInstrFlags::P_SUBNORMAL |
4306 SIInstrFlags::P_NORMAL;
4308 static_assert(((~(SIInstrFlags::S_NAN |
4309 SIInstrFlags::Q_NAN |
4310 SIInstrFlags::N_INFINITY |
4311 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
4315 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4316 X, DAG.getConstant(Mask, DL, MVT::i32));
4324 SDValue SITargetLowering::performOrCombine(SDNode *N,
4325 DAGCombinerInfo &DCI) const {
4326 SelectionDAG &DAG = DCI.DAG;
4327 SDValue LHS = N->getOperand(0);
4328 SDValue RHS = N->getOperand(1);
4330 EVT VT = N->getValueType(0);
4331 if (VT == MVT::i1) {
4332 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
4333 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
4334 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
4335 SDValue Src = LHS.getOperand(0);
4336 if (Src != RHS.getOperand(0))
4339 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
4340 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
4344 // Only 10 bits are used.
4345 static const uint32_t MaxMask = 0x3ff;
4347 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
4349 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4350 Src, DAG.getConstant(NewMask, DL, MVT::i32));
4359 // TODO: This could be a generic combine with a predicate for extracting the
4360 // high half of an integer being free.
4362 // (or i64:x, (zero_extend i32:y)) ->
4363 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
4364 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
4365 RHS.getOpcode() != ISD::ZERO_EXTEND)
4366 std::swap(LHS, RHS);
4368 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
4369 SDValue ExtSrc = RHS.getOperand(0);
4370 EVT SrcVT = ExtSrc.getValueType();
4371 if (SrcVT == MVT::i32) {
4373 SDValue LowLHS, HiBits;
4374 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
4375 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
4377 DCI.AddToWorklist(LowOr.getNode());
4378 DCI.AddToWorklist(HiBits.getNode());
4380 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
4382 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
4386 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
4389 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
4396 SDValue SITargetLowering::performXorCombine(SDNode *N,
4397 DAGCombinerInfo &DCI) const {
4398 EVT VT = N->getValueType(0);
4402 SDValue LHS = N->getOperand(0);
4403 SDValue RHS = N->getOperand(1);
4405 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4408 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
4415 // Instructions that will be lowered with a final instruction that zeros the
4416 // high result bits.
4417 // XXX - probably only need to list legal operations.
4418 static bool fp16SrcZerosHighBits(unsigned Opc) {
4427 case ISD::FCANONICALIZE:
4429 case ISD::UINT_TO_FP:
4430 case ISD::SINT_TO_FP:
4432 // Fabs is lowered to a bit operation, but it's an and which will clear the
4433 // high bits anyway.
4447 case ISD::FNEARBYINT:
4452 case AMDGPUISD::FRACT:
4453 case AMDGPUISD::CLAMP:
4454 case AMDGPUISD::COS_HW:
4455 case AMDGPUISD::SIN_HW:
4456 case AMDGPUISD::FMIN3:
4457 case AMDGPUISD::FMAX3:
4458 case AMDGPUISD::FMED3:
4459 case AMDGPUISD::FMAD_FTZ:
4460 case AMDGPUISD::RCP:
4461 case AMDGPUISD::RSQ:
4462 case AMDGPUISD::LDEXP:
4465 // fcopysign, select and others may be lowered to 32-bit bit operations
4466 // which don't zero the high bits.
4471 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
4472 DAGCombinerInfo &DCI) const {
4473 if (!Subtarget->has16BitInsts() ||
4474 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4477 EVT VT = N->getValueType(0);
4481 SDValue Src = N->getOperand(0);
4482 if (Src.getValueType() != MVT::i16)
4485 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
4486 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
4487 if (Src.getOpcode() == ISD::BITCAST) {
4488 SDValue BCSrc = Src.getOperand(0);
4489 if (BCSrc.getValueType() == MVT::f16 &&
4490 fp16SrcZerosHighBits(BCSrc.getOpcode()))
4491 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
4497 SDValue SITargetLowering::performClassCombine(SDNode *N,
4498 DAGCombinerInfo &DCI) const {
4499 SelectionDAG &DAG = DCI.DAG;
4500 SDValue Mask = N->getOperand(1);
4502 // fp_class x, 0 -> false
4503 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
4504 if (CMask->isNullValue())
4505 return DAG.getConstant(0, SDLoc(N), MVT::i1);
4508 if (N->getOperand(0).isUndef())
4509 return DAG.getUNDEF(MVT::i1);
4514 // Constant fold canonicalize.
4515 SDValue SITargetLowering::performFCanonicalizeCombine(
4517 DAGCombinerInfo &DCI) const {
4518 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
4522 SelectionDAG &DAG = DCI.DAG;
4523 const APFloat &C = CFP->getValueAPF();
4525 // Flush denormals to 0 if not enabled.
4526 if (C.isDenormal()) {
4527 EVT VT = N->getValueType(0);
4528 EVT SVT = VT.getScalarType();
4529 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
4530 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4532 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
4533 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4535 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
4536 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4540 EVT VT = N->getValueType(0);
4541 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
4542 if (C.isSignaling()) {
4543 // Quiet a signaling NaN.
4544 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4547 // Make sure it is the canonical NaN bitpattern.
4549 // TODO: Can we use -1 as the canonical NaN value since it's an inline
4551 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
4552 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4555 return N->getOperand(0);
4558 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
4561 return AMDGPUISD::FMAX3;
4563 return AMDGPUISD::SMAX3;
4565 return AMDGPUISD::UMAX3;
4567 return AMDGPUISD::FMIN3;
4569 return AMDGPUISD::SMIN3;
4571 return AMDGPUISD::UMIN3;
4573 llvm_unreachable("Not a min/max opcode");
4577 SDValue SITargetLowering::performIntMed3ImmCombine(
4578 SelectionDAG &DAG, const SDLoc &SL,
4579 SDValue Op0, SDValue Op1, bool Signed) const {
4580 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
4584 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4589 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
4592 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
4596 EVT VT = K0->getValueType(0);
4597 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
4598 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
4599 return DAG.getNode(Med3Opc, SL, VT,
4600 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
4603 // If there isn't a 16-bit med3 operation, convert to 32-bit.
4605 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4607 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
4608 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
4609 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
4611 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
4612 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
4615 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
4616 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
4619 return DAG.isKnownNeverNaN(Op);
4622 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
4625 SDValue Op1) const {
4626 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
4630 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
4634 // Ordered >= (although NaN inputs should have folded away by now).
4635 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
4636 if (Cmp == APFloat::cmpGreaterThan)
4639 // TODO: Check IEEE bit enabled?
4640 EVT VT = K0->getValueType(0);
4641 if (Subtarget->enableDX10Clamp()) {
4642 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
4643 // hardware fmed3 behavior converting to a min.
4644 // FIXME: Should this be allowing -0.0?
4645 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
4646 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
4649 // med3 for f16 is only available on gfx9+.
4650 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16()))
4653 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
4654 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
4655 // give the other result, which is different from med3 with a NaN input.
4656 SDValue Var = Op0.getOperand(0);
4657 if (!isKnownNeverSNan(DAG, Var))
4660 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
4661 Var, SDValue(K0, 0), SDValue(K1, 0));
4664 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
4665 DAGCombinerInfo &DCI) const {
4666 SelectionDAG &DAG = DCI.DAG;
4668 EVT VT = N->getValueType(0);
4669 unsigned Opc = N->getOpcode();
4670 SDValue Op0 = N->getOperand(0);
4671 SDValue Op1 = N->getOperand(1);
4673 // Only do this if the inner op has one use since this will just increases
4674 // register pressure for no benefit.
4677 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
4679 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
4680 // max(max(a, b), c) -> max3(a, b, c)
4681 // min(min(a, b), c) -> min3(a, b, c)
4682 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
4684 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4693 // max(a, max(b, c)) -> max3(a, b, c)
4694 // min(a, min(b, c)) -> min3(a, b, c)
4695 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
4697 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4706 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
4707 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
4708 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
4712 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4713 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
4717 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
4718 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
4719 (Opc == AMDGPUISD::FMIN_LEGACY &&
4720 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
4721 (VT == MVT::f32 || VT == MVT::f64 ||
4722 (VT == MVT::f16 && Subtarget->has16BitInsts())) &&
4724 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
4731 static bool isClampZeroToOne(SDValue A, SDValue B) {
4732 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
4733 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
4734 // FIXME: Should this be allowing -0.0?
4735 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
4736 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
4743 // FIXME: Should only worry about snans for version with chain.
4744 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
4745 DAGCombinerInfo &DCI) const {
4746 EVT VT = N->getValueType(0);
4747 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
4748 // NaNs. With a NaN input, the order of the operands may change the result.
4750 SelectionDAG &DAG = DCI.DAG;
4753 SDValue Src0 = N->getOperand(0);
4754 SDValue Src1 = N->getOperand(1);
4755 SDValue Src2 = N->getOperand(2);
4757 if (isClampZeroToOne(Src0, Src1)) {
4758 // const_a, const_b, x -> clamp is safe in all cases including signaling
4760 // FIXME: Should this be allowing -0.0?
4761 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
4764 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
4765 // handling no dx10-clamp?
4766 if (Subtarget->enableDX10Clamp()) {
4767 // If NaNs is clamped to 0, we are free to reorder the inputs.
4769 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4770 std::swap(Src0, Src1);
4772 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
4773 std::swap(Src1, Src2);
4775 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4776 std::swap(Src0, Src1);
4778 if (isClampZeroToOne(Src1, Src2))
4779 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
4785 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
4786 DAGCombinerInfo &DCI) const {
4787 SDValue Src0 = N->getOperand(0);
4788 SDValue Src1 = N->getOperand(1);
4789 if (Src0.isUndef() && Src1.isUndef())
4790 return DCI.DAG.getUNDEF(N->getValueType(0));
4794 SDValue SITargetLowering::performExtractVectorEltCombine(
4795 SDNode *N, DAGCombinerInfo &DCI) const {
4796 SDValue Vec = N->getOperand(0);
4798 SelectionDAG &DAG= DCI.DAG;
4799 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) {
4801 EVT EltVT = N->getValueType(0);
4802 SDValue Idx = N->getOperand(1);
4803 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4804 Vec.getOperand(0), Idx);
4805 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt);
4812 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
4814 const SDNode *N1) const {
4815 EVT VT = N0->getValueType(0);
4817 // Only do this if we are not trying to support denormals. v_mad_f32 does not
4818 // support denormals ever.
4819 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
4820 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
4823 const TargetOptions &Options = DAG.getTarget().Options;
4824 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
4825 (N0->getFlags().hasUnsafeAlgebra() &&
4826 N1->getFlags().hasUnsafeAlgebra())) &&
4827 isFMAFasterThanFMulAndFAdd(VT)) {
4834 SDValue SITargetLowering::performFAddCombine(SDNode *N,
4835 DAGCombinerInfo &DCI) const {
4836 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4839 SelectionDAG &DAG = DCI.DAG;
4840 EVT VT = N->getValueType(0);
4843 SDValue LHS = N->getOperand(0);
4844 SDValue RHS = N->getOperand(1);
4846 // These should really be instruction patterns, but writing patterns with
4847 // source modiifiers is a pain.
4849 // fadd (fadd (a, a), b) -> mad 2.0, a, b
4850 if (LHS.getOpcode() == ISD::FADD) {
4851 SDValue A = LHS.getOperand(0);
4852 if (A == LHS.getOperand(1)) {
4853 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4855 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4856 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
4861 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
4862 if (RHS.getOpcode() == ISD::FADD) {
4863 SDValue A = RHS.getOperand(0);
4864 if (A == RHS.getOperand(1)) {
4865 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4867 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4868 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
4876 SDValue SITargetLowering::performFSubCombine(SDNode *N,
4877 DAGCombinerInfo &DCI) const {
4878 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4881 SelectionDAG &DAG = DCI.DAG;
4883 EVT VT = N->getValueType(0);
4884 assert(!VT.isVector());
4886 // Try to get the fneg to fold into the source modifier. This undoes generic
4887 // DAG combines and folds them into the mad.
4889 // Only do this if we are not trying to support denormals. v_mad_f32 does
4890 // not support denormals ever.
4891 SDValue LHS = N->getOperand(0);
4892 SDValue RHS = N->getOperand(1);
4893 if (LHS.getOpcode() == ISD::FADD) {
4894 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
4895 SDValue A = LHS.getOperand(0);
4896 if (A == LHS.getOperand(1)) {
4897 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4899 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4900 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4902 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4907 if (RHS.getOpcode() == ISD::FADD) {
4908 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4910 SDValue A = RHS.getOperand(0);
4911 if (A == RHS.getOperand(1)) {
4912 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4914 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4915 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4923 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4924 DAGCombinerInfo &DCI) const {
4925 SelectionDAG &DAG = DCI.DAG;
4928 SDValue LHS = N->getOperand(0);
4929 SDValue RHS = N->getOperand(1);
4930 EVT VT = LHS.getValueType();
4932 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4936 // Match isinf pattern
4937 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4938 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4939 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4940 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4944 const APFloat &APF = CRHS->getValueAPF();
4945 if (APF.isInfinity() && !APF.isNegative()) {
4946 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4947 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4948 DAG.getConstant(Mask, SL, MVT::i32));
4955 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4956 DAGCombinerInfo &DCI) const {
4957 SelectionDAG &DAG = DCI.DAG;
4959 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4961 SDValue Src = N->getOperand(0);
4962 SDValue Srl = N->getOperand(0);
4963 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4964 Srl = Srl.getOperand(0);
4966 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4967 if (Srl.getOpcode() == ISD::SRL) {
4968 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4969 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4970 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4972 if (const ConstantSDNode *C =
4973 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4974 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4977 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4978 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4979 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4985 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4988 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4989 !DCI.isBeforeLegalizeOps());
4990 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4991 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
4992 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
4993 DCI.CommitTargetLoweringOpt(TLO);
4999 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
5000 DAGCombinerInfo &DCI) const {
5001 switch (N->getOpcode()) {
5003 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
5005 return performFAddCombine(N, DCI);
5007 return performFSubCombine(N, DCI);
5009 return performSetCCCombine(N, DCI);
5016 case AMDGPUISD::FMIN_LEGACY:
5017 case AMDGPUISD::FMAX_LEGACY: {
5018 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
5019 getTargetMachine().getOptLevel() > CodeGenOpt::None)
5020 return performMinMaxCombine(N, DCI);
5025 case ISD::ATOMIC_LOAD:
5026 case ISD::ATOMIC_STORE:
5027 case ISD::ATOMIC_CMP_SWAP:
5028 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
5029 case ISD::ATOMIC_SWAP:
5030 case ISD::ATOMIC_LOAD_ADD:
5031 case ISD::ATOMIC_LOAD_SUB:
5032 case ISD::ATOMIC_LOAD_AND:
5033 case ISD::ATOMIC_LOAD_OR:
5034 case ISD::ATOMIC_LOAD_XOR:
5035 case ISD::ATOMIC_LOAD_NAND:
5036 case ISD::ATOMIC_LOAD_MIN:
5037 case ISD::ATOMIC_LOAD_MAX:
5038 case ISD::ATOMIC_LOAD_UMIN:
5039 case ISD::ATOMIC_LOAD_UMAX:
5040 case AMDGPUISD::ATOMIC_INC:
5041 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
5042 if (DCI.isBeforeLegalize())
5044 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
5046 return performAndCombine(N, DCI);
5048 return performOrCombine(N, DCI);
5050 return performXorCombine(N, DCI);
5051 case ISD::ZERO_EXTEND:
5052 return performZeroExtendCombine(N, DCI);
5053 case AMDGPUISD::FP_CLASS:
5054 return performClassCombine(N, DCI);
5055 case ISD::FCANONICALIZE:
5056 return performFCanonicalizeCombine(N, DCI);
5057 case AMDGPUISD::FRACT:
5058 case AMDGPUISD::RCP:
5059 case AMDGPUISD::RSQ:
5060 case AMDGPUISD::RCP_LEGACY:
5061 case AMDGPUISD::RSQ_LEGACY:
5062 case AMDGPUISD::RSQ_CLAMP:
5063 case AMDGPUISD::LDEXP: {
5064 SDValue Src = N->getOperand(0);
5069 case ISD::SINT_TO_FP:
5070 case ISD::UINT_TO_FP:
5071 return performUCharToFloatCombine(N, DCI);
5072 case AMDGPUISD::CVT_F32_UBYTE0:
5073 case AMDGPUISD::CVT_F32_UBYTE1:
5074 case AMDGPUISD::CVT_F32_UBYTE2:
5075 case AMDGPUISD::CVT_F32_UBYTE3:
5076 return performCvtF32UByteNCombine(N, DCI);
5077 case AMDGPUISD::FMED3:
5078 return performFMed3Combine(N, DCI);
5079 case AMDGPUISD::CVT_PKRTZ_F16_F32:
5080 return performCvtPkRTZCombine(N, DCI);
5081 case ISD::SCALAR_TO_VECTOR: {
5082 SelectionDAG &DAG = DCI.DAG;
5083 EVT VT = N->getValueType(0);
5085 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
5086 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
5088 SDValue Src = N->getOperand(0);
5089 EVT EltVT = Src.getValueType();
5090 if (EltVT == MVT::f16)
5091 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
5093 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
5094 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
5099 case ISD::EXTRACT_VECTOR_ELT:
5100 return performExtractVectorEltCombine(N, DCI);
5102 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
5105 /// \brief Helper function for adjustWritemask
5106 static unsigned SubIdx2Lane(unsigned Idx) {
5109 case AMDGPU::sub0: return 0;
5110 case AMDGPU::sub1: return 1;
5111 case AMDGPU::sub2: return 2;
5112 case AMDGPU::sub3: return 3;
5116 /// \brief Adjust the writemask of MIMG instructions
5117 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
5118 SelectionDAG &DAG) const {
5119 SDNode *Users[4] = { };
5121 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
5122 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
5123 unsigned NewDmask = 0;
5125 // Try to figure out the used register components
5126 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
5129 // Don't look at users of the chain.
5130 if (I.getUse().getResNo() != 0)
5133 // Abort if we can't understand the usage
5134 if (!I->isMachineOpcode() ||
5135 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
5138 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
5139 // Note that subregs are packed, i.e. Lane==0 is the first bit set
5140 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
5142 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
5144 // Set which texture component corresponds to the lane.
5146 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
5148 Comp = countTrailingZeros(Dmask);
5149 Dmask &= ~(1 << Comp);
5152 // Abort if we have more than one user per component
5157 NewDmask |= 1 << Comp;
5160 // Abort if there's no change
5161 if (NewDmask == OldDmask)
5164 // Adjust the writemask in the node
5165 std::vector<SDValue> Ops;
5166 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
5167 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
5168 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
5169 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
5171 // If we only got one lane, replace it with a copy
5172 // (if NewDmask has only one bit set...)
5173 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
5174 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
5176 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
5177 SDLoc(), Users[Lane]->getValueType(0),
5178 SDValue(Node, 0), RC);
5179 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
5183 // Update the users of the node with the new indices
5184 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
5185 SDNode *User = Users[i];
5189 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
5190 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
5194 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
5195 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
5196 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
5201 static bool isFrameIndexOp(SDValue Op) {
5202 if (Op.getOpcode() == ISD::AssertZext)
5203 Op = Op.getOperand(0);
5205 return isa<FrameIndexSDNode>(Op);
5208 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
5209 /// with frame index operands.
5210 /// LLVM assumes that inputs are to these instructions are registers.
5211 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
5212 SelectionDAG &DAG) const {
5213 if (Node->getOpcode() == ISD::CopyToReg) {
5214 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
5215 SDValue SrcVal = Node->getOperand(2);
5217 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
5218 // to try understanding copies to physical registers.
5219 if (SrcVal.getValueType() == MVT::i1 &&
5220 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
5222 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
5223 SDValue VReg = DAG.getRegister(
5224 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
5226 SDNode *Glued = Node->getGluedNode();
5228 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
5229 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
5231 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
5232 VReg, ToVReg.getValue(1));
5233 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
5234 DAG.RemoveDeadNode(Node);
5235 return ToResultReg.getNode();
5239 SmallVector<SDValue, 8> Ops;
5240 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
5241 if (!isFrameIndexOp(Node->getOperand(i))) {
5242 Ops.push_back(Node->getOperand(i));
5247 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
5248 Node->getOperand(i).getValueType(),
5249 Node->getOperand(i)), 0));
5252 DAG.UpdateNodeOperands(Node, Ops);
5256 /// \brief Fold the instructions after selecting them.
5257 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
5258 SelectionDAG &DAG) const {
5259 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5260 unsigned Opcode = Node->getMachineOpcode();
5262 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
5263 !TII->isGather4(Opcode))
5264 adjustWritemask(Node, DAG);
5266 if (Opcode == AMDGPU::INSERT_SUBREG ||
5267 Opcode == AMDGPU::REG_SEQUENCE) {
5268 legalizeTargetIndependentNode(Node, DAG);
5274 /// \brief Assign the register class depending on the number of
5275 /// bits set in the writemask
5276 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
5277 SDNode *Node) const {
5278 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5280 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5282 if (TII->isVOP3(MI.getOpcode())) {
5283 // Make sure constant bus requirements are respected.
5284 TII->legalizeOperandsVOP3(MRI, MI);
5288 if (TII->isMIMG(MI)) {
5289 unsigned VReg = MI.getOperand(0).getReg();
5290 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
5291 // TODO: Need mapping tables to handle other cases (register classes).
5292 if (RC != &AMDGPU::VReg_128RegClass)
5295 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
5296 unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
5297 unsigned BitsSet = 0;
5298 for (unsigned i = 0; i < 4; ++i)
5299 BitsSet += Writemask & (1 << i) ? 1 : 0;
5302 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
5303 case 2: RC = &AMDGPU::VReg_64RegClass; break;
5304 case 3: RC = &AMDGPU::VReg_96RegClass; break;
5307 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
5308 MI.setDesc(TII->get(NewOpcode));
5309 MRI.setRegClass(VReg, RC);
5313 // Replace unused atomics with the no return version.
5314 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
5315 if (NoRetAtomicOp != -1) {
5316 if (!Node->hasAnyUseOfValue(0)) {
5317 MI.setDesc(TII->get(NoRetAtomicOp));
5318 MI.RemoveOperand(0);
5322 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
5323 // instruction, because the return type of these instructions is a vec2 of
5324 // the memory type, so it can be tied to the input operand.
5325 // This means these instructions always have a use, so we need to add a
5326 // special case to check if the atomic has only one extract_subreg use,
5327 // which itself has no uses.
5328 if ((Node->hasNUsesOfValue(1, 0) &&
5329 Node->use_begin()->isMachineOpcode() &&
5330 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
5331 !Node->use_begin()->hasAnyUseOfValue(0))) {
5332 unsigned Def = MI.getOperand(0).getReg();
5334 // Change this into a noret atomic.
5335 MI.setDesc(TII->get(NoRetAtomicOp));
5336 MI.RemoveOperand(0);
5338 // If we only remove the def operand from the atomic instruction, the
5339 // extract_subreg will be left with a use of a vreg without a def.
5340 // So we need to insert an implicit_def to avoid machine verifier
5342 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
5343 TII->get(AMDGPU::IMPLICIT_DEF), Def);
5349 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
5351 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
5352 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
5355 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
5357 SDValue Ptr) const {
5358 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5360 // Build the half of the subregister with the constants before building the
5361 // full 128-bit register. If we are building multiple resource descriptors,
5362 // this will allow CSEing of the 2-component register.
5363 const SDValue Ops0[] = {
5364 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
5365 buildSMovImm32(DAG, DL, 0),
5366 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5367 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
5368 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
5371 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
5372 MVT::v2i32, Ops0), 0);
5374 // Combine the constants and the pointer.
5375 const SDValue Ops1[] = {
5376 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5378 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
5380 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
5383 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
5386 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
5387 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
5388 /// of the resource descriptor) to create an offset, which is added to
5389 /// the resource pointer.
5390 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
5391 SDValue Ptr, uint32_t RsrcDword1,
5392 uint64_t RsrcDword2And3) const {
5393 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
5394 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
5396 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
5397 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
5401 SDValue DataLo = buildSMovImm32(DAG, DL,
5402 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
5403 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
5405 const SDValue Ops[] = {
5406 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5408 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5410 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
5412 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
5414 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
5417 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
5420 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
5421 const TargetRegisterClass *RC,
5422 unsigned Reg, EVT VT) const {
5423 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
5425 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
5426 cast<RegisterSDNode>(VReg)->getReg(), VT);
5429 //===----------------------------------------------------------------------===//
5430 // SI Inline Assembly Support
5431 //===----------------------------------------------------------------------===//
5433 std::pair<unsigned, const TargetRegisterClass *>
5434 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
5435 StringRef Constraint,
5437 if (!isTypeLegal(VT))
5438 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5440 if (Constraint.size() == 1) {
5441 switch (Constraint[0]) {
5444 switch (VT.getSizeInBits()) {
5446 return std::make_pair(0U, nullptr);
5449 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
5451 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
5453 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
5455 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
5457 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
5461 switch (VT.getSizeInBits()) {
5463 return std::make_pair(0U, nullptr);
5466 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
5468 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
5470 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
5472 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
5474 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
5476 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
5481 if (Constraint.size() > 1) {
5482 const TargetRegisterClass *RC = nullptr;
5483 if (Constraint[1] == 'v') {
5484 RC = &AMDGPU::VGPR_32RegClass;
5485 } else if (Constraint[1] == 's') {
5486 RC = &AMDGPU::SGPR_32RegClass;
5491 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
5492 if (!Failed && Idx < RC->getNumRegs())
5493 return std::make_pair(RC->getRegister(Idx), RC);
5496 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5499 SITargetLowering::ConstraintType
5500 SITargetLowering::getConstraintType(StringRef Constraint) const {
5501 if (Constraint.size() == 1) {
5502 switch (Constraint[0]) {
5506 return C_RegisterClass;
5509 return TargetLowering::getConstraintType(Constraint);