1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 /// \file 11 /// \brief Custom DAG lowering for SI 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifdef _MSC_VER 16 // Provide M_PI. 17 #define _USE_MATH_DEFINES 18 #include <cmath> 19 #endif 20 21 #include "AMDGPU.h" 22 #include "AMDGPUIntrinsicInfo.h" 23 #include "AMDGPUSubtarget.h" 24 #include "SIISelLowering.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineFunctionInfo.h" 27 #include "SIRegisterInfo.h" 28 #include "llvm/ADT/BitVector.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/CodeGen/CallingConvLower.h" 31 #include "llvm/CodeGen/MachineInstrBuilder.h" 32 #include "llvm/CodeGen/MachineRegisterInfo.h" 33 #include "llvm/CodeGen/SelectionDAG.h" 34 #include "llvm/IR/DiagnosticInfo.h" 35 #include "llvm/IR/Function.h" 36 37 using namespace llvm; 38 39 // -amdgpu-fast-fdiv - Command line option to enable faster 2.5 ulp fdiv. 40 static cl::opt<bool> EnableAMDGPUFastFDIV( 41 "amdgpu-fast-fdiv", 42 cl::desc("Enable faster 2.5 ulp fdiv"), 43 cl::init(false)); 44 45 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 46 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 47 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 48 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 49 return AMDGPU::SGPR0 + Reg; 50 } 51 } 52 llvm_unreachable("Cannot allocate sgpr"); 53 } 54 55 SITargetLowering::SITargetLowering(TargetMachine &TM, 56 const AMDGPUSubtarget &STI) 57 : AMDGPUTargetLowering(TM, STI) { 58 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 59 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 60 61 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 62 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 63 64 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 65 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 66 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 67 68 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 69 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 70 71 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 72 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 73 74 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 75 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 76 77 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 78 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 79 80 computeRegisterProperties(STI.getRegisterInfo()); 81 82 // We need to custom lower vector stores from local memory 83 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 84 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 85 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 86 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 87 setOperationAction(ISD::LOAD, MVT::i1, Custom); 88 89 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 90 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 91 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 92 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 93 setOperationAction(ISD::STORE, MVT::i1, Custom); 94 95 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 96 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 97 setOperationAction(ISD::FrameIndex, MVT::i32, Custom); 98 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 99 100 setOperationAction(ISD::SELECT, MVT::i1, Promote); 101 setOperationAction(ISD::SELECT, MVT::i64, Custom); 102 setOperationAction(ISD::SELECT, MVT::f64, Promote); 103 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 104 105 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 106 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 107 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 108 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 109 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 110 111 setOperationAction(ISD::SETCC, MVT::i1, Promote); 112 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 113 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 114 115 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 116 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 117 118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 125 126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 128 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 129 130 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 131 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 132 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 133 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 134 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 135 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 136 137 // We only support LOAD/STORE and vector manipulation ops for vectors 138 // with > 4 elements. 139 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) { 140 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 141 switch (Op) { 142 case ISD::LOAD: 143 case ISD::STORE: 144 case ISD::BUILD_VECTOR: 145 case ISD::BITCAST: 146 case ISD::EXTRACT_VECTOR_ELT: 147 case ISD::INSERT_VECTOR_ELT: 148 case ISD::INSERT_SUBVECTOR: 149 case ISD::EXTRACT_SUBVECTOR: 150 case ISD::SCALAR_TO_VECTOR: 151 break; 152 case ISD::CONCAT_VECTORS: 153 setOperationAction(Op, VT, Custom); 154 break; 155 default: 156 setOperationAction(Op, VT, Expand); 157 break; 158 } 159 } 160 } 161 162 // Most operations are naturally 32-bit vector operations. We only support 163 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 164 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 165 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 166 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 167 168 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 169 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 170 171 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 172 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 173 174 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 175 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 176 } 177 178 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 179 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 180 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 181 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 182 183 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 184 // and output demarshalling 185 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 186 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 187 188 // We can't return success/failure, only the old value, 189 // let LLVM add the comparison 190 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 191 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 192 193 if (Subtarget->hasFlatAddressSpace()) { 194 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 195 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 196 } 197 198 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 199 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 200 201 // On SI this is s_memtime and s_memrealtime on VI. 202 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 203 204 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 205 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 206 207 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) { 208 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 209 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 210 setOperationAction(ISD::FRINT, MVT::f64, Legal); 211 } 212 213 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 214 215 setOperationAction(ISD::FSIN, MVT::f32, Custom); 216 setOperationAction(ISD::FCOS, MVT::f32, Custom); 217 setOperationAction(ISD::FDIV, MVT::f32, Custom); 218 setOperationAction(ISD::FDIV, MVT::f64, Custom); 219 220 221 setTargetDAGCombine(ISD::FADD); 222 setTargetDAGCombine(ISD::FSUB); 223 setTargetDAGCombine(ISD::FMINNUM); 224 setTargetDAGCombine(ISD::FMAXNUM); 225 setTargetDAGCombine(ISD::SMIN); 226 setTargetDAGCombine(ISD::SMAX); 227 setTargetDAGCombine(ISD::UMIN); 228 setTargetDAGCombine(ISD::UMAX); 229 setTargetDAGCombine(ISD::SETCC); 230 setTargetDAGCombine(ISD::AND); 231 setTargetDAGCombine(ISD::OR); 232 setTargetDAGCombine(ISD::UINT_TO_FP); 233 setTargetDAGCombine(ISD::FCANONICALIZE); 234 235 // All memory operations. Some folding on the pointer operand is done to help 236 // matching the constant offsets in the addressing modes. 237 setTargetDAGCombine(ISD::LOAD); 238 setTargetDAGCombine(ISD::STORE); 239 setTargetDAGCombine(ISD::ATOMIC_LOAD); 240 setTargetDAGCombine(ISD::ATOMIC_STORE); 241 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 242 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 243 setTargetDAGCombine(ISD::ATOMIC_SWAP); 244 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 245 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 246 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 247 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 248 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 249 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 250 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 251 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 252 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 253 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 254 255 setSchedulingPreference(Sched::RegPressure); 256 } 257 258 //===----------------------------------------------------------------------===// 259 // TargetLowering queries 260 //===----------------------------------------------------------------------===// 261 262 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 263 const CallInst &CI, 264 unsigned IntrID) const { 265 switch (IntrID) { 266 case Intrinsic::amdgcn_atomic_inc: 267 case Intrinsic::amdgcn_atomic_dec: 268 Info.opc = ISD::INTRINSIC_W_CHAIN; 269 Info.memVT = MVT::getVT(CI.getType()); 270 Info.ptrVal = CI.getOperand(0); 271 Info.align = 0; 272 Info.vol = false; 273 Info.readMem = true; 274 Info.writeMem = true; 275 return true; 276 default: 277 return false; 278 } 279 } 280 281 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &, 282 EVT) const { 283 // SI has some legal vector types, but no legal vector operations. Say no 284 // shuffles are legal in order to prefer scalarizing some vector operations. 285 return false; 286 } 287 288 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 289 // Flat instructions do not have offsets, and only have the register 290 // address. 291 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1); 292 } 293 294 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 295 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 296 // additionally can do r + r + i with addr64. 32-bit has more addressing 297 // mode options. Depending on the resource constant, it can also do 298 // (i64 r0) + (i32 r1) * (i14 i). 299 // 300 // Private arrays end up using a scratch buffer most of the time, so also 301 // assume those use MUBUF instructions. Scratch loads / stores are currently 302 // implemented as mubuf instructions with offen bit set, so slightly 303 // different than the normal addr64. 304 if (!isUInt<12>(AM.BaseOffs)) 305 return false; 306 307 // FIXME: Since we can split immediate into soffset and immediate offset, 308 // would it make sense to allow any immediate? 309 310 switch (AM.Scale) { 311 case 0: // r + i or just i, depending on HasBaseReg. 312 return true; 313 case 1: 314 return true; // We have r + r or r + i. 315 case 2: 316 if (AM.HasBaseReg) { 317 // Reject 2 * r + r. 318 return false; 319 } 320 321 // Allow 2 * r as r + r 322 // Or 2 * r + i is allowed as r + r + i. 323 return true; 324 default: // Don't allow n * r 325 return false; 326 } 327 } 328 329 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 330 const AddrMode &AM, Type *Ty, 331 unsigned AS) const { 332 // No global is ever allowed as a base. 333 if (AM.BaseGV) 334 return false; 335 336 switch (AS) { 337 case AMDGPUAS::GLOBAL_ADDRESS: { 338 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 339 // Assume the we will use FLAT for all global memory accesses 340 // on VI. 341 // FIXME: This assumption is currently wrong. On VI we still use 342 // MUBUF instructions for the r + i addressing mode. As currently 343 // implemented, the MUBUF instructions only work on buffer < 4GB. 344 // It may be possible to support > 4GB buffers with MUBUF instructions, 345 // by setting the stride value in the resource descriptor which would 346 // increase the size limit to (stride * 4GB). However, this is risky, 347 // because it has never been validated. 348 return isLegalFlatAddressingMode(AM); 349 } 350 351 return isLegalMUBUFAddressingMode(AM); 352 } 353 case AMDGPUAS::CONSTANT_ADDRESS: { 354 // If the offset isn't a multiple of 4, it probably isn't going to be 355 // correctly aligned. 356 if (AM.BaseOffs % 4 != 0) 357 return isLegalMUBUFAddressingMode(AM); 358 359 // There are no SMRD extloads, so if we have to do a small type access we 360 // will use a MUBUF load. 361 // FIXME?: We also need to do this if unaligned, but we don't know the 362 // alignment here. 363 if (DL.getTypeStoreSize(Ty) < 4) 364 return isLegalMUBUFAddressingMode(AM); 365 366 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 367 // SMRD instructions have an 8-bit, dword offset on SI. 368 if (!isUInt<8>(AM.BaseOffs / 4)) 369 return false; 370 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 371 // On CI+, this can also be a 32-bit literal constant offset. If it fits 372 // in 8-bits, it can use a smaller encoding. 373 if (!isUInt<32>(AM.BaseOffs / 4)) 374 return false; 375 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) { 376 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 377 if (!isUInt<20>(AM.BaseOffs)) 378 return false; 379 } else 380 llvm_unreachable("unhandled generation"); 381 382 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 383 return true; 384 385 if (AM.Scale == 1 && AM.HasBaseReg) 386 return true; 387 388 return false; 389 } 390 391 case AMDGPUAS::PRIVATE_ADDRESS: 392 return isLegalMUBUFAddressingMode(AM); 393 394 case AMDGPUAS::LOCAL_ADDRESS: 395 case AMDGPUAS::REGION_ADDRESS: { 396 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 397 // field. 398 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 399 // an 8-bit dword offset but we don't know the alignment here. 400 if (!isUInt<16>(AM.BaseOffs)) 401 return false; 402 403 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 404 return true; 405 406 if (AM.Scale == 1 && AM.HasBaseReg) 407 return true; 408 409 return false; 410 } 411 case AMDGPUAS::FLAT_ADDRESS: 412 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE: 413 // For an unknown address space, this usually means that this is for some 414 // reason being used for pure arithmetic, and not based on some addressing 415 // computation. We don't have instructions that compute pointers with any 416 // addressing modes, so treat them as having no offset like flat 417 // instructions. 418 return isLegalFlatAddressingMode(AM); 419 420 default: 421 llvm_unreachable("unhandled address space"); 422 } 423 } 424 425 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 426 unsigned AddrSpace, 427 unsigned Align, 428 bool *IsFast) const { 429 if (IsFast) 430 *IsFast = false; 431 432 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 433 // which isn't a simple VT. 434 if (!VT.isSimple() || VT == MVT::Other) 435 return false; 436 437 // TODO - CI+ supports unaligned memory accesses, but this requires driver 438 // support. 439 440 // XXX - The only mention I see of this in the ISA manual is for LDS direct 441 // reads the "byte address and must be dword aligned". Is it also true for the 442 // normal loads and stores? 443 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) { 444 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 445 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 446 // with adjacent offsets. 447 bool AlignedBy4 = (Align % 4 == 0); 448 if (IsFast) 449 *IsFast = AlignedBy4; 450 return AlignedBy4; 451 } 452 453 // Smaller than dword value must be aligned. 454 // FIXME: This should be allowed on CI+ 455 if (VT.bitsLT(MVT::i32)) 456 return false; 457 458 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 459 // byte-address are ignored, thus forcing Dword alignment. 460 // This applies to private, global, and constant memory. 461 if (IsFast) 462 *IsFast = true; 463 464 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 465 } 466 467 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 468 unsigned SrcAlign, bool IsMemset, 469 bool ZeroMemset, 470 bool MemcpyStrSrc, 471 MachineFunction &MF) const { 472 // FIXME: Should account for address space here. 473 474 // The default fallback uses the private pointer size as a guess for a type to 475 // use. Make sure we switch these to 64-bit accesses. 476 477 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 478 return MVT::v4i32; 479 480 if (Size >= 8 && DstAlign >= 4) 481 return MVT::v2i32; 482 483 // Use the default. 484 return MVT::Other; 485 } 486 487 static bool isFlatGlobalAddrSpace(unsigned AS) { 488 return AS == AMDGPUAS::GLOBAL_ADDRESS || 489 AS == AMDGPUAS::FLAT_ADDRESS || 490 AS == AMDGPUAS::CONSTANT_ADDRESS; 491 } 492 493 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 494 unsigned DestAS) const { 495 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 496 } 497 498 499 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 500 const MemSDNode *MemNode = cast<MemSDNode>(N); 501 const Value *Ptr = MemNode->getMemOperand()->getValue(); 502 503 // UndefValue means this is a load of a kernel input. These are uniform. 504 // Sometimes LDS instructions have constant pointers 505 if (isa<UndefValue>(Ptr) || isa<Argument>(Ptr) || isa<Constant>(Ptr) || 506 isa<GlobalValue>(Ptr)) 507 return true; 508 509 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 510 return I && I->getMetadata("amdgpu.uniform"); 511 } 512 513 TargetLoweringBase::LegalizeTypeAction 514 SITargetLowering::getPreferredVectorAction(EVT VT) const { 515 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 516 return TypeSplitVector; 517 518 return TargetLoweringBase::getPreferredVectorAction(VT); 519 } 520 521 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 522 Type *Ty) const { 523 const SIInstrInfo *TII = 524 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 525 return TII->isInlineConstant(Imm); 526 } 527 528 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 529 530 // SimplifySetCC uses this function to determine whether or not it should 531 // create setcc with i1 operands. We don't have instructions for i1 setcc. 532 if (VT == MVT::i1 && Op == ISD::SETCC) 533 return false; 534 535 return TargetLowering::isTypeDesirableForOp(Op, VT); 536 } 537 538 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT, 539 const SDLoc &SL, SDValue Chain, 540 unsigned Offset, bool Signed) const { 541 const DataLayout &DL = DAG.getDataLayout(); 542 MachineFunction &MF = DAG.getMachineFunction(); 543 const SIRegisterInfo *TRI = 544 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 545 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 546 547 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 548 549 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 550 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 551 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 552 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 553 MRI.getLiveInVirtReg(InputPtrReg), PtrVT); 554 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 555 DAG.getConstant(Offset, SL, PtrVT)); 556 SDValue PtrOffset = DAG.getUNDEF(PtrVT); 557 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 558 559 unsigned Align = DL.getABITypeAlignment(Ty); 560 561 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 562 if (MemVT.isFloatingPoint()) 563 ExtTy = ISD::EXTLOAD; 564 565 return DAG.getLoad(ISD::UNINDEXED, ExtTy, 566 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT, 567 false, // isVolatile 568 true, // isNonTemporal 569 true, // isInvariant 570 Align); // Alignment 571 } 572 573 SDValue SITargetLowering::LowerFormalArguments( 574 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 575 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 576 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 577 const SIRegisterInfo *TRI = 578 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo()); 579 580 MachineFunction &MF = DAG.getMachineFunction(); 581 FunctionType *FType = MF.getFunction()->getFunctionType(); 582 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 583 const AMDGPUSubtarget &ST = MF.getSubtarget<AMDGPUSubtarget>(); 584 585 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 586 const Function *Fn = MF.getFunction(); 587 DiagnosticInfoUnsupported NoGraphicsHSA( 588 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 589 DAG.getContext()->diagnose(NoGraphicsHSA); 590 return DAG.getEntryNode(); 591 } 592 593 SmallVector<ISD::InputArg, 16> Splits; 594 BitVector Skipped(Ins.size()); 595 596 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) { 597 const ISD::InputArg &Arg = Ins[i]; 598 599 // First check if it's a PS input addr 600 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 601 !Arg.Flags.isByVal() && PSInputNum <= 15) { 602 603 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 604 // We can safely skip PS inputs 605 Skipped.set(i); 606 ++PSInputNum; 607 continue; 608 } 609 610 Info->markPSInputAllocated(PSInputNum); 611 if (Arg.Used) 612 Info->PSInputEna |= 1 << PSInputNum; 613 614 ++PSInputNum; 615 } 616 617 if (AMDGPU::isShader(CallConv)) { 618 // Second split vertices into their elements 619 if (Arg.VT.isVector()) { 620 ISD::InputArg NewArg = Arg; 621 NewArg.Flags.setSplit(); 622 NewArg.VT = Arg.VT.getVectorElementType(); 623 624 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 625 // three or five element vertex only needs three or five registers, 626 // NOT four or eight. 627 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 628 unsigned NumElements = ParamType->getVectorNumElements(); 629 630 for (unsigned j = 0; j != NumElements; ++j) { 631 Splits.push_back(NewArg); 632 NewArg.PartOffset += NewArg.VT.getStoreSize(); 633 } 634 } else { 635 Splits.push_back(Arg); 636 } 637 } 638 } 639 640 SmallVector<CCValAssign, 16> ArgLocs; 641 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 642 *DAG.getContext()); 643 644 // At least one interpolation mode must be enabled or else the GPU will hang. 645 // 646 // Check PSInputAddr instead of PSInputEna. The idea is that if the user set 647 // PSInputAddr, the user wants to enable some bits after the compilation 648 // based on run-time states. Since we can't know what the final PSInputEna 649 // will look like, so we shouldn't do anything here and the user should take 650 // responsibility for the correct programming. 651 // 652 // Otherwise, the following restrictions apply: 653 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 654 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 655 // enabled too. 656 if (CallConv == CallingConv::AMDGPU_PS && 657 ((Info->getPSInputAddr() & 0x7F) == 0 || 658 ((Info->getPSInputAddr() & 0xF) == 0 && 659 Info->isPSInputAllocated(11)))) { 660 CCInfo.AllocateReg(AMDGPU::VGPR0); 661 CCInfo.AllocateReg(AMDGPU::VGPR1); 662 Info->markPSInputAllocated(0); 663 Info->PSInputEna |= 1; 664 } 665 666 if (!AMDGPU::isShader(CallConv)) { 667 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins, 668 Splits); 669 670 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 671 } else { 672 assert(!Info->hasPrivateSegmentBuffer() && !Info->hasDispatchPtr() && 673 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 674 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 675 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 676 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 677 !Info->hasWorkItemIDZ()); 678 } 679 680 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 681 if (Info->hasPrivateSegmentBuffer()) { 682 unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI); 683 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass); 684 CCInfo.AllocateReg(PrivateSegmentBufferReg); 685 } 686 687 if (Info->hasDispatchPtr()) { 688 unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI); 689 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass); 690 CCInfo.AllocateReg(DispatchPtrReg); 691 } 692 693 if (Info->hasQueuePtr()) { 694 unsigned QueuePtrReg = Info->addQueuePtr(*TRI); 695 MF.addLiveIn(QueuePtrReg, &AMDGPU::SReg_64RegClass); 696 CCInfo.AllocateReg(QueuePtrReg); 697 } 698 699 if (Info->hasKernargSegmentPtr()) { 700 unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI); 701 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass); 702 CCInfo.AllocateReg(InputPtrReg); 703 } 704 705 if (Info->hasFlatScratchInit()) { 706 unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI); 707 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SReg_64RegClass); 708 CCInfo.AllocateReg(FlatScratchInitReg); 709 } 710 711 AnalyzeFormalArguments(CCInfo, Splits); 712 713 SmallVector<SDValue, 16> Chains; 714 715 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 716 717 const ISD::InputArg &Arg = Ins[i]; 718 if (Skipped[i]) { 719 InVals.push_back(DAG.getUNDEF(Arg.VT)); 720 continue; 721 } 722 723 CCValAssign &VA = ArgLocs[ArgIdx++]; 724 MVT VT = VA.getLocVT(); 725 726 if (VA.isMemLoc()) { 727 VT = Ins[i].VT; 728 EVT MemVT = Splits[i].VT; 729 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() + 730 VA.getLocMemOffset(); 731 // The first 36 bytes of the input buffer contains information about 732 // thread group and global sizes. 733 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain, 734 Offset, Ins[i].Flags.isSExt()); 735 Chains.push_back(Arg.getValue(1)); 736 737 auto *ParamTy = 738 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 739 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 740 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 741 // On SI local pointers are just offsets into LDS, so they are always 742 // less than 16-bits. On CI and newer they could potentially be 743 // real pointers, so we can't guarantee their size. 744 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 745 DAG.getValueType(MVT::i16)); 746 } 747 748 InVals.push_back(Arg); 749 Info->ABIArgOffset = Offset + MemVT.getStoreSize(); 750 continue; 751 } 752 assert(VA.isRegLoc() && "Parameter must be in a register!"); 753 754 unsigned Reg = VA.getLocReg(); 755 756 if (VT == MVT::i64) { 757 // For now assume it is a pointer 758 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, 759 &AMDGPU::SReg_64RegClass); 760 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass); 761 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 762 InVals.push_back(Copy); 763 continue; 764 } 765 766 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 767 768 Reg = MF.addLiveIn(Reg, RC); 769 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 770 771 if (Arg.VT.isVector()) { 772 773 // Build a vector from the registers 774 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 775 unsigned NumElements = ParamType->getVectorNumElements(); 776 777 SmallVector<SDValue, 4> Regs; 778 Regs.push_back(Val); 779 for (unsigned j = 1; j != NumElements; ++j) { 780 Reg = ArgLocs[ArgIdx++].getLocReg(); 781 Reg = MF.addLiveIn(Reg, RC); 782 783 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 784 Regs.push_back(Copy); 785 } 786 787 // Fill up the missing vector elements 788 NumElements = Arg.VT.getVectorNumElements() - NumElements; 789 Regs.append(NumElements, DAG.getUNDEF(VT)); 790 791 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 792 continue; 793 } 794 795 InVals.push_back(Val); 796 } 797 798 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 799 // these from the dispatch pointer. 800 801 // Start adding system SGPRs. 802 if (Info->hasWorkGroupIDX()) { 803 unsigned Reg = Info->addWorkGroupIDX(); 804 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 805 CCInfo.AllocateReg(Reg); 806 } 807 808 if (Info->hasWorkGroupIDY()) { 809 unsigned Reg = Info->addWorkGroupIDY(); 810 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 811 CCInfo.AllocateReg(Reg); 812 } 813 814 if (Info->hasWorkGroupIDZ()) { 815 unsigned Reg = Info->addWorkGroupIDZ(); 816 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 817 CCInfo.AllocateReg(Reg); 818 } 819 820 if (Info->hasWorkGroupInfo()) { 821 unsigned Reg = Info->addWorkGroupInfo(); 822 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 823 CCInfo.AllocateReg(Reg); 824 } 825 826 if (Info->hasPrivateSegmentWaveByteOffset()) { 827 // Scratch wave offset passed in system SGPR. 828 unsigned PrivateSegmentWaveByteOffsetReg; 829 830 if (AMDGPU::isShader(CallConv)) { 831 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 832 Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 833 } else 834 PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset(); 835 836 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 837 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 838 } 839 840 // Now that we've figured out where the scratch register inputs are, see if 841 // should reserve the arguments and use them directly. 842 bool HasStackObjects = MF.getFrameInfo()->hasStackObjects(); 843 // Record that we know we have non-spill stack objects so we don't need to 844 // check all stack objects later. 845 if (HasStackObjects) 846 Info->setHasNonSpillStackObjects(true); 847 848 if (ST.isAmdHsaOS()) { 849 // TODO: Assume we will spill without optimizations. 850 if (HasStackObjects) { 851 // If we have stack objects, we unquestionably need the private buffer 852 // resource. For the HSA ABI, this will be the first 4 user SGPR 853 // inputs. We can reserve those and use them directly. 854 855 unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue( 856 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER); 857 Info->setScratchRSrcReg(PrivateSegmentBufferReg); 858 859 unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue( 860 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 861 Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 862 } else { 863 unsigned ReservedBufferReg 864 = TRI->reservedPrivateSegmentBufferReg(MF); 865 unsigned ReservedOffsetReg 866 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 867 868 // We tentatively reserve the last registers (skipping the last two 869 // which may contain VCC). After register allocation, we'll replace 870 // these with the ones immediately after those which were really 871 // allocated. In the prologue copies will be inserted from the argument 872 // to these reserved registers. 873 Info->setScratchRSrcReg(ReservedBufferReg); 874 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 875 } 876 } else { 877 unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF); 878 879 // Without HSA, relocations are used for the scratch pointer and the 880 // buffer resource setup is always inserted in the prologue. Scratch wave 881 // offset is still in an input SGPR. 882 Info->setScratchRSrcReg(ReservedBufferReg); 883 884 if (HasStackObjects) { 885 unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue( 886 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 887 Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg); 888 } else { 889 unsigned ReservedOffsetReg 890 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 891 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 892 } 893 } 894 895 if (Info->hasWorkItemIDX()) { 896 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X); 897 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 898 CCInfo.AllocateReg(Reg); 899 } 900 901 if (Info->hasWorkItemIDY()) { 902 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y); 903 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 904 CCInfo.AllocateReg(Reg); 905 } 906 907 if (Info->hasWorkItemIDZ()) { 908 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z); 909 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 910 CCInfo.AllocateReg(Reg); 911 } 912 913 if (Chains.empty()) 914 return Chain; 915 916 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 917 } 918 919 SDValue 920 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 921 bool isVarArg, 922 const SmallVectorImpl<ISD::OutputArg> &Outs, 923 const SmallVectorImpl<SDValue> &OutVals, 924 const SDLoc &DL, SelectionDAG &DAG) const { 925 MachineFunction &MF = DAG.getMachineFunction(); 926 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 927 928 if (!AMDGPU::isShader(CallConv)) 929 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 930 OutVals, DL, DAG); 931 932 Info->setIfReturnsVoid(Outs.size() == 0); 933 934 SmallVector<ISD::OutputArg, 48> Splits; 935 SmallVector<SDValue, 48> SplitVals; 936 937 // Split vectors into their elements. 938 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 939 const ISD::OutputArg &Out = Outs[i]; 940 941 if (Out.VT.isVector()) { 942 MVT VT = Out.VT.getVectorElementType(); 943 ISD::OutputArg NewOut = Out; 944 NewOut.Flags.setSplit(); 945 NewOut.VT = VT; 946 947 // We want the original number of vector elements here, e.g. 948 // three or five, not four or eight. 949 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 950 951 for (unsigned j = 0; j != NumElements; ++j) { 952 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 953 DAG.getConstant(j, DL, MVT::i32)); 954 SplitVals.push_back(Elem); 955 Splits.push_back(NewOut); 956 NewOut.PartOffset += NewOut.VT.getStoreSize(); 957 } 958 } else { 959 SplitVals.push_back(OutVals[i]); 960 Splits.push_back(Out); 961 } 962 } 963 964 // CCValAssign - represent the assignment of the return value to a location. 965 SmallVector<CCValAssign, 48> RVLocs; 966 967 // CCState - Info about the registers and stack slots. 968 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 969 *DAG.getContext()); 970 971 // Analyze outgoing return values. 972 AnalyzeReturn(CCInfo, Splits); 973 974 SDValue Flag; 975 SmallVector<SDValue, 48> RetOps; 976 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 977 978 // Copy the result values into the output registers. 979 for (unsigned i = 0, realRVLocIdx = 0; 980 i != RVLocs.size(); 981 ++i, ++realRVLocIdx) { 982 CCValAssign &VA = RVLocs[i]; 983 assert(VA.isRegLoc() && "Can only return in registers!"); 984 985 SDValue Arg = SplitVals[realRVLocIdx]; 986 987 // Copied from other backends. 988 switch (VA.getLocInfo()) { 989 default: llvm_unreachable("Unknown loc info!"); 990 case CCValAssign::Full: 991 break; 992 case CCValAssign::BCvt: 993 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 994 break; 995 } 996 997 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 998 Flag = Chain.getValue(1); 999 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1000 } 1001 1002 // Update chain and glue. 1003 RetOps[0] = Chain; 1004 if (Flag.getNode()) 1005 RetOps.push_back(Flag); 1006 1007 return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, RetOps); 1008 } 1009 1010 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 1011 SelectionDAG &DAG) const { 1012 unsigned Reg = StringSwitch<unsigned>(RegName) 1013 .Case("m0", AMDGPU::M0) 1014 .Case("exec", AMDGPU::EXEC) 1015 .Case("exec_lo", AMDGPU::EXEC_LO) 1016 .Case("exec_hi", AMDGPU::EXEC_HI) 1017 .Case("flat_scratch", AMDGPU::FLAT_SCR) 1018 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 1019 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 1020 .Default(AMDGPU::NoRegister); 1021 1022 if (Reg == AMDGPU::NoRegister) { 1023 report_fatal_error(Twine("invalid register name \"" 1024 + StringRef(RegName) + "\".")); 1025 1026 } 1027 1028 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 1029 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 1030 report_fatal_error(Twine("invalid register \"" 1031 + StringRef(RegName) + "\" for subtarget.")); 1032 } 1033 1034 switch (Reg) { 1035 case AMDGPU::M0: 1036 case AMDGPU::EXEC_LO: 1037 case AMDGPU::EXEC_HI: 1038 case AMDGPU::FLAT_SCR_LO: 1039 case AMDGPU::FLAT_SCR_HI: 1040 if (VT.getSizeInBits() == 32) 1041 return Reg; 1042 break; 1043 case AMDGPU::EXEC: 1044 case AMDGPU::FLAT_SCR: 1045 if (VT.getSizeInBits() == 64) 1046 return Reg; 1047 break; 1048 default: 1049 llvm_unreachable("missing register type checking"); 1050 } 1051 1052 report_fatal_error(Twine("invalid type for register \"" 1053 + StringRef(RegName) + "\".")); 1054 } 1055 1056 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 1057 MachineInstr *MI, MachineBasicBlock *BB) const { 1058 switch (MI->getOpcode()) { 1059 case AMDGPU::SI_INIT_M0: { 1060 const SIInstrInfo *TII = 1061 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 1062 BuildMI(*BB, MI->getIterator(), MI->getDebugLoc(), 1063 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1064 .addOperand(MI->getOperand(0)); 1065 MI->eraseFromParent(); 1066 break; 1067 } 1068 case AMDGPU::BRANCH: 1069 return BB; 1070 case AMDGPU::GET_GROUPSTATICSIZE: { 1071 const SIInstrInfo *TII = 1072 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 1073 MachineFunction *MF = BB->getParent(); 1074 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 1075 DebugLoc DL = MI->getDebugLoc(); 1076 BuildMI (*BB, MI, DL, TII->get(AMDGPU::S_MOVK_I32)) 1077 .addOperand(MI->getOperand(0)) 1078 .addImm(MFI->LDSSize); 1079 MI->eraseFromParent(); 1080 return BB; 1081 } 1082 default: 1083 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 1084 } 1085 return BB; 1086 } 1087 1088 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1089 // This currently forces unfolding various combinations of fsub into fma with 1090 // free fneg'd operands. As long as we have fast FMA (controlled by 1091 // isFMAFasterThanFMulAndFAdd), we should perform these. 1092 1093 // When fma is quarter rate, for f64 where add / sub are at best half rate, 1094 // most of these combines appear to be cycle neutral but save on instruction 1095 // count / code size. 1096 return true; 1097 } 1098 1099 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 1100 EVT VT) const { 1101 if (!VT.isVector()) { 1102 return MVT::i1; 1103 } 1104 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 1105 } 1106 1107 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const { 1108 return MVT::i32; 1109 } 1110 1111 // Answering this is somewhat tricky and depends on the specific device which 1112 // have different rates for fma or all f64 operations. 1113 // 1114 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 1115 // regardless of which device (although the number of cycles differs between 1116 // devices), so it is always profitable for f64. 1117 // 1118 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 1119 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 1120 // which we can always do even without fused FP ops since it returns the same 1121 // result as the separate operations and since it is always full 1122 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 1123 // however does not support denormals, so we do report fma as faster if we have 1124 // a fast fma device and require denormals. 1125 // 1126 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 1127 VT = VT.getScalarType(); 1128 1129 if (!VT.isSimple()) 1130 return false; 1131 1132 switch (VT.getSimpleVT().SimpleTy) { 1133 case MVT::f32: 1134 // This is as fast on some subtargets. However, we always have full rate f32 1135 // mad available which returns the same result as the separate operations 1136 // which we should prefer over fma. We can't use this if we want to support 1137 // denormals, so only report this in these cases. 1138 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 1139 case MVT::f64: 1140 return true; 1141 default: 1142 break; 1143 } 1144 1145 return false; 1146 } 1147 1148 //===----------------------------------------------------------------------===// 1149 // Custom DAG Lowering Operations 1150 //===----------------------------------------------------------------------===// 1151 1152 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 1153 switch (Op.getOpcode()) { 1154 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 1155 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG); 1156 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 1157 case ISD::LOAD: { 1158 SDValue Result = LowerLOAD(Op, DAG); 1159 assert((!Result.getNode() || 1160 Result.getNode()->getNumValues() == 2) && 1161 "Load should return a value and a chain"); 1162 return Result; 1163 } 1164 1165 case ISD::FSIN: 1166 case ISD::FCOS: 1167 return LowerTrig(Op, DAG); 1168 case ISD::SELECT: return LowerSELECT(Op, DAG); 1169 case ISD::FDIV: return LowerFDIV(Op, DAG); 1170 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 1171 case ISD::STORE: return LowerSTORE(Op, DAG); 1172 case ISD::GlobalAddress: { 1173 MachineFunction &MF = DAG.getMachineFunction(); 1174 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1175 return LowerGlobalAddress(MFI, Op, DAG); 1176 } 1177 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 1178 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 1179 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 1180 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 1181 } 1182 return SDValue(); 1183 } 1184 1185 /// \brief Helper function for LowerBRCOND 1186 static SDNode *findUser(SDValue Value, unsigned Opcode) { 1187 1188 SDNode *Parent = Value.getNode(); 1189 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 1190 I != E; ++I) { 1191 1192 if (I.getUse().get() != Value) 1193 continue; 1194 1195 if (I->getOpcode() == Opcode) 1196 return *I; 1197 } 1198 return nullptr; 1199 } 1200 1201 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const { 1202 1203 SDLoc SL(Op); 1204 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op); 1205 unsigned FrameIndex = FINode->getIndex(); 1206 1207 // A FrameIndex node represents a 32-bit offset into scratch memory. If the 1208 // high bit of a frame index offset were to be set, this would mean that it 1209 // represented an offset of ~2GB * 64 = ~128GB from the start of the scratch 1210 // buffer, with 64 being the number of threads per wave. 1211 // 1212 // The maximum private allocation for the entire GPU is 4G, and we are 1213 // concerned with the largest the index could ever be for an individual 1214 // workitem. This will occur with the minmum dispatch size. If a program 1215 // requires more, the dispatch size will be reduced. 1216 // 1217 // With this limit, we can mark the high bit of the FrameIndex node as known 1218 // zero, which is important, because it means in most situations we can prove 1219 // that values derived from FrameIndex nodes are non-negative. This enables us 1220 // to take advantage of more addressing modes when accessing scratch buffers, 1221 // since for scratch reads/writes, the register offset must always be 1222 // positive. 1223 1224 uint64_t MaxGPUAlloc = UINT64_C(4) * 1024 * 1024 * 1024; 1225 1226 // XXX - It is unclear if partial dispatch works. Assume it works at half wave 1227 // granularity. It is probably a full wave. 1228 uint64_t MinGranularity = 32; 1229 1230 unsigned KnownBits = Log2_64(MaxGPUAlloc / MinGranularity); 1231 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), KnownBits); 1232 1233 SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32); 1234 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI, 1235 DAG.getValueType(ExtVT)); 1236 } 1237 1238 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 1239 if (Intr->getOpcode() != ISD::INTRINSIC_W_CHAIN) 1240 return false; 1241 1242 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 1243 default: return false; 1244 case AMDGPUIntrinsic::amdgcn_if: 1245 case AMDGPUIntrinsic::amdgcn_else: 1246 case AMDGPUIntrinsic::amdgcn_break: 1247 case AMDGPUIntrinsic::amdgcn_if_break: 1248 case AMDGPUIntrinsic::amdgcn_else_break: 1249 case AMDGPUIntrinsic::amdgcn_loop: 1250 case AMDGPUIntrinsic::amdgcn_end_cf: 1251 return true; 1252 } 1253 } 1254 1255 /// This transforms the control flow intrinsics to get the branch destination as 1256 /// last parameter, also switches branch target with BR if the need arise 1257 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 1258 SelectionDAG &DAG) const { 1259 1260 SDLoc DL(BRCOND); 1261 1262 SDNode *Intr = BRCOND.getOperand(1).getNode(); 1263 SDValue Target = BRCOND.getOperand(2); 1264 SDNode *BR = nullptr; 1265 SDNode *SetCC = nullptr; 1266 1267 if (Intr->getOpcode() == ISD::SETCC) { 1268 // As long as we negate the condition everything is fine 1269 SetCC = Intr; 1270 Intr = SetCC->getOperand(0).getNode(); 1271 1272 } else { 1273 // Get the target from BR if we don't negate the condition 1274 BR = findUser(BRCOND, ISD::BR); 1275 Target = BR->getOperand(1); 1276 } 1277 1278 if (!isCFIntrinsic(Intr)) { 1279 // This is a uniform branch so we don't need to legalize. 1280 return BRCOND; 1281 } 1282 1283 assert(!SetCC || 1284 (SetCC->getConstantOperandVal(1) == 1 && 1285 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 1286 ISD::SETNE)); 1287 1288 // Build the result and 1289 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 1290 1291 // operands of the new intrinsic call 1292 SmallVector<SDValue, 4> Ops; 1293 Ops.push_back(BRCOND.getOperand(0)); 1294 Ops.append(Intr->op_begin() + 1, Intr->op_end()); 1295 Ops.push_back(Target); 1296 1297 // build the new intrinsic call 1298 SDNode *Result = DAG.getNode( 1299 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL, 1300 DAG.getVTList(Res), Ops).getNode(); 1301 1302 if (BR) { 1303 // Give the branch instruction our target 1304 SDValue Ops[] = { 1305 BR->getOperand(0), 1306 BRCOND.getOperand(2) 1307 }; 1308 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 1309 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 1310 BR = NewBR.getNode(); 1311 } 1312 1313 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 1314 1315 // Copy the intrinsic results to registers 1316 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 1317 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 1318 if (!CopyToReg) 1319 continue; 1320 1321 Chain = DAG.getCopyToReg( 1322 Chain, DL, 1323 CopyToReg->getOperand(1), 1324 SDValue(Result, i - 1), 1325 SDValue()); 1326 1327 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 1328 } 1329 1330 // Remove the old intrinsic from the chain 1331 DAG.ReplaceAllUsesOfValueWith( 1332 SDValue(Intr, Intr->getNumValues() - 1), 1333 Intr->getOperand(0)); 1334 1335 return Chain; 1336 } 1337 1338 SDValue SITargetLowering::getSegmentAperture(unsigned AS, 1339 SelectionDAG &DAG) const { 1340 SDLoc SL; 1341 MachineFunction &MF = DAG.getMachineFunction(); 1342 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1343 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 1344 assert(UserSGPR != AMDGPU::NoRegister); 1345 1346 SDValue QueuePtr = CreateLiveInRegister( 1347 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 1348 1349 // Offset into amd_queue_t for group_segment_aperture_base_hi / 1350 // private_segment_aperture_base_hi. 1351 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 1352 1353 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr, 1354 DAG.getConstant(StructOffset, SL, MVT::i64)); 1355 1356 // TODO: Use custom target PseudoSourceValue. 1357 // TODO: We should use the value from the IR intrinsic call, but it might not 1358 // be available and how do we get it? 1359 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 1360 AMDGPUAS::CONSTANT_ADDRESS)); 1361 1362 MachinePointerInfo PtrInfo(V, StructOffset); 1363 return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, 1364 PtrInfo, false, 1365 false, true, 1366 MinAlign(64, StructOffset)); 1367 } 1368 1369 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 1370 SelectionDAG &DAG) const { 1371 SDLoc SL(Op); 1372 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 1373 1374 SDValue Src = ASC->getOperand(0); 1375 1376 // FIXME: Really support non-0 null pointers. 1377 SDValue SegmentNullPtr = DAG.getConstant(-1, SL, MVT::i32); 1378 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 1379 1380 // flat -> local/private 1381 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 1382 if (ASC->getDestAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 1383 ASC->getDestAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 1384 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 1385 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 1386 1387 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 1388 NonNull, Ptr, SegmentNullPtr); 1389 } 1390 } 1391 1392 // local/private -> flat 1393 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 1394 if (ASC->getSrcAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 1395 ASC->getSrcAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 1396 SDValue NonNull 1397 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 1398 1399 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG); 1400 SDValue CvtPtr 1401 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 1402 1403 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 1404 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 1405 FlatNullPtr); 1406 } 1407 } 1408 1409 // global <-> flat are no-ops and never emitted. 1410 1411 const MachineFunction &MF = DAG.getMachineFunction(); 1412 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 1413 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 1414 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 1415 1416 return DAG.getUNDEF(ASC->getValueType(0)); 1417 } 1418 1419 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 1420 const SDLoc &DL, SDValue V) const { 1421 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 1422 // the destination register. 1423 // 1424 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 1425 // so we will end up with redundant moves to m0. 1426 // 1427 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 1428 1429 // A Null SDValue creates a glue result. 1430 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 1431 V, Chain); 1432 return SDValue(M0, 0); 1433 } 1434 1435 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 1436 SDValue Op, 1437 MVT VT, 1438 unsigned Offset) const { 1439 SDLoc SL(Op); 1440 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL, 1441 DAG.getEntryNode(), Offset, false); 1442 // The local size values will have the hi 16-bits as zero. 1443 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 1444 DAG.getValueType(VT)); 1445 } 1446 1447 static SDValue emitNonHSAIntrinsicError(SelectionDAG& DAG, EVT VT) { 1448 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 1449 "non-hsa intrinsic with hsa target"); 1450 DAG.getContext()->diagnose(BadIntrin); 1451 return DAG.getUNDEF(VT); 1452 } 1453 1454 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 1455 SelectionDAG &DAG) const { 1456 MachineFunction &MF = DAG.getMachineFunction(); 1457 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 1458 const SIRegisterInfo *TRI = 1459 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo()); 1460 1461 EVT VT = Op.getValueType(); 1462 SDLoc DL(Op); 1463 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1464 1465 // TODO: Should this propagate fast-math-flags? 1466 1467 switch (IntrinsicID) { 1468 case Intrinsic::amdgcn_dispatch_ptr: 1469 case Intrinsic::amdgcn_queue_ptr: { 1470 if (!Subtarget->isAmdHsaOS()) { 1471 DiagnosticInfoUnsupported BadIntrin( 1472 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 1473 DL.getDebugLoc()); 1474 DAG.getContext()->diagnose(BadIntrin); 1475 return DAG.getUNDEF(VT); 1476 } 1477 1478 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 1479 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR; 1480 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, 1481 TRI->getPreloadedValue(MF, Reg), VT); 1482 } 1483 case Intrinsic::amdgcn_kernarg_segment_ptr: { 1484 unsigned Reg 1485 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 1486 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 1487 } 1488 case Intrinsic::amdgcn_rcp: 1489 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 1490 case Intrinsic::amdgcn_rsq: 1491 case AMDGPUIntrinsic::AMDGPU_rsq: // Legacy name 1492 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 1493 case Intrinsic::amdgcn_rsq_clamp: 1494 case AMDGPUIntrinsic::AMDGPU_rsq_clamped: { // Legacy name 1495 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 1496 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 1497 1498 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 1499 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 1500 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 1501 1502 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 1503 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 1504 DAG.getConstantFP(Max, DL, VT)); 1505 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 1506 DAG.getConstantFP(Min, DL, VT)); 1507 } 1508 case Intrinsic::r600_read_ngroups_x: 1509 if (Subtarget->isAmdHsaOS()) 1510 return emitNonHSAIntrinsicError(DAG, VT); 1511 1512 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1513 SI::KernelInputOffsets::NGROUPS_X, false); 1514 case Intrinsic::r600_read_ngroups_y: 1515 if (Subtarget->isAmdHsaOS()) 1516 return emitNonHSAIntrinsicError(DAG, VT); 1517 1518 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1519 SI::KernelInputOffsets::NGROUPS_Y, false); 1520 case Intrinsic::r600_read_ngroups_z: 1521 if (Subtarget->isAmdHsaOS()) 1522 return emitNonHSAIntrinsicError(DAG, VT); 1523 1524 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1525 SI::KernelInputOffsets::NGROUPS_Z, false); 1526 case Intrinsic::r600_read_global_size_x: 1527 if (Subtarget->isAmdHsaOS()) 1528 return emitNonHSAIntrinsicError(DAG, VT); 1529 1530 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1531 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 1532 case Intrinsic::r600_read_global_size_y: 1533 if (Subtarget->isAmdHsaOS()) 1534 return emitNonHSAIntrinsicError(DAG, VT); 1535 1536 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1537 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 1538 case Intrinsic::r600_read_global_size_z: 1539 if (Subtarget->isAmdHsaOS()) 1540 return emitNonHSAIntrinsicError(DAG, VT); 1541 1542 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 1543 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 1544 case Intrinsic::r600_read_local_size_x: 1545 if (Subtarget->isAmdHsaOS()) 1546 return emitNonHSAIntrinsicError(DAG, VT); 1547 1548 return lowerImplicitZextParam(DAG, Op, MVT::i16, 1549 SI::KernelInputOffsets::LOCAL_SIZE_X); 1550 case Intrinsic::r600_read_local_size_y: 1551 if (Subtarget->isAmdHsaOS()) 1552 return emitNonHSAIntrinsicError(DAG, VT); 1553 1554 return lowerImplicitZextParam(DAG, Op, MVT::i16, 1555 SI::KernelInputOffsets::LOCAL_SIZE_Y); 1556 case Intrinsic::r600_read_local_size_z: 1557 if (Subtarget->isAmdHsaOS()) 1558 return emitNonHSAIntrinsicError(DAG, VT); 1559 1560 return lowerImplicitZextParam(DAG, Op, MVT::i16, 1561 SI::KernelInputOffsets::LOCAL_SIZE_Z); 1562 case Intrinsic::amdgcn_read_workdim: 1563 case AMDGPUIntrinsic::AMDGPU_read_workdim: // Legacy name. 1564 // Really only 2 bits. 1565 return lowerImplicitZextParam(DAG, Op, MVT::i8, 1566 getImplicitParameterOffset(MFI, GRID_DIM)); 1567 case Intrinsic::amdgcn_workgroup_id_x: 1568 case Intrinsic::r600_read_tgid_x: 1569 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 1570 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT); 1571 case Intrinsic::amdgcn_workgroup_id_y: 1572 case Intrinsic::r600_read_tgid_y: 1573 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 1574 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT); 1575 case Intrinsic::amdgcn_workgroup_id_z: 1576 case Intrinsic::r600_read_tgid_z: 1577 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 1578 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT); 1579 case Intrinsic::amdgcn_workitem_id_x: 1580 case Intrinsic::r600_read_tidig_x: 1581 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 1582 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT); 1583 case Intrinsic::amdgcn_workitem_id_y: 1584 case Intrinsic::r600_read_tidig_y: 1585 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 1586 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT); 1587 case Intrinsic::amdgcn_workitem_id_z: 1588 case Intrinsic::r600_read_tidig_z: 1589 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 1590 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT); 1591 case AMDGPUIntrinsic::SI_load_const: { 1592 SDValue Ops[] = { 1593 Op.getOperand(1), 1594 Op.getOperand(2) 1595 }; 1596 1597 MachineMemOperand *MMO = MF.getMachineMemOperand( 1598 MachinePointerInfo(), 1599 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant, 1600 VT.getStoreSize(), 4); 1601 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 1602 Op->getVTList(), Ops, VT, MMO); 1603 } 1604 case AMDGPUIntrinsic::SI_vs_load_input: 1605 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT, 1606 Op.getOperand(1), 1607 Op.getOperand(2), 1608 Op.getOperand(3)); 1609 1610 case AMDGPUIntrinsic::SI_fs_constant: { 1611 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3)); 1612 SDValue Glue = M0.getValue(1); 1613 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 1614 DAG.getConstant(2, DL, MVT::i32), // P0 1615 Op.getOperand(1), Op.getOperand(2), Glue); 1616 } 1617 case AMDGPUIntrinsic::SI_packf16: 1618 if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef()) 1619 return DAG.getUNDEF(MVT::i32); 1620 return Op; 1621 case AMDGPUIntrinsic::SI_fs_interp: { 1622 SDValue IJ = Op.getOperand(4); 1623 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ, 1624 DAG.getConstant(0, DL, MVT::i32)); 1625 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ, 1626 DAG.getConstant(1, DL, MVT::i32)); 1627 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3)); 1628 SDValue Glue = M0.getValue(1); 1629 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL, 1630 DAG.getVTList(MVT::f32, MVT::Glue), 1631 I, Op.getOperand(1), Op.getOperand(2), Glue); 1632 Glue = SDValue(P1.getNode(), 1); 1633 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J, 1634 Op.getOperand(1), Op.getOperand(2), Glue); 1635 } 1636 case Intrinsic::amdgcn_interp_p1: { 1637 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 1638 SDValue Glue = M0.getValue(1); 1639 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 1640 Op.getOperand(2), Op.getOperand(3), Glue); 1641 } 1642 case Intrinsic::amdgcn_interp_p2: { 1643 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 1644 SDValue Glue = SDValue(M0.getNode(), 1); 1645 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 1646 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 1647 Glue); 1648 } 1649 case Intrinsic::amdgcn_sin: 1650 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 1651 1652 case Intrinsic::amdgcn_cos: 1653 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 1654 1655 case Intrinsic::amdgcn_log_clamp: { 1656 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 1657 return SDValue(); 1658 1659 DiagnosticInfoUnsupported BadIntrin( 1660 *MF.getFunction(), "intrinsic not supported on subtarget", 1661 DL.getDebugLoc()); 1662 DAG.getContext()->diagnose(BadIntrin); 1663 return DAG.getUNDEF(VT); 1664 } 1665 case Intrinsic::amdgcn_ldexp: 1666 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 1667 Op.getOperand(1), Op.getOperand(2)); 1668 1669 case Intrinsic::amdgcn_fract: 1670 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 1671 1672 case Intrinsic::amdgcn_class: 1673 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 1674 Op.getOperand(1), Op.getOperand(2)); 1675 case Intrinsic::amdgcn_div_fmas: 1676 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 1677 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 1678 Op.getOperand(4)); 1679 1680 case Intrinsic::amdgcn_div_fixup: 1681 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 1682 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 1683 1684 case Intrinsic::amdgcn_trig_preop: 1685 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 1686 Op.getOperand(1), Op.getOperand(2)); 1687 case Intrinsic::amdgcn_div_scale: { 1688 // 3rd parameter required to be a constant. 1689 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 1690 if (!Param) 1691 return DAG.getUNDEF(VT); 1692 1693 // Translate to the operands expected by the machine instruction. The 1694 // first parameter must be the same as the first instruction. 1695 SDValue Numerator = Op.getOperand(1); 1696 SDValue Denominator = Op.getOperand(2); 1697 1698 // Note this order is opposite of the machine instruction's operations, 1699 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 1700 // intrinsic has the numerator as the first operand to match a normal 1701 // division operation. 1702 1703 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 1704 1705 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 1706 Denominator, Numerator); 1707 } 1708 case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte0: 1709 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Op.getOperand(1)); 1710 case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte1: 1711 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE1, DL, VT, Op.getOperand(1)); 1712 case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte2: 1713 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE2, DL, VT, Op.getOperand(1)); 1714 case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte3: 1715 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE3, DL, VT, Op.getOperand(1)); 1716 default: 1717 return AMDGPUTargetLowering::LowerOperation(Op, DAG); 1718 } 1719 } 1720 1721 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 1722 SelectionDAG &DAG) const { 1723 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 1724 switch (IntrID) { 1725 case Intrinsic::amdgcn_atomic_inc: 1726 case Intrinsic::amdgcn_atomic_dec: { 1727 MemSDNode *M = cast<MemSDNode>(Op); 1728 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ? 1729 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC; 1730 SDValue Ops[] = { 1731 M->getOperand(0), // Chain 1732 M->getOperand(2), // Ptr 1733 M->getOperand(3) // Value 1734 }; 1735 1736 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 1737 M->getMemoryVT(), M->getMemOperand()); 1738 } 1739 default: 1740 return SDValue(); 1741 } 1742 } 1743 1744 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 1745 SelectionDAG &DAG) const { 1746 MachineFunction &MF = DAG.getMachineFunction(); 1747 SDLoc DL(Op); 1748 SDValue Chain = Op.getOperand(0); 1749 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 1750 1751 switch (IntrinsicID) { 1752 case AMDGPUIntrinsic::SI_sendmsg: { 1753 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 1754 SDValue Glue = Chain.getValue(1); 1755 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain, 1756 Op.getOperand(2), Glue); 1757 } 1758 case AMDGPUIntrinsic::SI_tbuffer_store: { 1759 SDValue Ops[] = { 1760 Chain, 1761 Op.getOperand(2), 1762 Op.getOperand(3), 1763 Op.getOperand(4), 1764 Op.getOperand(5), 1765 Op.getOperand(6), 1766 Op.getOperand(7), 1767 Op.getOperand(8), 1768 Op.getOperand(9), 1769 Op.getOperand(10), 1770 Op.getOperand(11), 1771 Op.getOperand(12), 1772 Op.getOperand(13), 1773 Op.getOperand(14) 1774 }; 1775 1776 EVT VT = Op.getOperand(3).getValueType(); 1777 1778 MachineMemOperand *MMO = MF.getMachineMemOperand( 1779 MachinePointerInfo(), 1780 MachineMemOperand::MOStore, 1781 VT.getStoreSize(), 4); 1782 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 1783 Op->getVTList(), Ops, VT, MMO); 1784 } 1785 default: 1786 return SDValue(); 1787 } 1788 } 1789 1790 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 1791 SDLoc DL(Op); 1792 LoadSDNode *Load = cast<LoadSDNode>(Op); 1793 ISD::LoadExtType ExtType = Load->getExtensionType(); 1794 EVT MemVT = Load->getMemoryVT(); 1795 1796 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 1797 assert(MemVT == MVT::i1 && "Only i1 non-extloads expected"); 1798 // FIXME: Copied from PPC 1799 // First, load into 32 bits, then truncate to 1 bit. 1800 1801 SDValue Chain = Load->getChain(); 1802 SDValue BasePtr = Load->getBasePtr(); 1803 MachineMemOperand *MMO = Load->getMemOperand(); 1804 1805 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 1806 BasePtr, MVT::i8, MMO); 1807 1808 SDValue Ops[] = { 1809 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 1810 NewLD.getValue(1) 1811 }; 1812 1813 return DAG.getMergeValues(Ops, DL); 1814 } 1815 1816 if (!MemVT.isVector()) 1817 return SDValue(); 1818 1819 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 1820 "Custom lowering for non-i32 vectors hasn't been implemented."); 1821 1822 unsigned AS = Load->getAddressSpace(); 1823 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 1824 AS, Load->getAlignment())) { 1825 SDValue Ops[2]; 1826 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 1827 return DAG.getMergeValues(Ops, DL); 1828 } 1829 1830 unsigned NumElements = MemVT.getVectorNumElements(); 1831 switch (AS) { 1832 case AMDGPUAS::CONSTANT_ADDRESS: 1833 if (isMemOpUniform(Load)) 1834 return SDValue(); 1835 // Non-uniform loads will be selected to MUBUF instructions, so they 1836 // have the same legalization requires ments as global and private 1837 // loads. 1838 // 1839 // Fall-through 1840 case AMDGPUAS::GLOBAL_ADDRESS: 1841 case AMDGPUAS::FLAT_ADDRESS: 1842 if (NumElements > 4) 1843 return SplitVectorLoad(Op, DAG); 1844 // v4 loads are supported for private and global memory. 1845 return SDValue(); 1846 case AMDGPUAS::PRIVATE_ADDRESS: { 1847 // Depending on the setting of the private_element_size field in the 1848 // resource descriptor, we can only make private accesses up to a certain 1849 // size. 1850 switch (Subtarget->getMaxPrivateElementSize()) { 1851 case 4: 1852 return scalarizeVectorLoad(Load, DAG); 1853 case 8: 1854 if (NumElements > 2) 1855 return SplitVectorLoad(Op, DAG); 1856 return SDValue(); 1857 case 16: 1858 // Same as global/flat 1859 if (NumElements > 4) 1860 return SplitVectorLoad(Op, DAG); 1861 return SDValue(); 1862 default: 1863 llvm_unreachable("unsupported private_element_size"); 1864 } 1865 } 1866 case AMDGPUAS::LOCAL_ADDRESS: { 1867 if (NumElements > 2) 1868 return SplitVectorLoad(Op, DAG); 1869 1870 if (NumElements == 2) 1871 return SDValue(); 1872 1873 // If properly aligned, if we split we might be able to use ds_read_b64. 1874 return SplitVectorLoad(Op, DAG); 1875 } 1876 default: 1877 return SDValue(); 1878 } 1879 } 1880 1881 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 1882 if (Op.getValueType() != MVT::i64) 1883 return SDValue(); 1884 1885 SDLoc DL(Op); 1886 SDValue Cond = Op.getOperand(0); 1887 1888 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 1889 SDValue One = DAG.getConstant(1, DL, MVT::i32); 1890 1891 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 1892 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 1893 1894 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 1895 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 1896 1897 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 1898 1899 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 1900 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 1901 1902 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 1903 1904 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 1905 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 1906 } 1907 1908 // Catch division cases where we can use shortcuts with rcp and rsq 1909 // instructions. 1910 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const { 1911 SDLoc SL(Op); 1912 SDValue LHS = Op.getOperand(0); 1913 SDValue RHS = Op.getOperand(1); 1914 EVT VT = Op.getValueType(); 1915 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath; 1916 1917 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 1918 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) && 1919 CLHS->isExactlyValue(1.0)) { 1920 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 1921 // the CI documentation has a worst case error of 1 ulp. 1922 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 1923 // use it as long as we aren't trying to use denormals. 1924 1925 // 1.0 / sqrt(x) -> rsq(x) 1926 // 1927 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 1928 // error seems really high at 2^29 ULP. 1929 if (RHS.getOpcode() == ISD::FSQRT) 1930 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 1931 1932 // 1.0 / x -> rcp(x) 1933 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 1934 } 1935 } 1936 1937 const SDNodeFlags *Flags = Op->getFlags(); 1938 1939 if (Unsafe || Flags->hasAllowReciprocal()) { 1940 // Turn into multiply by the reciprocal. 1941 // x / y -> x * (1.0 / y) 1942 SDNodeFlags Flags; 1943 Flags.setUnsafeAlgebra(true); 1944 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 1945 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags); 1946 } 1947 1948 return SDValue(); 1949 } 1950 1951 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 1952 if (SDValue FastLowered = LowerFastFDIV(Op, DAG)) 1953 return FastLowered; 1954 1955 // This uses v_rcp_f32 which does not handle denormals. Let this hit a 1956 // selection error for now rather than do something incorrect. 1957 if (Subtarget->hasFP32Denormals()) 1958 return SDValue(); 1959 1960 SDLoc SL(Op); 1961 SDValue LHS = Op.getOperand(0); 1962 SDValue RHS = Op.getOperand(1); 1963 1964 // faster 2.5 ulp fdiv when using -amdgpu-fast-fdiv flag 1965 if (EnableAMDGPUFastFDIV) { 1966 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 1967 1968 const APFloat K0Val(BitsToFloat(0x6f800000)); 1969 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 1970 1971 const APFloat K1Val(BitsToFloat(0x2f800000)); 1972 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 1973 1974 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 1975 1976 EVT SetCCVT = 1977 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 1978 1979 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 1980 1981 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 1982 1983 // TODO: Should this propagate fast-math-flags? 1984 1985 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 1986 1987 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 1988 1989 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 1990 1991 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 1992 } 1993 1994 // Generates more precise fpdiv32. 1995 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 1996 1997 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 1998 1999 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, RHS, RHS, LHS); 2000 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, LHS, RHS, LHS); 2001 2002 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, DenominatorScaled); 2003 2004 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, DenominatorScaled); 2005 2006 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, ApproxRcp, One); 2007 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, ApproxRcp); 2008 2009 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, NumeratorScaled, Fma1); 2010 2011 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, NumeratorScaled); 2012 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul); 2013 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, NumeratorScaled); 2014 2015 SDValue Scale = NumeratorScaled.getValue(1); 2016 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, Fma4, Fma1, Fma3, Scale); 2017 2018 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 2019 } 2020 2021 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 2022 if (DAG.getTarget().Options.UnsafeFPMath) 2023 return LowerFastFDIV(Op, DAG); 2024 2025 SDLoc SL(Op); 2026 SDValue X = Op.getOperand(0); 2027 SDValue Y = Op.getOperand(1); 2028 2029 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 2030 2031 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 2032 2033 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 2034 2035 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 2036 2037 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 2038 2039 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 2040 2041 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 2042 2043 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 2044 2045 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 2046 2047 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 2048 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 2049 2050 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 2051 NegDivScale0, Mul, DivScale1); 2052 2053 SDValue Scale; 2054 2055 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 2056 // Workaround a hardware bug on SI where the condition output from div_scale 2057 // is not usable. 2058 2059 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 2060 2061 // Figure out if the scale to use for div_fmas. 2062 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 2063 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 2064 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 2065 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 2066 2067 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 2068 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 2069 2070 SDValue Scale0Hi 2071 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 2072 SDValue Scale1Hi 2073 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 2074 2075 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 2076 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 2077 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 2078 } else { 2079 Scale = DivScale1.getValue(1); 2080 } 2081 2082 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 2083 Fma4, Fma3, Mul, Scale); 2084 2085 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 2086 } 2087 2088 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 2089 EVT VT = Op.getValueType(); 2090 2091 if (VT == MVT::f32) 2092 return LowerFDIV32(Op, DAG); 2093 2094 if (VT == MVT::f64) 2095 return LowerFDIV64(Op, DAG); 2096 2097 llvm_unreachable("Unexpected type for fdiv"); 2098 } 2099 2100 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 2101 SDLoc DL(Op); 2102 StoreSDNode *Store = cast<StoreSDNode>(Op); 2103 EVT VT = Store->getMemoryVT(); 2104 2105 if (VT == MVT::i1) { 2106 return DAG.getTruncStore(Store->getChain(), DL, 2107 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 2108 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 2109 } 2110 2111 assert(VT.isVector() && 2112 Store->getValue().getValueType().getScalarType() == MVT::i32); 2113 2114 unsigned AS = Store->getAddressSpace(); 2115 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 2116 AS, Store->getAlignment())) { 2117 return expandUnalignedStore(Store, DAG); 2118 } 2119 2120 unsigned NumElements = VT.getVectorNumElements(); 2121 switch (AS) { 2122 case AMDGPUAS::GLOBAL_ADDRESS: 2123 case AMDGPUAS::FLAT_ADDRESS: 2124 if (NumElements > 4) 2125 return SplitVectorStore(Op, DAG); 2126 return SDValue(); 2127 case AMDGPUAS::PRIVATE_ADDRESS: { 2128 switch (Subtarget->getMaxPrivateElementSize()) { 2129 case 4: 2130 return scalarizeVectorStore(Store, DAG); 2131 case 8: 2132 if (NumElements > 2) 2133 return SplitVectorStore(Op, DAG); 2134 return SDValue(); 2135 case 16: 2136 if (NumElements > 4) 2137 return SplitVectorStore(Op, DAG); 2138 return SDValue(); 2139 default: 2140 llvm_unreachable("unsupported private_element_size"); 2141 } 2142 } 2143 case AMDGPUAS::LOCAL_ADDRESS: { 2144 if (NumElements > 2) 2145 return SplitVectorStore(Op, DAG); 2146 2147 if (NumElements == 2) 2148 return Op; 2149 2150 // If properly aligned, if we split we might be able to use ds_write_b64. 2151 return SplitVectorStore(Op, DAG); 2152 } 2153 default: 2154 llvm_unreachable("unhandled address space"); 2155 } 2156 } 2157 2158 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 2159 SDLoc DL(Op); 2160 EVT VT = Op.getValueType(); 2161 SDValue Arg = Op.getOperand(0); 2162 // TODO: Should this propagate fast-math-flags? 2163 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 2164 DAG.getNode(ISD::FMUL, DL, VT, Arg, 2165 DAG.getConstantFP(0.5/M_PI, DL, 2166 VT))); 2167 2168 switch (Op.getOpcode()) { 2169 case ISD::FCOS: 2170 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 2171 case ISD::FSIN: 2172 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 2173 default: 2174 llvm_unreachable("Wrong trig opcode"); 2175 } 2176 } 2177 2178 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 2179 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 2180 assert(AtomicNode->isCompareAndSwap()); 2181 unsigned AS = AtomicNode->getAddressSpace(); 2182 2183 // No custom lowering required for local address space 2184 if (!isFlatGlobalAddrSpace(AS)) 2185 return Op; 2186 2187 // Non-local address space requires custom lowering for atomic compare 2188 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 2189 SDLoc DL(Op); 2190 SDValue ChainIn = Op.getOperand(0); 2191 SDValue Addr = Op.getOperand(1); 2192 SDValue Old = Op.getOperand(2); 2193 SDValue New = Op.getOperand(3); 2194 EVT VT = Op.getValueType(); 2195 MVT SimpleVT = VT.getSimpleVT(); 2196 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 2197 2198 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 2199 SDValue Ops[] = { ChainIn, Addr, NewOld }; 2200 2201 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 2202 Ops, VT, AtomicNode->getMemOperand()); 2203 } 2204 2205 //===----------------------------------------------------------------------===// 2206 // Custom DAG optimizations 2207 //===----------------------------------------------------------------------===// 2208 2209 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 2210 DAGCombinerInfo &DCI) const { 2211 EVT VT = N->getValueType(0); 2212 EVT ScalarVT = VT.getScalarType(); 2213 if (ScalarVT != MVT::f32) 2214 return SDValue(); 2215 2216 SelectionDAG &DAG = DCI.DAG; 2217 SDLoc DL(N); 2218 2219 SDValue Src = N->getOperand(0); 2220 EVT SrcVT = Src.getValueType(); 2221 2222 // TODO: We could try to match extracting the higher bytes, which would be 2223 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 2224 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 2225 // about in practice. 2226 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 2227 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 2228 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 2229 DCI.AddToWorklist(Cvt.getNode()); 2230 return Cvt; 2231 } 2232 } 2233 2234 // We are primarily trying to catch operations on illegal vector types 2235 // before they are expanded. 2236 // For scalars, we can use the more flexible method of checking masked bits 2237 // after legalization. 2238 if (!DCI.isBeforeLegalize() || 2239 !SrcVT.isVector() || 2240 SrcVT.getVectorElementType() != MVT::i8) { 2241 return SDValue(); 2242 } 2243 2244 assert(DCI.isBeforeLegalize() && "Unexpected legal type"); 2245 2246 // Weird sized vectors are a pain to handle, but we know 3 is really the same 2247 // size as 4. 2248 unsigned NElts = SrcVT.getVectorNumElements(); 2249 if (!SrcVT.isSimple() && NElts != 3) 2250 return SDValue(); 2251 2252 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to 2253 // prevent a mess from expanding to v4i32 and repacking. 2254 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) { 2255 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT); 2256 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT); 2257 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts); 2258 LoadSDNode *Load = cast<LoadSDNode>(Src); 2259 2260 unsigned AS = Load->getAddressSpace(); 2261 unsigned Align = Load->getAlignment(); 2262 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext()); 2263 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 2264 2265 // Don't try to replace the load if we have to expand it due to alignment 2266 // problems. Otherwise we will end up scalarizing the load, and trying to 2267 // repack into the vector for no real reason. 2268 if (Align < ABIAlignment && 2269 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) { 2270 return SDValue(); 2271 } 2272 2273 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT, 2274 Load->getChain(), 2275 Load->getBasePtr(), 2276 LoadVT, 2277 Load->getMemOperand()); 2278 2279 // Make sure successors of the original load stay after it by updating 2280 // them to use the new Chain. 2281 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1)); 2282 2283 SmallVector<SDValue, 4> Elts; 2284 if (RegVT.isVector()) 2285 DAG.ExtractVectorElements(NewLoad, Elts); 2286 else 2287 Elts.push_back(NewLoad); 2288 2289 SmallVector<SDValue, 4> Ops; 2290 2291 unsigned EltIdx = 0; 2292 for (SDValue Elt : Elts) { 2293 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx); 2294 for (unsigned I = 0; I < ComponentsInElt; ++I) { 2295 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I; 2296 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt); 2297 DCI.AddToWorklist(Cvt.getNode()); 2298 Ops.push_back(Cvt); 2299 } 2300 2301 ++EltIdx; 2302 } 2303 2304 assert(Ops.size() == NElts); 2305 2306 return DAG.getBuildVector(FloatVT, DL, Ops); 2307 } 2308 2309 return SDValue(); 2310 } 2311 2312 /// \brief Return true if the given offset Size in bytes can be folded into 2313 /// the immediate offsets of a memory instruction for the given address space. 2314 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 2315 const AMDGPUSubtarget &STI) { 2316 switch (AS) { 2317 case AMDGPUAS::GLOBAL_ADDRESS: { 2318 // MUBUF instructions a 12-bit offset in bytes. 2319 return isUInt<12>(OffsetSize); 2320 } 2321 case AMDGPUAS::CONSTANT_ADDRESS: { 2322 // SMRD instructions have an 8-bit offset in dwords on SI and 2323 // a 20-bit offset in bytes on VI. 2324 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 2325 return isUInt<20>(OffsetSize); 2326 else 2327 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 2328 } 2329 case AMDGPUAS::LOCAL_ADDRESS: 2330 case AMDGPUAS::REGION_ADDRESS: { 2331 // The single offset versions have a 16-bit offset in bytes. 2332 return isUInt<16>(OffsetSize); 2333 } 2334 case AMDGPUAS::PRIVATE_ADDRESS: 2335 // Indirect register addressing does not use any offsets. 2336 default: 2337 return 0; 2338 } 2339 } 2340 2341 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 2342 2343 // This is a variant of 2344 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 2345 // 2346 // The normal DAG combiner will do this, but only if the add has one use since 2347 // that would increase the number of instructions. 2348 // 2349 // This prevents us from seeing a constant offset that can be folded into a 2350 // memory instruction's addressing mode. If we know the resulting add offset of 2351 // a pointer can be folded into an addressing offset, we can replace the pointer 2352 // operand with the add of new constant offset. This eliminates one of the uses, 2353 // and may allow the remaining use to also be simplified. 2354 // 2355 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 2356 unsigned AddrSpace, 2357 DAGCombinerInfo &DCI) const { 2358 SDValue N0 = N->getOperand(0); 2359 SDValue N1 = N->getOperand(1); 2360 2361 if (N0.getOpcode() != ISD::ADD) 2362 return SDValue(); 2363 2364 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 2365 if (!CN1) 2366 return SDValue(); 2367 2368 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2369 if (!CAdd) 2370 return SDValue(); 2371 2372 // If the resulting offset is too large, we can't fold it into the addressing 2373 // mode offset. 2374 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 2375 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget)) 2376 return SDValue(); 2377 2378 SelectionDAG &DAG = DCI.DAG; 2379 SDLoc SL(N); 2380 EVT VT = N->getValueType(0); 2381 2382 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 2383 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 2384 2385 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 2386 } 2387 2388 SDValue SITargetLowering::performAndCombine(SDNode *N, 2389 DAGCombinerInfo &DCI) const { 2390 if (DCI.isBeforeLegalize()) 2391 return SDValue(); 2392 2393 if (SDValue Base = AMDGPUTargetLowering::performAndCombine(N, DCI)) 2394 return Base; 2395 2396 SelectionDAG &DAG = DCI.DAG; 2397 2398 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 2399 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 2400 SDValue LHS = N->getOperand(0); 2401 SDValue RHS = N->getOperand(1); 2402 2403 if (LHS.getOpcode() == ISD::SETCC && 2404 RHS.getOpcode() == ISD::SETCC) { 2405 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 2406 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 2407 2408 SDValue X = LHS.getOperand(0); 2409 SDValue Y = RHS.getOperand(0); 2410 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 2411 return SDValue(); 2412 2413 if (LCC == ISD::SETO) { 2414 if (X != LHS.getOperand(1)) 2415 return SDValue(); 2416 2417 if (RCC == ISD::SETUNE) { 2418 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 2419 if (!C1 || !C1->isInfinity() || C1->isNegative()) 2420 return SDValue(); 2421 2422 const uint32_t Mask = SIInstrFlags::N_NORMAL | 2423 SIInstrFlags::N_SUBNORMAL | 2424 SIInstrFlags::N_ZERO | 2425 SIInstrFlags::P_ZERO | 2426 SIInstrFlags::P_SUBNORMAL | 2427 SIInstrFlags::P_NORMAL; 2428 2429 static_assert(((~(SIInstrFlags::S_NAN | 2430 SIInstrFlags::Q_NAN | 2431 SIInstrFlags::N_INFINITY | 2432 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 2433 "mask not equal"); 2434 2435 SDLoc DL(N); 2436 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 2437 X, DAG.getConstant(Mask, DL, MVT::i32)); 2438 } 2439 } 2440 } 2441 2442 return SDValue(); 2443 } 2444 2445 SDValue SITargetLowering::performOrCombine(SDNode *N, 2446 DAGCombinerInfo &DCI) const { 2447 SelectionDAG &DAG = DCI.DAG; 2448 SDValue LHS = N->getOperand(0); 2449 SDValue RHS = N->getOperand(1); 2450 2451 EVT VT = N->getValueType(0); 2452 if (VT == MVT::i64) { 2453 // TODO: This could be a generic combine with a predicate for extracting the 2454 // high half of an integer being free. 2455 2456 // (or i64:x, (zero_extend i32:y)) -> 2457 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 2458 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 2459 RHS.getOpcode() != ISD::ZERO_EXTEND) 2460 std::swap(LHS, RHS); 2461 2462 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 2463 SDValue ExtSrc = RHS.getOperand(0); 2464 EVT SrcVT = ExtSrc.getValueType(); 2465 if (SrcVT == MVT::i32) { 2466 SDLoc SL(N); 2467 SDValue LowLHS, HiBits; 2468 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 2469 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 2470 2471 DCI.AddToWorklist(LowOr.getNode()); 2472 DCI.AddToWorklist(HiBits.getNode()); 2473 2474 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 2475 LowOr, HiBits); 2476 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 2477 } 2478 } 2479 } 2480 2481 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 2482 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 2483 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 2484 SDValue Src = LHS.getOperand(0); 2485 if (Src != RHS.getOperand(0)) 2486 return SDValue(); 2487 2488 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 2489 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 2490 if (!CLHS || !CRHS) 2491 return SDValue(); 2492 2493 // Only 10 bits are used. 2494 static const uint32_t MaxMask = 0x3ff; 2495 2496 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 2497 SDLoc DL(N); 2498 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 2499 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 2500 } 2501 2502 return SDValue(); 2503 } 2504 2505 SDValue SITargetLowering::performClassCombine(SDNode *N, 2506 DAGCombinerInfo &DCI) const { 2507 SelectionDAG &DAG = DCI.DAG; 2508 SDValue Mask = N->getOperand(1); 2509 2510 // fp_class x, 0 -> false 2511 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 2512 if (CMask->isNullValue()) 2513 return DAG.getConstant(0, SDLoc(N), MVT::i1); 2514 } 2515 2516 return SDValue(); 2517 } 2518 2519 // Constant fold canonicalize. 2520 SDValue SITargetLowering::performFCanonicalizeCombine( 2521 SDNode *N, 2522 DAGCombinerInfo &DCI) const { 2523 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 2524 if (!CFP) 2525 return SDValue(); 2526 2527 SelectionDAG &DAG = DCI.DAG; 2528 const APFloat &C = CFP->getValueAPF(); 2529 2530 // Flush denormals to 0 if not enabled. 2531 if (C.isDenormal()) { 2532 EVT VT = N->getValueType(0); 2533 if (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) 2534 return DAG.getConstantFP(0.0, SDLoc(N), VT); 2535 2536 if (VT == MVT::f64 && !Subtarget->hasFP64Denormals()) 2537 return DAG.getConstantFP(0.0, SDLoc(N), VT); 2538 } 2539 2540 if (C.isNaN()) { 2541 EVT VT = N->getValueType(0); 2542 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 2543 if (C.isSignaling()) { 2544 // Quiet a signaling NaN. 2545 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 2546 } 2547 2548 // Make sure it is the canonical NaN bitpattern. 2549 // 2550 // TODO: Can we use -1 as the canonical NaN value since it's an inline 2551 // immediate? 2552 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 2553 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 2554 } 2555 2556 return SDValue(CFP, 0); 2557 } 2558 2559 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 2560 switch (Opc) { 2561 case ISD::FMAXNUM: 2562 return AMDGPUISD::FMAX3; 2563 case ISD::SMAX: 2564 return AMDGPUISD::SMAX3; 2565 case ISD::UMAX: 2566 return AMDGPUISD::UMAX3; 2567 case ISD::FMINNUM: 2568 return AMDGPUISD::FMIN3; 2569 case ISD::SMIN: 2570 return AMDGPUISD::SMIN3; 2571 case ISD::UMIN: 2572 return AMDGPUISD::UMIN3; 2573 default: 2574 llvm_unreachable("Not a min/max opcode"); 2575 } 2576 } 2577 2578 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL, 2579 SDValue Op0, SDValue Op1, bool Signed) { 2580 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 2581 if (!K1) 2582 return SDValue(); 2583 2584 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 2585 if (!K0) 2586 return SDValue(); 2587 2588 2589 if (Signed) { 2590 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 2591 return SDValue(); 2592 } else { 2593 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 2594 return SDValue(); 2595 } 2596 2597 EVT VT = K0->getValueType(0); 2598 return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT, 2599 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 2600 } 2601 2602 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 2603 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 2604 return true; 2605 2606 return DAG.isKnownNeverNaN(Op); 2607 } 2608 2609 static SDValue performFPMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL, 2610 SDValue Op0, SDValue Op1) { 2611 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1); 2612 if (!K1) 2613 return SDValue(); 2614 2615 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1)); 2616 if (!K0) 2617 return SDValue(); 2618 2619 // Ordered >= (although NaN inputs should have folded away by now). 2620 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 2621 if (Cmp == APFloat::cmpGreaterThan) 2622 return SDValue(); 2623 2624 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 2625 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then 2626 // give the other result, which is different from med3 with a NaN input. 2627 SDValue Var = Op0.getOperand(0); 2628 if (!isKnownNeverSNan(DAG, Var)) 2629 return SDValue(); 2630 2631 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 2632 Var, SDValue(K0, 0), SDValue(K1, 0)); 2633 } 2634 2635 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 2636 DAGCombinerInfo &DCI) const { 2637 SelectionDAG &DAG = DCI.DAG; 2638 2639 unsigned Opc = N->getOpcode(); 2640 SDValue Op0 = N->getOperand(0); 2641 SDValue Op1 = N->getOperand(1); 2642 2643 // Only do this if the inner op has one use since this will just increases 2644 // register pressure for no benefit. 2645 2646 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY) { 2647 // max(max(a, b), c) -> max3(a, b, c) 2648 // min(min(a, b), c) -> min3(a, b, c) 2649 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 2650 SDLoc DL(N); 2651 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 2652 DL, 2653 N->getValueType(0), 2654 Op0.getOperand(0), 2655 Op0.getOperand(1), 2656 Op1); 2657 } 2658 2659 // Try commuted. 2660 // max(a, max(b, c)) -> max3(a, b, c) 2661 // min(a, min(b, c)) -> min3(a, b, c) 2662 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 2663 SDLoc DL(N); 2664 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 2665 DL, 2666 N->getValueType(0), 2667 Op0, 2668 Op1.getOperand(0), 2669 Op1.getOperand(1)); 2670 } 2671 } 2672 2673 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 2674 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 2675 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 2676 return Med3; 2677 } 2678 2679 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 2680 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 2681 return Med3; 2682 } 2683 2684 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 2685 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 2686 (Opc == AMDGPUISD::FMIN_LEGACY && 2687 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 2688 N->getValueType(0) == MVT::f32 && Op0.hasOneUse()) { 2689 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 2690 return Res; 2691 } 2692 2693 return SDValue(); 2694 } 2695 2696 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 2697 DAGCombinerInfo &DCI) const { 2698 SelectionDAG &DAG = DCI.DAG; 2699 SDLoc SL(N); 2700 2701 SDValue LHS = N->getOperand(0); 2702 SDValue RHS = N->getOperand(1); 2703 EVT VT = LHS.getValueType(); 2704 2705 if (VT != MVT::f32 && VT != MVT::f64) 2706 return SDValue(); 2707 2708 // Match isinf pattern 2709 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 2710 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 2711 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 2712 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 2713 if (!CRHS) 2714 return SDValue(); 2715 2716 const APFloat &APF = CRHS->getValueAPF(); 2717 if (APF.isInfinity() && !APF.isNegative()) { 2718 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 2719 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 2720 DAG.getConstant(Mask, SL, MVT::i32)); 2721 } 2722 } 2723 2724 return SDValue(); 2725 } 2726 2727 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 2728 DAGCombinerInfo &DCI) const { 2729 SelectionDAG &DAG = DCI.DAG; 2730 SDLoc DL(N); 2731 2732 switch (N->getOpcode()) { 2733 default: 2734 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 2735 case ISD::SETCC: 2736 return performSetCCCombine(N, DCI); 2737 case ISD::FMAXNUM: 2738 case ISD::FMINNUM: 2739 case ISD::SMAX: 2740 case ISD::SMIN: 2741 case ISD::UMAX: 2742 case ISD::UMIN: 2743 case AMDGPUISD::FMIN_LEGACY: 2744 case AMDGPUISD::FMAX_LEGACY: { 2745 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 2746 N->getValueType(0) != MVT::f64 && 2747 getTargetMachine().getOptLevel() > CodeGenOpt::None) 2748 return performMinMaxCombine(N, DCI); 2749 break; 2750 } 2751 2752 case AMDGPUISD::CVT_F32_UBYTE0: 2753 case AMDGPUISD::CVT_F32_UBYTE1: 2754 case AMDGPUISD::CVT_F32_UBYTE2: 2755 case AMDGPUISD::CVT_F32_UBYTE3: { 2756 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 2757 SDValue Src = N->getOperand(0); 2758 2759 if (Src.getOpcode() == ISD::SRL) { 2760 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 2761 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 2762 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 2763 2764 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src.getOperand(1))) { 2765 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 2766 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 2767 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, DL, 2768 MVT::f32, Src.getOperand(0)); 2769 } 2770 } 2771 } 2772 2773 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 2774 2775 APInt KnownZero, KnownOne; 2776 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2777 !DCI.isBeforeLegalizeOps()); 2778 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2779 if (TLO.ShrinkDemandedConstant(Src, Demanded) || 2780 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) { 2781 DCI.CommitTargetLoweringOpt(TLO); 2782 } 2783 2784 break; 2785 } 2786 2787 case ISD::UINT_TO_FP: { 2788 return performUCharToFloatCombine(N, DCI); 2789 } 2790 case ISD::FADD: { 2791 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 2792 break; 2793 2794 EVT VT = N->getValueType(0); 2795 if (VT != MVT::f32) 2796 break; 2797 2798 // Only do this if we are not trying to support denormals. v_mad_f32 does 2799 // not support denormals ever. 2800 if (Subtarget->hasFP32Denormals()) 2801 break; 2802 2803 SDValue LHS = N->getOperand(0); 2804 SDValue RHS = N->getOperand(1); 2805 2806 // These should really be instruction patterns, but writing patterns with 2807 // source modiifiers is a pain. 2808 2809 // fadd (fadd (a, a), b) -> mad 2.0, a, b 2810 if (LHS.getOpcode() == ISD::FADD) { 2811 SDValue A = LHS.getOperand(0); 2812 if (A == LHS.getOperand(1)) { 2813 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 2814 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS); 2815 } 2816 } 2817 2818 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 2819 if (RHS.getOpcode() == ISD::FADD) { 2820 SDValue A = RHS.getOperand(0); 2821 if (A == RHS.getOperand(1)) { 2822 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 2823 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS); 2824 } 2825 } 2826 2827 return SDValue(); 2828 } 2829 case ISD::FSUB: { 2830 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 2831 break; 2832 2833 EVT VT = N->getValueType(0); 2834 2835 // Try to get the fneg to fold into the source modifier. This undoes generic 2836 // DAG combines and folds them into the mad. 2837 // 2838 // Only do this if we are not trying to support denormals. v_mad_f32 does 2839 // not support denormals ever. 2840 if (VT == MVT::f32 && 2841 !Subtarget->hasFP32Denormals()) { 2842 SDValue LHS = N->getOperand(0); 2843 SDValue RHS = N->getOperand(1); 2844 if (LHS.getOpcode() == ISD::FADD) { 2845 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 2846 2847 SDValue A = LHS.getOperand(0); 2848 if (A == LHS.getOperand(1)) { 2849 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 2850 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS); 2851 2852 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS); 2853 } 2854 } 2855 2856 if (RHS.getOpcode() == ISD::FADD) { 2857 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 2858 2859 SDValue A = RHS.getOperand(0); 2860 if (A == RHS.getOperand(1)) { 2861 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32); 2862 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS); 2863 } 2864 } 2865 2866 return SDValue(); 2867 } 2868 2869 break; 2870 } 2871 case ISD::LOAD: 2872 case ISD::STORE: 2873 case ISD::ATOMIC_LOAD: 2874 case ISD::ATOMIC_STORE: 2875 case ISD::ATOMIC_CMP_SWAP: 2876 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 2877 case ISD::ATOMIC_SWAP: 2878 case ISD::ATOMIC_LOAD_ADD: 2879 case ISD::ATOMIC_LOAD_SUB: 2880 case ISD::ATOMIC_LOAD_AND: 2881 case ISD::ATOMIC_LOAD_OR: 2882 case ISD::ATOMIC_LOAD_XOR: 2883 case ISD::ATOMIC_LOAD_NAND: 2884 case ISD::ATOMIC_LOAD_MIN: 2885 case ISD::ATOMIC_LOAD_MAX: 2886 case ISD::ATOMIC_LOAD_UMIN: 2887 case ISD::ATOMIC_LOAD_UMAX: 2888 case AMDGPUISD::ATOMIC_INC: 2889 case AMDGPUISD::ATOMIC_DEC: { // TODO: Target mem intrinsics. 2890 if (DCI.isBeforeLegalize()) 2891 break; 2892 2893 MemSDNode *MemNode = cast<MemSDNode>(N); 2894 SDValue Ptr = MemNode->getBasePtr(); 2895 2896 // TODO: We could also do this for multiplies. 2897 unsigned AS = MemNode->getAddressSpace(); 2898 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) { 2899 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 2900 if (NewPtr) { 2901 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end()); 2902 2903 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 2904 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0); 2905 } 2906 } 2907 break; 2908 } 2909 case ISD::AND: 2910 return performAndCombine(N, DCI); 2911 case ISD::OR: 2912 return performOrCombine(N, DCI); 2913 case AMDGPUISD::FP_CLASS: 2914 return performClassCombine(N, DCI); 2915 case ISD::FCANONICALIZE: 2916 return performFCanonicalizeCombine(N, DCI); 2917 } 2918 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 2919 } 2920 2921 /// \brief Analyze the possible immediate value Op 2922 /// 2923 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate 2924 /// and the immediate value if it's a literal immediate 2925 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const { 2926 2927 const SIInstrInfo *TII = 2928 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 2929 2930 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) { 2931 if (TII->isInlineConstant(Node->getAPIntValue())) 2932 return 0; 2933 2934 uint64_t Val = Node->getZExtValue(); 2935 return isUInt<32>(Val) ? Val : -1; 2936 } 2937 2938 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) { 2939 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt())) 2940 return 0; 2941 2942 if (Node->getValueType(0) == MVT::f32) 2943 return FloatToBits(Node->getValueAPF().convertToFloat()); 2944 2945 return -1; 2946 } 2947 2948 return -1; 2949 } 2950 2951 /// \brief Helper function for adjustWritemask 2952 static unsigned SubIdx2Lane(unsigned Idx) { 2953 switch (Idx) { 2954 default: return 0; 2955 case AMDGPU::sub0: return 0; 2956 case AMDGPU::sub1: return 1; 2957 case AMDGPU::sub2: return 2; 2958 case AMDGPU::sub3: return 3; 2959 } 2960 } 2961 2962 /// \brief Adjust the writemask of MIMG instructions 2963 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 2964 SelectionDAG &DAG) const { 2965 SDNode *Users[4] = { }; 2966 unsigned Lane = 0; 2967 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 2968 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 2969 unsigned NewDmask = 0; 2970 2971 // Try to figure out the used register components 2972 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 2973 I != E; ++I) { 2974 2975 // Abort if we can't understand the usage 2976 if (!I->isMachineOpcode() || 2977 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 2978 return; 2979 2980 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 2981 // Note that subregs are packed, i.e. Lane==0 is the first bit set 2982 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 2983 // set, etc. 2984 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 2985 2986 // Set which texture component corresponds to the lane. 2987 unsigned Comp; 2988 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 2989 assert(Dmask); 2990 Comp = countTrailingZeros(Dmask); 2991 Dmask &= ~(1 << Comp); 2992 } 2993 2994 // Abort if we have more than one user per component 2995 if (Users[Lane]) 2996 return; 2997 2998 Users[Lane] = *I; 2999 NewDmask |= 1 << Comp; 3000 } 3001 3002 // Abort if there's no change 3003 if (NewDmask == OldDmask) 3004 return; 3005 3006 // Adjust the writemask in the node 3007 std::vector<SDValue> Ops; 3008 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 3009 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 3010 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 3011 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 3012 3013 // If we only got one lane, replace it with a copy 3014 // (if NewDmask has only one bit set...) 3015 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 3016 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 3017 MVT::i32); 3018 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 3019 SDLoc(), Users[Lane]->getValueType(0), 3020 SDValue(Node, 0), RC); 3021 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 3022 return; 3023 } 3024 3025 // Update the users of the node with the new indices 3026 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 3027 3028 SDNode *User = Users[i]; 3029 if (!User) 3030 continue; 3031 3032 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 3033 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 3034 3035 switch (Idx) { 3036 default: break; 3037 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 3038 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 3039 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 3040 } 3041 } 3042 } 3043 3044 static bool isFrameIndexOp(SDValue Op) { 3045 if (Op.getOpcode() == ISD::AssertZext) 3046 Op = Op.getOperand(0); 3047 3048 return isa<FrameIndexSDNode>(Op); 3049 } 3050 3051 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 3052 /// with frame index operands. 3053 /// LLVM assumes that inputs are to these instructions are registers. 3054 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 3055 SelectionDAG &DAG) const { 3056 3057 SmallVector<SDValue, 8> Ops; 3058 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 3059 if (!isFrameIndexOp(Node->getOperand(i))) { 3060 Ops.push_back(Node->getOperand(i)); 3061 continue; 3062 } 3063 3064 SDLoc DL(Node); 3065 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 3066 Node->getOperand(i).getValueType(), 3067 Node->getOperand(i)), 0)); 3068 } 3069 3070 DAG.UpdateNodeOperands(Node, Ops); 3071 } 3072 3073 /// \brief Fold the instructions after selecting them. 3074 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 3075 SelectionDAG &DAG) const { 3076 const SIInstrInfo *TII = 3077 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 3078 unsigned Opcode = Node->getMachineOpcode(); 3079 3080 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore()) 3081 adjustWritemask(Node, DAG); 3082 3083 if (Opcode == AMDGPU::INSERT_SUBREG || 3084 Opcode == AMDGPU::REG_SEQUENCE) { 3085 legalizeTargetIndependentNode(Node, DAG); 3086 return Node; 3087 } 3088 return Node; 3089 } 3090 3091 /// \brief Assign the register class depending on the number of 3092 /// bits set in the writemask 3093 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 3094 SDNode *Node) const { 3095 const SIInstrInfo *TII = 3096 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 3097 3098 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo(); 3099 3100 if (TII->isVOP3(MI->getOpcode())) { 3101 // Make sure constant bus requirements are respected. 3102 TII->legalizeOperandsVOP3(MRI, MI); 3103 return; 3104 } 3105 3106 if (TII->isMIMG(*MI)) { 3107 unsigned VReg = MI->getOperand(0).getReg(); 3108 unsigned DmaskIdx = MI->getNumOperands() == 12 ? 3 : 4; 3109 unsigned Writemask = MI->getOperand(DmaskIdx).getImm(); 3110 unsigned BitsSet = 0; 3111 for (unsigned i = 0; i < 4; ++i) 3112 BitsSet += Writemask & (1 << i) ? 1 : 0; 3113 3114 const TargetRegisterClass *RC; 3115 switch (BitsSet) { 3116 default: return; 3117 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 3118 case 2: RC = &AMDGPU::VReg_64RegClass; break; 3119 case 3: RC = &AMDGPU::VReg_96RegClass; break; 3120 } 3121 3122 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet); 3123 MI->setDesc(TII->get(NewOpcode)); 3124 MRI.setRegClass(VReg, RC); 3125 return; 3126 } 3127 3128 // Replace unused atomics with the no return version. 3129 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode()); 3130 if (NoRetAtomicOp != -1) { 3131 if (!Node->hasAnyUseOfValue(0)) { 3132 MI->setDesc(TII->get(NoRetAtomicOp)); 3133 MI->RemoveOperand(0); 3134 return; 3135 } 3136 3137 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 3138 // instruction, because the return type of these instructions is a vec2 of 3139 // the memory type, so it can be tied to the input operand. 3140 // This means these instructions always have a use, so we need to add a 3141 // special case to check if the atomic has only one extract_subreg use, 3142 // which itself has no uses. 3143 if ((Node->hasNUsesOfValue(1, 0) && 3144 Node->use_begin()->isMachineOpcode() && 3145 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 3146 !Node->use_begin()->hasAnyUseOfValue(0))) { 3147 unsigned Def = MI->getOperand(0).getReg(); 3148 3149 // Change this into a noret atomic. 3150 MI->setDesc(TII->get(NoRetAtomicOp)); 3151 MI->RemoveOperand(0); 3152 3153 // If we only remove the def operand from the atomic instruction, the 3154 // extract_subreg will be left with a use of a vreg without a def. 3155 // So we need to insert an implicit_def to avoid machine verifier 3156 // errors. 3157 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), 3158 TII->get(AMDGPU::IMPLICIT_DEF), Def); 3159 } 3160 return; 3161 } 3162 } 3163 3164 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 3165 uint64_t Val) { 3166 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 3167 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 3168 } 3169 3170 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 3171 const SDLoc &DL, 3172 SDValue Ptr) const { 3173 const SIInstrInfo *TII = 3174 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo()); 3175 3176 // Build the half of the subregister with the constants before building the 3177 // full 128-bit register. If we are building multiple resource descriptors, 3178 // this will allow CSEing of the 2-component register. 3179 const SDValue Ops0[] = { 3180 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 3181 buildSMovImm32(DAG, DL, 0), 3182 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 3183 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 3184 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 3185 }; 3186 3187 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 3188 MVT::v2i32, Ops0), 0); 3189 3190 // Combine the constants and the pointer. 3191 const SDValue Ops1[] = { 3192 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 3193 Ptr, 3194 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 3195 SubRegHi, 3196 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 3197 }; 3198 3199 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 3200 } 3201 3202 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 3203 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 3204 /// of the resource descriptor) to create an offset, which is added to 3205 /// the resource pointer. 3206 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 3207 SDValue Ptr, uint32_t RsrcDword1, 3208 uint64_t RsrcDword2And3) const { 3209 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 3210 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 3211 if (RsrcDword1) { 3212 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 3213 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 3214 0); 3215 } 3216 3217 SDValue DataLo = buildSMovImm32(DAG, DL, 3218 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 3219 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 3220 3221 const SDValue Ops[] = { 3222 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 3223 PtrLo, 3224 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 3225 PtrHi, 3226 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 3227 DataLo, 3228 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 3229 DataHi, 3230 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 3231 }; 3232 3233 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 3234 } 3235 3236 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG, 3237 const TargetRegisterClass *RC, 3238 unsigned Reg, EVT VT) const { 3239 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT); 3240 3241 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()), 3242 cast<RegisterSDNode>(VReg)->getReg(), VT); 3243 } 3244 3245 //===----------------------------------------------------------------------===// 3246 // SI Inline Assembly Support 3247 //===----------------------------------------------------------------------===// 3248 3249 std::pair<unsigned, const TargetRegisterClass *> 3250 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 3251 StringRef Constraint, 3252 MVT VT) const { 3253 3254 if (Constraint.size() == 1) { 3255 switch (Constraint[0]) { 3256 case 's': 3257 case 'r': 3258 switch (VT.getSizeInBits()) { 3259 default: 3260 return std::make_pair(0U, nullptr); 3261 case 32: 3262 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass); 3263 case 64: 3264 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 3265 case 128: 3266 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 3267 case 256: 3268 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 3269 } 3270 3271 case 'v': 3272 switch (VT.getSizeInBits()) { 3273 default: 3274 return std::make_pair(0U, nullptr); 3275 case 32: 3276 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 3277 case 64: 3278 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 3279 case 96: 3280 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 3281 case 128: 3282 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 3283 case 256: 3284 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 3285 case 512: 3286 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 3287 } 3288 } 3289 } 3290 3291 if (Constraint.size() > 1) { 3292 const TargetRegisterClass *RC = nullptr; 3293 if (Constraint[1] == 'v') { 3294 RC = &AMDGPU::VGPR_32RegClass; 3295 } else if (Constraint[1] == 's') { 3296 RC = &AMDGPU::SGPR_32RegClass; 3297 } 3298 3299 if (RC) { 3300 uint32_t Idx; 3301 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 3302 if (!Failed && Idx < RC->getNumRegs()) 3303 return std::make_pair(RC->getRegister(Idx), RC); 3304 } 3305 } 3306 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 3307 } 3308 3309 SITargetLowering::ConstraintType 3310 SITargetLowering::getConstraintType(StringRef Constraint) const { 3311 if (Constraint.size() == 1) { 3312 switch (Constraint[0]) { 3313 default: break; 3314 case 's': 3315 case 'v': 3316 return C_RegisterClass; 3317 } 3318 } 3319 return TargetLowering::getConstraintType(Constraint); 3320 } 3321