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/CodeGen/Analysis.h" 35 #include "llvm/IR/DiagnosticInfo.h" 36 #include "llvm/IR/Function.h" 37 38 using namespace llvm; 39 40 static cl::opt<bool> EnableVGPRIndexMode( 41 "amdgpu-vgpr-index-mode", 42 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 43 cl::init(false)); 44 45 46 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 47 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 48 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 49 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 50 return AMDGPU::SGPR0 + Reg; 51 } 52 } 53 llvm_unreachable("Cannot allocate sgpr"); 54 } 55 56 SITargetLowering::SITargetLowering(const TargetMachine &TM, 57 const SISubtarget &STI) 58 : AMDGPUTargetLowering(TM, STI) { 59 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 60 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 61 62 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 63 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 64 65 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 66 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 67 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 68 69 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 70 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 71 72 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 73 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 74 75 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 76 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 77 78 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 79 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 80 81 if (Subtarget->has16BitInsts()) { 82 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 83 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 84 } 85 86 computeRegisterProperties(STI.getRegisterInfo()); 87 88 // We need to custom lower vector stores from local memory 89 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 90 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 91 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 92 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 93 setOperationAction(ISD::LOAD, MVT::i1, Custom); 94 95 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 96 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 97 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 98 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 99 setOperationAction(ISD::STORE, MVT::i1, Custom); 100 101 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 102 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 103 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 104 105 setOperationAction(ISD::SELECT, MVT::i1, Promote); 106 setOperationAction(ISD::SELECT, MVT::i64, Custom); 107 setOperationAction(ISD::SELECT, MVT::f64, Promote); 108 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 109 110 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 111 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 112 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 113 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 114 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 115 116 setOperationAction(ISD::SETCC, MVT::i1, Promote); 117 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 118 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 119 120 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 121 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 122 123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 125 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 126 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 127 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 130 131 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 132 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 133 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 134 135 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 136 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 137 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 138 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 139 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 140 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 141 142 // We only support LOAD/STORE and vector manipulation ops for vectors 143 // with > 4 elements. 144 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) { 145 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 146 switch (Op) { 147 case ISD::LOAD: 148 case ISD::STORE: 149 case ISD::BUILD_VECTOR: 150 case ISD::BITCAST: 151 case ISD::EXTRACT_VECTOR_ELT: 152 case ISD::INSERT_VECTOR_ELT: 153 case ISD::INSERT_SUBVECTOR: 154 case ISD::EXTRACT_SUBVECTOR: 155 case ISD::SCALAR_TO_VECTOR: 156 break; 157 case ISD::CONCAT_VECTORS: 158 setOperationAction(Op, VT, Custom); 159 break; 160 default: 161 setOperationAction(Op, VT, Expand); 162 break; 163 } 164 } 165 } 166 167 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 168 // is expanded to avoid having two separate loops in case the index is a VGPR. 169 170 // Most operations are naturally 32-bit vector operations. We only support 171 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 172 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 173 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 174 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 175 176 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 177 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 178 179 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 180 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 181 182 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 183 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 184 } 185 186 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 187 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 188 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 189 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 190 191 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 192 // and output demarshalling 193 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 194 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 195 196 // We can't return success/failure, only the old value, 197 // let LLVM add the comparison 198 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 199 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 200 201 if (getSubtarget()->hasFlatAddressSpace()) { 202 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 203 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 204 } 205 206 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 207 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 208 209 // On SI this is s_memtime and s_memrealtime on VI. 210 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 211 setOperationAction(ISD::TRAP, MVT::Other, Custom); 212 213 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 214 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 215 216 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) { 217 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 218 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 219 setOperationAction(ISD::FRINT, MVT::f64, Legal); 220 } 221 222 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 223 224 setOperationAction(ISD::FSIN, MVT::f32, Custom); 225 setOperationAction(ISD::FCOS, MVT::f32, Custom); 226 setOperationAction(ISD::FDIV, MVT::f32, Custom); 227 setOperationAction(ISD::FDIV, MVT::f64, Custom); 228 229 if (Subtarget->has16BitInsts()) { 230 setOperationAction(ISD::Constant, MVT::i16, Legal); 231 232 setOperationAction(ISD::SMIN, MVT::i16, Legal); 233 setOperationAction(ISD::SMAX, MVT::i16, Legal); 234 235 setOperationAction(ISD::UMIN, MVT::i16, Legal); 236 setOperationAction(ISD::UMAX, MVT::i16, Legal); 237 238 setOperationAction(ISD::SETCC, MVT::i16, Promote); 239 AddPromotedToType(ISD::SETCC, MVT::i16, MVT::i32); 240 241 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 242 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 243 244 setOperationAction(ISD::ROTR, MVT::i16, Promote); 245 setOperationAction(ISD::ROTL, MVT::i16, Promote); 246 247 setOperationAction(ISD::SDIV, MVT::i16, Promote); 248 setOperationAction(ISD::UDIV, MVT::i16, Promote); 249 setOperationAction(ISD::SREM, MVT::i16, Promote); 250 setOperationAction(ISD::UREM, MVT::i16, Promote); 251 252 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 253 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 254 255 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 256 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 257 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 258 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 259 260 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 261 262 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 263 264 setOperationAction(ISD::LOAD, MVT::i16, Custom); 265 266 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 267 268 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 269 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 270 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 271 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 272 273 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 274 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 275 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 276 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 277 278 // F16 - Constant Actions. 279 setOperationAction(ISD::ConstantFP, MVT::f16, Custom); 280 281 // F16 - Load/Store Actions. 282 setOperationAction(ISD::LOAD, MVT::f16, Promote); 283 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 284 setOperationAction(ISD::STORE, MVT::f16, Promote); 285 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 286 287 // F16 - VOP1 Actions. 288 setOperationAction(ISD::FCOS, MVT::f16, Promote); 289 setOperationAction(ISD::FSIN, MVT::f16, Promote); 290 291 // F16 - VOP2 Actions. 292 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 293 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 294 setOperationAction(ISD::FDIV, MVT::f16, Promote); 295 296 // F16 - VOP3 Actions. 297 setOperationAction(ISD::FMA, MVT::f16, Legal); 298 if (!Subtarget->hasFP16Denormals()) 299 setOperationAction(ISD::FMAD, MVT::f16, Legal); 300 } 301 302 setTargetDAGCombine(ISD::FADD); 303 setTargetDAGCombine(ISD::FSUB); 304 setTargetDAGCombine(ISD::FMINNUM); 305 setTargetDAGCombine(ISD::FMAXNUM); 306 setTargetDAGCombine(ISD::SMIN); 307 setTargetDAGCombine(ISD::SMAX); 308 setTargetDAGCombine(ISD::UMIN); 309 setTargetDAGCombine(ISD::UMAX); 310 setTargetDAGCombine(ISD::SETCC); 311 setTargetDAGCombine(ISD::AND); 312 setTargetDAGCombine(ISD::OR); 313 setTargetDAGCombine(ISD::XOR); 314 setTargetDAGCombine(ISD::SINT_TO_FP); 315 setTargetDAGCombine(ISD::UINT_TO_FP); 316 setTargetDAGCombine(ISD::FCANONICALIZE); 317 318 // All memory operations. Some folding on the pointer operand is done to help 319 // matching the constant offsets in the addressing modes. 320 setTargetDAGCombine(ISD::LOAD); 321 setTargetDAGCombine(ISD::STORE); 322 setTargetDAGCombine(ISD::ATOMIC_LOAD); 323 setTargetDAGCombine(ISD::ATOMIC_STORE); 324 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 325 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 326 setTargetDAGCombine(ISD::ATOMIC_SWAP); 327 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 328 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 329 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 330 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 331 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 332 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 333 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 334 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 335 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 336 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 337 338 setSchedulingPreference(Sched::RegPressure); 339 } 340 341 const SISubtarget *SITargetLowering::getSubtarget() const { 342 return static_cast<const SISubtarget *>(Subtarget); 343 } 344 345 //===----------------------------------------------------------------------===// 346 // TargetLowering queries 347 //===----------------------------------------------------------------------===// 348 349 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 350 const CallInst &CI, 351 unsigned IntrID) const { 352 switch (IntrID) { 353 case Intrinsic::amdgcn_atomic_inc: 354 case Intrinsic::amdgcn_atomic_dec: 355 Info.opc = ISD::INTRINSIC_W_CHAIN; 356 Info.memVT = MVT::getVT(CI.getType()); 357 Info.ptrVal = CI.getOperand(0); 358 Info.align = 0; 359 Info.vol = false; 360 Info.readMem = true; 361 Info.writeMem = true; 362 return true; 363 default: 364 return false; 365 } 366 } 367 368 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &, 369 EVT) const { 370 // SI has some legal vector types, but no legal vector operations. Say no 371 // shuffles are legal in order to prefer scalarizing some vector operations. 372 return false; 373 } 374 375 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 376 // Flat instructions do not have offsets, and only have the register 377 // address. 378 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1); 379 } 380 381 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 382 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 383 // additionally can do r + r + i with addr64. 32-bit has more addressing 384 // mode options. Depending on the resource constant, it can also do 385 // (i64 r0) + (i32 r1) * (i14 i). 386 // 387 // Private arrays end up using a scratch buffer most of the time, so also 388 // assume those use MUBUF instructions. Scratch loads / stores are currently 389 // implemented as mubuf instructions with offen bit set, so slightly 390 // different than the normal addr64. 391 if (!isUInt<12>(AM.BaseOffs)) 392 return false; 393 394 // FIXME: Since we can split immediate into soffset and immediate offset, 395 // would it make sense to allow any immediate? 396 397 switch (AM.Scale) { 398 case 0: // r + i or just i, depending on HasBaseReg. 399 return true; 400 case 1: 401 return true; // We have r + r or r + i. 402 case 2: 403 if (AM.HasBaseReg) { 404 // Reject 2 * r + r. 405 return false; 406 } 407 408 // Allow 2 * r as r + r 409 // Or 2 * r + i is allowed as r + r + i. 410 return true; 411 default: // Don't allow n * r 412 return false; 413 } 414 } 415 416 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 417 const AddrMode &AM, Type *Ty, 418 unsigned AS) const { 419 // No global is ever allowed as a base. 420 if (AM.BaseGV) 421 return false; 422 423 switch (AS) { 424 case AMDGPUAS::GLOBAL_ADDRESS: { 425 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 426 // Assume the we will use FLAT for all global memory accesses 427 // on VI. 428 // FIXME: This assumption is currently wrong. On VI we still use 429 // MUBUF instructions for the r + i addressing mode. As currently 430 // implemented, the MUBUF instructions only work on buffer < 4GB. 431 // It may be possible to support > 4GB buffers with MUBUF instructions, 432 // by setting the stride value in the resource descriptor which would 433 // increase the size limit to (stride * 4GB). However, this is risky, 434 // because it has never been validated. 435 return isLegalFlatAddressingMode(AM); 436 } 437 438 return isLegalMUBUFAddressingMode(AM); 439 } 440 case AMDGPUAS::CONSTANT_ADDRESS: { 441 // If the offset isn't a multiple of 4, it probably isn't going to be 442 // correctly aligned. 443 // FIXME: Can we get the real alignment here? 444 if (AM.BaseOffs % 4 != 0) 445 return isLegalMUBUFAddressingMode(AM); 446 447 // There are no SMRD extloads, so if we have to do a small type access we 448 // will use a MUBUF load. 449 // FIXME?: We also need to do this if unaligned, but we don't know the 450 // alignment here. 451 if (DL.getTypeStoreSize(Ty) < 4) 452 return isLegalMUBUFAddressingMode(AM); 453 454 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 455 // SMRD instructions have an 8-bit, dword offset on SI. 456 if (!isUInt<8>(AM.BaseOffs / 4)) 457 return false; 458 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) { 459 // On CI+, this can also be a 32-bit literal constant offset. If it fits 460 // in 8-bits, it can use a smaller encoding. 461 if (!isUInt<32>(AM.BaseOffs / 4)) 462 return false; 463 } else if (Subtarget->getGeneration() == SISubtarget::VOLCANIC_ISLANDS) { 464 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 465 if (!isUInt<20>(AM.BaseOffs)) 466 return false; 467 } else 468 llvm_unreachable("unhandled generation"); 469 470 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 471 return true; 472 473 if (AM.Scale == 1 && AM.HasBaseReg) 474 return true; 475 476 return false; 477 } 478 479 case AMDGPUAS::PRIVATE_ADDRESS: 480 return isLegalMUBUFAddressingMode(AM); 481 482 case AMDGPUAS::LOCAL_ADDRESS: 483 case AMDGPUAS::REGION_ADDRESS: { 484 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 485 // field. 486 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 487 // an 8-bit dword offset but we don't know the alignment here. 488 if (!isUInt<16>(AM.BaseOffs)) 489 return false; 490 491 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 492 return true; 493 494 if (AM.Scale == 1 && AM.HasBaseReg) 495 return true; 496 497 return false; 498 } 499 case AMDGPUAS::FLAT_ADDRESS: 500 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE: 501 // For an unknown address space, this usually means that this is for some 502 // reason being used for pure arithmetic, and not based on some addressing 503 // computation. We don't have instructions that compute pointers with any 504 // addressing modes, so treat them as having no offset like flat 505 // instructions. 506 return isLegalFlatAddressingMode(AM); 507 508 default: 509 llvm_unreachable("unhandled address space"); 510 } 511 } 512 513 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 514 unsigned AddrSpace, 515 unsigned Align, 516 bool *IsFast) const { 517 if (IsFast) 518 *IsFast = false; 519 520 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 521 // which isn't a simple VT. 522 // Until MVT is extended to handle this, simply check for the size and 523 // rely on the condition below: allow accesses if the size is a multiple of 4. 524 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 525 VT.getStoreSize() > 16)) { 526 return false; 527 } 528 529 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 530 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 531 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 532 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 533 // with adjacent offsets. 534 bool AlignedBy4 = (Align % 4 == 0); 535 if (IsFast) 536 *IsFast = AlignedBy4; 537 538 return AlignedBy4; 539 } 540 541 // FIXME: We have to be conservative here and assume that flat operations 542 // will access scratch. If we had access to the IR function, then we 543 // could determine if any private memory was used in the function. 544 if (!Subtarget->hasUnalignedScratchAccess() && 545 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 546 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 547 return false; 548 } 549 550 if (Subtarget->hasUnalignedBufferAccess()) { 551 // If we have an uniform constant load, it still requires using a slow 552 // buffer instruction if unaligned. 553 if (IsFast) { 554 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) ? 555 (Align % 4 == 0) : true; 556 } 557 558 return true; 559 } 560 561 // Smaller than dword value must be aligned. 562 if (VT.bitsLT(MVT::i32)) 563 return false; 564 565 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 566 // byte-address are ignored, thus forcing Dword alignment. 567 // This applies to private, global, and constant memory. 568 if (IsFast) 569 *IsFast = true; 570 571 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 572 } 573 574 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 575 unsigned SrcAlign, bool IsMemset, 576 bool ZeroMemset, 577 bool MemcpyStrSrc, 578 MachineFunction &MF) const { 579 // FIXME: Should account for address space here. 580 581 // The default fallback uses the private pointer size as a guess for a type to 582 // use. Make sure we switch these to 64-bit accesses. 583 584 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 585 return MVT::v4i32; 586 587 if (Size >= 8 && DstAlign >= 4) 588 return MVT::v2i32; 589 590 // Use the default. 591 return MVT::Other; 592 } 593 594 static bool isFlatGlobalAddrSpace(unsigned AS) { 595 return AS == AMDGPUAS::GLOBAL_ADDRESS || 596 AS == AMDGPUAS::FLAT_ADDRESS || 597 AS == AMDGPUAS::CONSTANT_ADDRESS; 598 } 599 600 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 601 unsigned DestAS) const { 602 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 603 } 604 605 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 606 const MemSDNode *MemNode = cast<MemSDNode>(N); 607 const Value *Ptr = MemNode->getMemOperand()->getValue(); 608 609 // UndefValue means this is a load of a kernel input. These are uniform. 610 // Sometimes LDS instructions have constant pointers. 611 // If Ptr is null, then that means this mem operand contains a 612 // PseudoSourceValue like GOT. 613 if (!Ptr || isa<UndefValue>(Ptr) || isa<Argument>(Ptr) || 614 isa<Constant>(Ptr) || isa<GlobalValue>(Ptr)) 615 return true; 616 617 const Instruction *I = dyn_cast<Instruction>(Ptr); 618 return I && I->getMetadata("amdgpu.uniform"); 619 } 620 621 TargetLoweringBase::LegalizeTypeAction 622 SITargetLowering::getPreferredVectorAction(EVT VT) const { 623 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 624 return TypeSplitVector; 625 626 return TargetLoweringBase::getPreferredVectorAction(VT); 627 } 628 629 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 630 Type *Ty) const { 631 // FIXME: Could be smarter if called for vector constants. 632 return true; 633 } 634 635 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 636 637 // i16 is not desirable unless it is a load or a store. 638 if (VT == MVT::i16 && Op != ISD::LOAD && Op != ISD::STORE) 639 return false; 640 641 // SimplifySetCC uses this function to determine whether or not it should 642 // create setcc with i1 operands. We don't have instructions for i1 setcc. 643 if (VT == MVT::i1 && Op == ISD::SETCC) 644 return false; 645 646 return TargetLowering::isTypeDesirableForOp(Op, VT); 647 } 648 649 SDValue SITargetLowering::LowerParameterPtr(SelectionDAG &DAG, 650 const SDLoc &SL, SDValue Chain, 651 unsigned Offset) const { 652 const DataLayout &DL = DAG.getDataLayout(); 653 MachineFunction &MF = DAG.getMachineFunction(); 654 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 655 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 656 657 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 658 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 659 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 660 MRI.getLiveInVirtReg(InputPtrReg), PtrVT); 661 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 662 DAG.getConstant(Offset, SL, PtrVT)); 663 } 664 665 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT, 666 const SDLoc &SL, SDValue Chain, 667 unsigned Offset, bool Signed) const { 668 const DataLayout &DL = DAG.getDataLayout(); 669 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 670 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 671 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 672 673 unsigned Align = DL.getABITypeAlignment(Ty); 674 675 SDValue Ptr = LowerParameterPtr(DAG, SL, Chain, Offset); 676 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 677 MachineMemOperand::MONonTemporal | 678 MachineMemOperand::MODereferenceable | 679 MachineMemOperand::MOInvariant); 680 681 SDValue Val; 682 if (MemVT.isFloatingPoint()) 683 Val = getFPExtOrFPTrunc(DAG, Load, SL, VT); 684 else if (Signed) 685 Val = DAG.getSExtOrTrunc(Load, SL, VT); 686 else 687 Val = DAG.getZExtOrTrunc(Load, SL, VT); 688 689 SDValue Ops[] = { 690 Val, 691 Load.getValue(1) 692 }; 693 694 return DAG.getMergeValues(Ops, SL); 695 } 696 697 SDValue SITargetLowering::LowerFormalArguments( 698 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 699 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 700 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 701 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 702 703 MachineFunction &MF = DAG.getMachineFunction(); 704 FunctionType *FType = MF.getFunction()->getFunctionType(); 705 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 706 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 707 708 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 709 const Function *Fn = MF.getFunction(); 710 DiagnosticInfoUnsupported NoGraphicsHSA( 711 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 712 DAG.getContext()->diagnose(NoGraphicsHSA); 713 return DAG.getEntryNode(); 714 } 715 716 // Create stack objects that are used for emitting debugger prologue if 717 // "amdgpu-debugger-emit-prologue" attribute was specified. 718 if (ST.debuggerEmitPrologue()) 719 createDebuggerPrologueStackObjects(MF); 720 721 SmallVector<ISD::InputArg, 16> Splits; 722 BitVector Skipped(Ins.size()); 723 724 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) { 725 const ISD::InputArg &Arg = Ins[i]; 726 727 // First check if it's a PS input addr 728 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 729 !Arg.Flags.isByVal() && PSInputNum <= 15) { 730 731 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 732 // We can safely skip PS inputs 733 Skipped.set(i); 734 ++PSInputNum; 735 continue; 736 } 737 738 Info->markPSInputAllocated(PSInputNum); 739 if (Arg.Used) 740 Info->PSInputEna |= 1 << PSInputNum; 741 742 ++PSInputNum; 743 } 744 745 if (AMDGPU::isShader(CallConv)) { 746 // Second split vertices into their elements 747 if (Arg.VT.isVector()) { 748 ISD::InputArg NewArg = Arg; 749 NewArg.Flags.setSplit(); 750 NewArg.VT = Arg.VT.getVectorElementType(); 751 752 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 753 // three or five element vertex only needs three or five registers, 754 // NOT four or eight. 755 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 756 unsigned NumElements = ParamType->getVectorNumElements(); 757 758 for (unsigned j = 0; j != NumElements; ++j) { 759 Splits.push_back(NewArg); 760 NewArg.PartOffset += NewArg.VT.getStoreSize(); 761 } 762 } else { 763 Splits.push_back(Arg); 764 } 765 } 766 } 767 768 SmallVector<CCValAssign, 16> ArgLocs; 769 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 770 *DAG.getContext()); 771 772 // At least one interpolation mode must be enabled or else the GPU will hang. 773 // 774 // Check PSInputAddr instead of PSInputEna. The idea is that if the user set 775 // PSInputAddr, the user wants to enable some bits after the compilation 776 // based on run-time states. Since we can't know what the final PSInputEna 777 // will look like, so we shouldn't do anything here and the user should take 778 // responsibility for the correct programming. 779 // 780 // Otherwise, the following restrictions apply: 781 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 782 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 783 // enabled too. 784 if (CallConv == CallingConv::AMDGPU_PS && 785 ((Info->getPSInputAddr() & 0x7F) == 0 || 786 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11)))) { 787 CCInfo.AllocateReg(AMDGPU::VGPR0); 788 CCInfo.AllocateReg(AMDGPU::VGPR1); 789 Info->markPSInputAllocated(0); 790 Info->PSInputEna |= 1; 791 } 792 793 if (!AMDGPU::isShader(CallConv)) { 794 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 795 } else { 796 assert(!Info->hasPrivateSegmentBuffer() && !Info->hasDispatchPtr() && 797 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 798 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 799 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 800 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 801 !Info->hasWorkItemIDZ()); 802 } 803 804 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 805 if (Info->hasPrivateSegmentBuffer()) { 806 unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI); 807 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass); 808 CCInfo.AllocateReg(PrivateSegmentBufferReg); 809 } 810 811 if (Info->hasDispatchPtr()) { 812 unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI); 813 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass); 814 CCInfo.AllocateReg(DispatchPtrReg); 815 } 816 817 if (Info->hasQueuePtr()) { 818 unsigned QueuePtrReg = Info->addQueuePtr(*TRI); 819 MF.addLiveIn(QueuePtrReg, &AMDGPU::SReg_64RegClass); 820 CCInfo.AllocateReg(QueuePtrReg); 821 } 822 823 if (Info->hasKernargSegmentPtr()) { 824 unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI); 825 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass); 826 CCInfo.AllocateReg(InputPtrReg); 827 } 828 829 if (Info->hasDispatchID()) { 830 unsigned DispatchIDReg = Info->addDispatchID(*TRI); 831 MF.addLiveIn(DispatchIDReg, &AMDGPU::SReg_64RegClass); 832 CCInfo.AllocateReg(DispatchIDReg); 833 } 834 835 if (Info->hasFlatScratchInit()) { 836 unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI); 837 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SReg_64RegClass); 838 CCInfo.AllocateReg(FlatScratchInitReg); 839 } 840 841 if (!AMDGPU::isShader(CallConv)) 842 analyzeFormalArgumentsCompute(CCInfo, Ins); 843 else 844 AnalyzeFormalArguments(CCInfo, Splits); 845 846 SmallVector<SDValue, 16> Chains; 847 848 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 849 850 const ISD::InputArg &Arg = Ins[i]; 851 if (Skipped[i]) { 852 InVals.push_back(DAG.getUNDEF(Arg.VT)); 853 continue; 854 } 855 856 CCValAssign &VA = ArgLocs[ArgIdx++]; 857 MVT VT = VA.getLocVT(); 858 859 if (VA.isMemLoc()) { 860 VT = Ins[i].VT; 861 EVT MemVT = VA.getLocVT(); 862 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() + 863 VA.getLocMemOffset(); 864 // The first 36 bytes of the input buffer contains information about 865 // thread group and global sizes. 866 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain, 867 Offset, Ins[i].Flags.isSExt()); 868 Chains.push_back(Arg.getValue(1)); 869 870 auto *ParamTy = 871 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 872 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 873 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 874 // On SI local pointers are just offsets into LDS, so they are always 875 // less than 16-bits. On CI and newer they could potentially be 876 // real pointers, so we can't guarantee their size. 877 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 878 DAG.getValueType(MVT::i16)); 879 } 880 881 InVals.push_back(Arg); 882 Info->setABIArgOffset(Offset + MemVT.getStoreSize()); 883 continue; 884 } 885 assert(VA.isRegLoc() && "Parameter must be in a register!"); 886 887 unsigned Reg = VA.getLocReg(); 888 889 if (VT == MVT::i64) { 890 // For now assume it is a pointer 891 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, 892 &AMDGPU::SReg_64RegClass); 893 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass); 894 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 895 InVals.push_back(Copy); 896 continue; 897 } 898 899 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 900 901 Reg = MF.addLiveIn(Reg, RC); 902 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 903 904 if (Arg.VT.isVector()) { 905 906 // Build a vector from the registers 907 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 908 unsigned NumElements = ParamType->getVectorNumElements(); 909 910 SmallVector<SDValue, 4> Regs; 911 Regs.push_back(Val); 912 for (unsigned j = 1; j != NumElements; ++j) { 913 Reg = ArgLocs[ArgIdx++].getLocReg(); 914 Reg = MF.addLiveIn(Reg, RC); 915 916 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 917 Regs.push_back(Copy); 918 } 919 920 // Fill up the missing vector elements 921 NumElements = Arg.VT.getVectorNumElements() - NumElements; 922 Regs.append(NumElements, DAG.getUNDEF(VT)); 923 924 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 925 continue; 926 } 927 928 InVals.push_back(Val); 929 } 930 931 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 932 // these from the dispatch pointer. 933 934 // Start adding system SGPRs. 935 if (Info->hasWorkGroupIDX()) { 936 unsigned Reg = Info->addWorkGroupIDX(); 937 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 938 CCInfo.AllocateReg(Reg); 939 } 940 941 if (Info->hasWorkGroupIDY()) { 942 unsigned Reg = Info->addWorkGroupIDY(); 943 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 944 CCInfo.AllocateReg(Reg); 945 } 946 947 if (Info->hasWorkGroupIDZ()) { 948 unsigned Reg = Info->addWorkGroupIDZ(); 949 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 950 CCInfo.AllocateReg(Reg); 951 } 952 953 if (Info->hasWorkGroupInfo()) { 954 unsigned Reg = Info->addWorkGroupInfo(); 955 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass); 956 CCInfo.AllocateReg(Reg); 957 } 958 959 if (Info->hasPrivateSegmentWaveByteOffset()) { 960 // Scratch wave offset passed in system SGPR. 961 unsigned PrivateSegmentWaveByteOffsetReg; 962 963 if (AMDGPU::isShader(CallConv)) { 964 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 965 Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 966 } else 967 PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset(); 968 969 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 970 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 971 } 972 973 // Now that we've figured out where the scratch register inputs are, see if 974 // should reserve the arguments and use them directly. 975 bool HasStackObjects = MF.getFrameInfo().hasStackObjects(); 976 // Record that we know we have non-spill stack objects so we don't need to 977 // check all stack objects later. 978 if (HasStackObjects) 979 Info->setHasNonSpillStackObjects(true); 980 981 // Everything live out of a block is spilled with fast regalloc, so it's 982 // almost certain that spilling will be required. 983 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 984 HasStackObjects = true; 985 986 if (ST.isAmdCodeObjectV2()) { 987 if (HasStackObjects) { 988 // If we have stack objects, we unquestionably need the private buffer 989 // resource. For the Code Object V2 ABI, this will be the first 4 user 990 // SGPR inputs. We can reserve those and use them directly. 991 992 unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue( 993 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER); 994 Info->setScratchRSrcReg(PrivateSegmentBufferReg); 995 996 unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue( 997 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 998 Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 999 } else { 1000 unsigned ReservedBufferReg 1001 = TRI->reservedPrivateSegmentBufferReg(MF); 1002 unsigned ReservedOffsetReg 1003 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 1004 1005 // We tentatively reserve the last registers (skipping the last two 1006 // which may contain VCC). After register allocation, we'll replace 1007 // these with the ones immediately after those which were really 1008 // allocated. In the prologue copies will be inserted from the argument 1009 // to these reserved registers. 1010 Info->setScratchRSrcReg(ReservedBufferReg); 1011 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 1012 } 1013 } else { 1014 unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF); 1015 1016 // Without HSA, relocations are used for the scratch pointer and the 1017 // buffer resource setup is always inserted in the prologue. Scratch wave 1018 // offset is still in an input SGPR. 1019 Info->setScratchRSrcReg(ReservedBufferReg); 1020 1021 if (HasStackObjects) { 1022 unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue( 1023 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1024 Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg); 1025 } else { 1026 unsigned ReservedOffsetReg 1027 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 1028 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 1029 } 1030 } 1031 1032 if (Info->hasWorkItemIDX()) { 1033 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X); 1034 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1035 CCInfo.AllocateReg(Reg); 1036 } 1037 1038 if (Info->hasWorkItemIDY()) { 1039 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y); 1040 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1041 CCInfo.AllocateReg(Reg); 1042 } 1043 1044 if (Info->hasWorkItemIDZ()) { 1045 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z); 1046 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1047 CCInfo.AllocateReg(Reg); 1048 } 1049 1050 if (Chains.empty()) 1051 return Chain; 1052 1053 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 1054 } 1055 1056 SDValue 1057 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1058 bool isVarArg, 1059 const SmallVectorImpl<ISD::OutputArg> &Outs, 1060 const SmallVectorImpl<SDValue> &OutVals, 1061 const SDLoc &DL, SelectionDAG &DAG) const { 1062 MachineFunction &MF = DAG.getMachineFunction(); 1063 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1064 1065 if (!AMDGPU::isShader(CallConv)) 1066 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 1067 OutVals, DL, DAG); 1068 1069 Info->setIfReturnsVoid(Outs.size() == 0); 1070 1071 SmallVector<ISD::OutputArg, 48> Splits; 1072 SmallVector<SDValue, 48> SplitVals; 1073 1074 // Split vectors into their elements. 1075 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 1076 const ISD::OutputArg &Out = Outs[i]; 1077 1078 if (Out.VT.isVector()) { 1079 MVT VT = Out.VT.getVectorElementType(); 1080 ISD::OutputArg NewOut = Out; 1081 NewOut.Flags.setSplit(); 1082 NewOut.VT = VT; 1083 1084 // We want the original number of vector elements here, e.g. 1085 // three or five, not four or eight. 1086 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 1087 1088 for (unsigned j = 0; j != NumElements; ++j) { 1089 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 1090 DAG.getConstant(j, DL, MVT::i32)); 1091 SplitVals.push_back(Elem); 1092 Splits.push_back(NewOut); 1093 NewOut.PartOffset += NewOut.VT.getStoreSize(); 1094 } 1095 } else { 1096 SplitVals.push_back(OutVals[i]); 1097 Splits.push_back(Out); 1098 } 1099 } 1100 1101 // CCValAssign - represent the assignment of the return value to a location. 1102 SmallVector<CCValAssign, 48> RVLocs; 1103 1104 // CCState - Info about the registers and stack slots. 1105 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1106 *DAG.getContext()); 1107 1108 // Analyze outgoing return values. 1109 AnalyzeReturn(CCInfo, Splits); 1110 1111 SDValue Flag; 1112 SmallVector<SDValue, 48> RetOps; 1113 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1114 1115 // Copy the result values into the output registers. 1116 for (unsigned i = 0, realRVLocIdx = 0; 1117 i != RVLocs.size(); 1118 ++i, ++realRVLocIdx) { 1119 CCValAssign &VA = RVLocs[i]; 1120 assert(VA.isRegLoc() && "Can only return in registers!"); 1121 1122 SDValue Arg = SplitVals[realRVLocIdx]; 1123 1124 // Copied from other backends. 1125 switch (VA.getLocInfo()) { 1126 default: llvm_unreachable("Unknown loc info!"); 1127 case CCValAssign::Full: 1128 break; 1129 case CCValAssign::BCvt: 1130 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 1131 break; 1132 } 1133 1134 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 1135 Flag = Chain.getValue(1); 1136 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1137 } 1138 1139 // Update chain and glue. 1140 RetOps[0] = Chain; 1141 if (Flag.getNode()) 1142 RetOps.push_back(Flag); 1143 1144 unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN; 1145 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 1146 } 1147 1148 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 1149 SelectionDAG &DAG) const { 1150 unsigned Reg = StringSwitch<unsigned>(RegName) 1151 .Case("m0", AMDGPU::M0) 1152 .Case("exec", AMDGPU::EXEC) 1153 .Case("exec_lo", AMDGPU::EXEC_LO) 1154 .Case("exec_hi", AMDGPU::EXEC_HI) 1155 .Case("flat_scratch", AMDGPU::FLAT_SCR) 1156 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 1157 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 1158 .Default(AMDGPU::NoRegister); 1159 1160 if (Reg == AMDGPU::NoRegister) { 1161 report_fatal_error(Twine("invalid register name \"" 1162 + StringRef(RegName) + "\".")); 1163 1164 } 1165 1166 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1167 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 1168 report_fatal_error(Twine("invalid register \"" 1169 + StringRef(RegName) + "\" for subtarget.")); 1170 } 1171 1172 switch (Reg) { 1173 case AMDGPU::M0: 1174 case AMDGPU::EXEC_LO: 1175 case AMDGPU::EXEC_HI: 1176 case AMDGPU::FLAT_SCR_LO: 1177 case AMDGPU::FLAT_SCR_HI: 1178 if (VT.getSizeInBits() == 32) 1179 return Reg; 1180 break; 1181 case AMDGPU::EXEC: 1182 case AMDGPU::FLAT_SCR: 1183 if (VT.getSizeInBits() == 64) 1184 return Reg; 1185 break; 1186 default: 1187 llvm_unreachable("missing register type checking"); 1188 } 1189 1190 report_fatal_error(Twine("invalid type for register \"" 1191 + StringRef(RegName) + "\".")); 1192 } 1193 1194 // If kill is not the last instruction, split the block so kill is always a 1195 // proper terminator. 1196 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 1197 MachineBasicBlock *BB) const { 1198 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1199 1200 MachineBasicBlock::iterator SplitPoint(&MI); 1201 ++SplitPoint; 1202 1203 if (SplitPoint == BB->end()) { 1204 // Don't bother with a new block. 1205 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 1206 return BB; 1207 } 1208 1209 MachineFunction *MF = BB->getParent(); 1210 MachineBasicBlock *SplitBB 1211 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 1212 1213 MF->insert(++MachineFunction::iterator(BB), SplitBB); 1214 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 1215 1216 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 1217 BB->addSuccessor(SplitBB); 1218 1219 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 1220 return SplitBB; 1221 } 1222 1223 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 1224 // wavefront. If the value is uniform and just happens to be in a VGPR, this 1225 // will only do one iteration. In the worst case, this will loop 64 times. 1226 // 1227 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 1228 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 1229 const SIInstrInfo *TII, 1230 MachineRegisterInfo &MRI, 1231 MachineBasicBlock &OrigBB, 1232 MachineBasicBlock &LoopBB, 1233 const DebugLoc &DL, 1234 const MachineOperand &IdxReg, 1235 unsigned InitReg, 1236 unsigned ResultReg, 1237 unsigned PhiReg, 1238 unsigned InitSaveExecReg, 1239 int Offset, 1240 bool UseGPRIdxMode) { 1241 MachineBasicBlock::iterator I = LoopBB.begin(); 1242 1243 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1244 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1245 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 1246 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1247 1248 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 1249 .addReg(InitReg) 1250 .addMBB(&OrigBB) 1251 .addReg(ResultReg) 1252 .addMBB(&LoopBB); 1253 1254 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 1255 .addReg(InitSaveExecReg) 1256 .addMBB(&OrigBB) 1257 .addReg(NewExec) 1258 .addMBB(&LoopBB); 1259 1260 // Read the next variant <- also loop target. 1261 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 1262 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 1263 1264 // Compare the just read M0 value to all possible Idx values. 1265 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 1266 .addReg(CurrentIdxReg) 1267 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 1268 1269 if (UseGPRIdxMode) { 1270 unsigned IdxReg; 1271 if (Offset == 0) { 1272 IdxReg = CurrentIdxReg; 1273 } else { 1274 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 1275 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 1276 .addReg(CurrentIdxReg, RegState::Kill) 1277 .addImm(Offset); 1278 } 1279 1280 MachineInstr *SetIdx = 1281 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX)) 1282 .addReg(IdxReg, RegState::Kill); 1283 SetIdx->getOperand(2).setIsUndef(); 1284 } else { 1285 // Move index from VCC into M0 1286 if (Offset == 0) { 1287 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1288 .addReg(CurrentIdxReg, RegState::Kill); 1289 } else { 1290 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 1291 .addReg(CurrentIdxReg, RegState::Kill) 1292 .addImm(Offset); 1293 } 1294 } 1295 1296 // Update EXEC, save the original EXEC value to VCC. 1297 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 1298 .addReg(CondReg, RegState::Kill); 1299 1300 MRI.setSimpleHint(NewExec, CondReg); 1301 1302 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 1303 MachineInstr *InsertPt = 1304 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 1305 .addReg(AMDGPU::EXEC) 1306 .addReg(NewExec); 1307 1308 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 1309 // s_cbranch_scc0? 1310 1311 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 1312 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 1313 .addMBB(&LoopBB); 1314 1315 return InsertPt->getIterator(); 1316 } 1317 1318 // This has slightly sub-optimal regalloc when the source vector is killed by 1319 // the read. The register allocator does not understand that the kill is 1320 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 1321 // subregister from it, using 1 more VGPR than necessary. This was saved when 1322 // this was expanded after register allocation. 1323 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 1324 MachineBasicBlock &MBB, 1325 MachineInstr &MI, 1326 unsigned InitResultReg, 1327 unsigned PhiReg, 1328 int Offset, 1329 bool UseGPRIdxMode) { 1330 MachineFunction *MF = MBB.getParent(); 1331 MachineRegisterInfo &MRI = MF->getRegInfo(); 1332 const DebugLoc &DL = MI.getDebugLoc(); 1333 MachineBasicBlock::iterator I(&MI); 1334 1335 unsigned DstReg = MI.getOperand(0).getReg(); 1336 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1337 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1338 1339 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 1340 1341 // Save the EXEC mask 1342 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 1343 .addReg(AMDGPU::EXEC); 1344 1345 // To insert the loop we need to split the block. Move everything after this 1346 // point to a new block, and insert a new empty block between the two. 1347 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 1348 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 1349 MachineFunction::iterator MBBI(MBB); 1350 ++MBBI; 1351 1352 MF->insert(MBBI, LoopBB); 1353 MF->insert(MBBI, RemainderBB); 1354 1355 LoopBB->addSuccessor(LoopBB); 1356 LoopBB->addSuccessor(RemainderBB); 1357 1358 // Move the rest of the block into a new block. 1359 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 1360 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 1361 1362 MBB.addSuccessor(LoopBB); 1363 1364 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1365 1366 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 1367 InitResultReg, DstReg, PhiReg, TmpExec, 1368 Offset, UseGPRIdxMode); 1369 1370 MachineBasicBlock::iterator First = RemainderBB->begin(); 1371 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 1372 .addReg(SaveExec); 1373 1374 return InsPt; 1375 } 1376 1377 // Returns subreg index, offset 1378 static std::pair<unsigned, int> 1379 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 1380 const TargetRegisterClass *SuperRC, 1381 unsigned VecReg, 1382 int Offset) { 1383 int NumElts = SuperRC->getSize() / 4; 1384 1385 // Skip out of bounds offsets, or else we would end up using an undefined 1386 // register. 1387 if (Offset >= NumElts || Offset < 0) 1388 return std::make_pair(AMDGPU::sub0, Offset); 1389 1390 return std::make_pair(AMDGPU::sub0 + Offset, 0); 1391 } 1392 1393 // Return true if the index is an SGPR and was set. 1394 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 1395 MachineRegisterInfo &MRI, 1396 MachineInstr &MI, 1397 int Offset, 1398 bool UseGPRIdxMode, 1399 bool IsIndirectSrc) { 1400 MachineBasicBlock *MBB = MI.getParent(); 1401 const DebugLoc &DL = MI.getDebugLoc(); 1402 MachineBasicBlock::iterator I(&MI); 1403 1404 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1405 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 1406 1407 assert(Idx->getReg() != AMDGPU::NoRegister); 1408 1409 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 1410 return false; 1411 1412 if (UseGPRIdxMode) { 1413 unsigned IdxMode = IsIndirectSrc ? 1414 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 1415 if (Offset == 0) { 1416 MachineInstr *SetOn = 1417 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1418 .addOperand(*Idx) 1419 .addImm(IdxMode); 1420 1421 SetOn->getOperand(3).setIsUndef(); 1422 } else { 1423 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 1424 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 1425 .addOperand(*Idx) 1426 .addImm(Offset); 1427 MachineInstr *SetOn = 1428 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1429 .addReg(Tmp, RegState::Kill) 1430 .addImm(IdxMode); 1431 1432 SetOn->getOperand(3).setIsUndef(); 1433 } 1434 1435 return true; 1436 } 1437 1438 if (Offset == 0) { 1439 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1440 .addOperand(*Idx); 1441 } else { 1442 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 1443 .addOperand(*Idx) 1444 .addImm(Offset); 1445 } 1446 1447 return true; 1448 } 1449 1450 // Control flow needs to be inserted if indexing with a VGPR. 1451 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 1452 MachineBasicBlock &MBB, 1453 const SISubtarget &ST) { 1454 const SIInstrInfo *TII = ST.getInstrInfo(); 1455 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 1456 MachineFunction *MF = MBB.getParent(); 1457 MachineRegisterInfo &MRI = MF->getRegInfo(); 1458 1459 unsigned Dst = MI.getOperand(0).getReg(); 1460 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 1461 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 1462 1463 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 1464 1465 unsigned SubReg; 1466 std::tie(SubReg, Offset) 1467 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 1468 1469 bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode; 1470 1471 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 1472 MachineBasicBlock::iterator I(&MI); 1473 const DebugLoc &DL = MI.getDebugLoc(); 1474 1475 if (UseGPRIdxMode) { 1476 // TODO: Look at the uses to avoid the copy. This may require rescheduling 1477 // to avoid interfering with other uses, so probably requires a new 1478 // optimization pass. 1479 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 1480 .addReg(SrcReg, RegState::Undef, SubReg) 1481 .addReg(SrcReg, RegState::Implicit) 1482 .addReg(AMDGPU::M0, RegState::Implicit); 1483 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1484 } else { 1485 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 1486 .addReg(SrcReg, RegState::Undef, SubReg) 1487 .addReg(SrcReg, RegState::Implicit); 1488 } 1489 1490 MI.eraseFromParent(); 1491 1492 return &MBB; 1493 } 1494 1495 1496 const DebugLoc &DL = MI.getDebugLoc(); 1497 MachineBasicBlock::iterator I(&MI); 1498 1499 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1500 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1501 1502 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 1503 1504 if (UseGPRIdxMode) { 1505 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1506 .addImm(0) // Reset inside loop. 1507 .addImm(VGPRIndexMode::SRC0_ENABLE); 1508 SetOn->getOperand(3).setIsUndef(); 1509 1510 // Disable again after the loop. 1511 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1512 } 1513 1514 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode); 1515 MachineBasicBlock *LoopBB = InsPt->getParent(); 1516 1517 if (UseGPRIdxMode) { 1518 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 1519 .addReg(SrcReg, RegState::Undef, SubReg) 1520 .addReg(SrcReg, RegState::Implicit) 1521 .addReg(AMDGPU::M0, RegState::Implicit); 1522 } else { 1523 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 1524 .addReg(SrcReg, RegState::Undef, SubReg) 1525 .addReg(SrcReg, RegState::Implicit); 1526 } 1527 1528 MI.eraseFromParent(); 1529 1530 return LoopBB; 1531 } 1532 1533 static unsigned getMOVRELDPseudo(const TargetRegisterClass *VecRC) { 1534 switch (VecRC->getSize()) { 1535 case 4: 1536 return AMDGPU::V_MOVRELD_B32_V1; 1537 case 8: 1538 return AMDGPU::V_MOVRELD_B32_V2; 1539 case 16: 1540 return AMDGPU::V_MOVRELD_B32_V4; 1541 case 32: 1542 return AMDGPU::V_MOVRELD_B32_V8; 1543 case 64: 1544 return AMDGPU::V_MOVRELD_B32_V16; 1545 default: 1546 llvm_unreachable("unsupported size for MOVRELD pseudos"); 1547 } 1548 } 1549 1550 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 1551 MachineBasicBlock &MBB, 1552 const SISubtarget &ST) { 1553 const SIInstrInfo *TII = ST.getInstrInfo(); 1554 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 1555 MachineFunction *MF = MBB.getParent(); 1556 MachineRegisterInfo &MRI = MF->getRegInfo(); 1557 1558 unsigned Dst = MI.getOperand(0).getReg(); 1559 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 1560 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1561 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 1562 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 1563 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 1564 1565 // This can be an immediate, but will be folded later. 1566 assert(Val->getReg()); 1567 1568 unsigned SubReg; 1569 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 1570 SrcVec->getReg(), 1571 Offset); 1572 bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode; 1573 1574 if (Idx->getReg() == AMDGPU::NoRegister) { 1575 MachineBasicBlock::iterator I(&MI); 1576 const DebugLoc &DL = MI.getDebugLoc(); 1577 1578 assert(Offset == 0); 1579 1580 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 1581 .addOperand(*SrcVec) 1582 .addOperand(*Val) 1583 .addImm(SubReg); 1584 1585 MI.eraseFromParent(); 1586 return &MBB; 1587 } 1588 1589 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 1590 MachineBasicBlock::iterator I(&MI); 1591 const DebugLoc &DL = MI.getDebugLoc(); 1592 1593 if (UseGPRIdxMode) { 1594 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 1595 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 1596 .addOperand(*Val) 1597 .addReg(Dst, RegState::ImplicitDefine) 1598 .addReg(SrcVec->getReg(), RegState::Implicit) 1599 .addReg(AMDGPU::M0, RegState::Implicit); 1600 1601 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1602 } else { 1603 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC)); 1604 1605 BuildMI(MBB, I, DL, MovRelDesc) 1606 .addReg(Dst, RegState::Define) 1607 .addReg(SrcVec->getReg()) 1608 .addOperand(*Val) 1609 .addImm(SubReg - AMDGPU::sub0); 1610 } 1611 1612 MI.eraseFromParent(); 1613 return &MBB; 1614 } 1615 1616 if (Val->isReg()) 1617 MRI.clearKillFlags(Val->getReg()); 1618 1619 const DebugLoc &DL = MI.getDebugLoc(); 1620 1621 if (UseGPRIdxMode) { 1622 MachineBasicBlock::iterator I(&MI); 1623 1624 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1625 .addImm(0) // Reset inside loop. 1626 .addImm(VGPRIndexMode::DST_ENABLE); 1627 SetOn->getOperand(3).setIsUndef(); 1628 1629 // Disable again after the loop. 1630 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1631 } 1632 1633 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 1634 1635 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 1636 Offset, UseGPRIdxMode); 1637 MachineBasicBlock *LoopBB = InsPt->getParent(); 1638 1639 if (UseGPRIdxMode) { 1640 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 1641 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 1642 .addOperand(*Val) // src0 1643 .addReg(Dst, RegState::ImplicitDefine) 1644 .addReg(PhiReg, RegState::Implicit) 1645 .addReg(AMDGPU::M0, RegState::Implicit); 1646 } else { 1647 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC)); 1648 1649 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 1650 .addReg(Dst, RegState::Define) 1651 .addReg(PhiReg) 1652 .addOperand(*Val) 1653 .addImm(SubReg - AMDGPU::sub0); 1654 } 1655 1656 MI.eraseFromParent(); 1657 1658 return LoopBB; 1659 } 1660 1661 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 1662 MachineInstr &MI, MachineBasicBlock *BB) const { 1663 switch (MI.getOpcode()) { 1664 case AMDGPU::SI_INIT_M0: { 1665 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1666 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 1667 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1668 .addOperand(MI.getOperand(0)); 1669 MI.eraseFromParent(); 1670 return BB; 1671 } 1672 case AMDGPU::GET_GROUPSTATICSIZE: { 1673 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1674 1675 MachineFunction *MF = BB->getParent(); 1676 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 1677 DebugLoc DL = MI.getDebugLoc(); 1678 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 1679 .addOperand(MI.getOperand(0)) 1680 .addImm(MFI->getLDSSize()); 1681 MI.eraseFromParent(); 1682 return BB; 1683 } 1684 case AMDGPU::SI_INDIRECT_SRC_V1: 1685 case AMDGPU::SI_INDIRECT_SRC_V2: 1686 case AMDGPU::SI_INDIRECT_SRC_V4: 1687 case AMDGPU::SI_INDIRECT_SRC_V8: 1688 case AMDGPU::SI_INDIRECT_SRC_V16: 1689 return emitIndirectSrc(MI, *BB, *getSubtarget()); 1690 case AMDGPU::SI_INDIRECT_DST_V1: 1691 case AMDGPU::SI_INDIRECT_DST_V2: 1692 case AMDGPU::SI_INDIRECT_DST_V4: 1693 case AMDGPU::SI_INDIRECT_DST_V8: 1694 case AMDGPU::SI_INDIRECT_DST_V16: 1695 return emitIndirectDst(MI, *BB, *getSubtarget()); 1696 case AMDGPU::SI_KILL: 1697 return splitKillBlock(MI, BB); 1698 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 1699 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 1700 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1701 1702 unsigned Dst = MI.getOperand(0).getReg(); 1703 unsigned Src0 = MI.getOperand(1).getReg(); 1704 unsigned Src1 = MI.getOperand(2).getReg(); 1705 const DebugLoc &DL = MI.getDebugLoc(); 1706 unsigned SrcCond = MI.getOperand(3).getReg(); 1707 1708 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1709 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1710 1711 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 1712 .addReg(Src0, 0, AMDGPU::sub0) 1713 .addReg(Src1, 0, AMDGPU::sub0) 1714 .addReg(SrcCond); 1715 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 1716 .addReg(Src0, 0, AMDGPU::sub1) 1717 .addReg(Src1, 0, AMDGPU::sub1) 1718 .addReg(SrcCond); 1719 1720 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 1721 .addReg(DstLo) 1722 .addImm(AMDGPU::sub0) 1723 .addReg(DstHi) 1724 .addImm(AMDGPU::sub1); 1725 MI.eraseFromParent(); 1726 return BB; 1727 } 1728 default: 1729 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 1730 } 1731 } 1732 1733 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1734 // This currently forces unfolding various combinations of fsub into fma with 1735 // free fneg'd operands. As long as we have fast FMA (controlled by 1736 // isFMAFasterThanFMulAndFAdd), we should perform these. 1737 1738 // When fma is quarter rate, for f64 where add / sub are at best half rate, 1739 // most of these combines appear to be cycle neutral but save on instruction 1740 // count / code size. 1741 return true; 1742 } 1743 1744 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 1745 EVT VT) const { 1746 if (!VT.isVector()) { 1747 return MVT::i1; 1748 } 1749 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 1750 } 1751 1752 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const { 1753 return MVT::i32; 1754 } 1755 1756 // Answering this is somewhat tricky and depends on the specific device which 1757 // have different rates for fma or all f64 operations. 1758 // 1759 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 1760 // regardless of which device (although the number of cycles differs between 1761 // devices), so it is always profitable for f64. 1762 // 1763 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 1764 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 1765 // which we can always do even without fused FP ops since it returns the same 1766 // result as the separate operations and since it is always full 1767 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 1768 // however does not support denormals, so we do report fma as faster if we have 1769 // a fast fma device and require denormals. 1770 // 1771 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 1772 VT = VT.getScalarType(); 1773 1774 if (!VT.isSimple()) 1775 return false; 1776 1777 switch (VT.getSimpleVT().SimpleTy) { 1778 case MVT::f32: 1779 // This is as fast on some subtargets. However, we always have full rate f32 1780 // mad available which returns the same result as the separate operations 1781 // which we should prefer over fma. We can't use this if we want to support 1782 // denormals, so only report this in these cases. 1783 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 1784 case MVT::f64: 1785 return true; 1786 default: 1787 break; 1788 } 1789 1790 return false; 1791 } 1792 1793 //===----------------------------------------------------------------------===// 1794 // Custom DAG Lowering Operations 1795 //===----------------------------------------------------------------------===// 1796 1797 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 1798 switch (Op.getOpcode()) { 1799 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 1800 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 1801 case ISD::LOAD: { 1802 SDValue Result = LowerLOAD(Op, DAG); 1803 assert((!Result.getNode() || 1804 Result.getNode()->getNumValues() == 2) && 1805 "Load should return a value and a chain"); 1806 return Result; 1807 } 1808 1809 case ISD::FSIN: 1810 case ISD::FCOS: 1811 return LowerTrig(Op, DAG); 1812 case ISD::SELECT: return LowerSELECT(Op, DAG); 1813 case ISD::FDIV: return LowerFDIV(Op, DAG); 1814 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 1815 case ISD::STORE: return LowerSTORE(Op, DAG); 1816 case ISD::GlobalAddress: { 1817 MachineFunction &MF = DAG.getMachineFunction(); 1818 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1819 return LowerGlobalAddress(MFI, Op, DAG); 1820 } 1821 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 1822 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 1823 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 1824 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 1825 case ISD::TRAP: return lowerTRAP(Op, DAG); 1826 1827 case ISD::ConstantFP: 1828 return lowerConstantFP(Op, DAG); 1829 case ISD::FP_TO_SINT: 1830 case ISD::FP_TO_UINT: 1831 return lowerFpToInt(Op, DAG); 1832 case ISD::SINT_TO_FP: 1833 case ISD::UINT_TO_FP: 1834 return lowerIntToFp(Op, DAG); 1835 } 1836 return SDValue(); 1837 } 1838 1839 /// \brief Helper function for LowerBRCOND 1840 static SDNode *findUser(SDValue Value, unsigned Opcode) { 1841 1842 SDNode *Parent = Value.getNode(); 1843 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 1844 I != E; ++I) { 1845 1846 if (I.getUse().get() != Value) 1847 continue; 1848 1849 if (I->getOpcode() == Opcode) 1850 return *I; 1851 } 1852 return nullptr; 1853 } 1854 1855 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 1856 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 1857 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 1858 case AMDGPUIntrinsic::amdgcn_if: 1859 case AMDGPUIntrinsic::amdgcn_else: 1860 case AMDGPUIntrinsic::amdgcn_end_cf: 1861 case AMDGPUIntrinsic::amdgcn_loop: 1862 return true; 1863 default: 1864 return false; 1865 } 1866 } 1867 1868 if (Intr->getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 1869 switch (cast<ConstantSDNode>(Intr->getOperand(0))->getZExtValue()) { 1870 case AMDGPUIntrinsic::amdgcn_break: 1871 case AMDGPUIntrinsic::amdgcn_if_break: 1872 case AMDGPUIntrinsic::amdgcn_else_break: 1873 return true; 1874 default: 1875 return false; 1876 } 1877 } 1878 1879 return false; 1880 } 1881 1882 void SITargetLowering::createDebuggerPrologueStackObjects( 1883 MachineFunction &MF) const { 1884 // Create stack objects that are used for emitting debugger prologue. 1885 // 1886 // Debugger prologue writes work group IDs and work item IDs to scratch memory 1887 // at fixed location in the following format: 1888 // offset 0: work group ID x 1889 // offset 4: work group ID y 1890 // offset 8: work group ID z 1891 // offset 16: work item ID x 1892 // offset 20: work item ID y 1893 // offset 24: work item ID z 1894 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1895 int ObjectIdx = 0; 1896 1897 // For each dimension: 1898 for (unsigned i = 0; i < 3; ++i) { 1899 // Create fixed stack object for work group ID. 1900 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 1901 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 1902 // Create fixed stack object for work item ID. 1903 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 1904 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 1905 } 1906 } 1907 1908 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 1909 const Triple &TT = getTargetMachine().getTargetTriple(); 1910 return GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS && 1911 AMDGPU::shouldEmitConstantsToTextSection(TT); 1912 } 1913 1914 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 1915 return (GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 1916 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) && 1917 !shouldEmitFixup(GV) && 1918 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 1919 } 1920 1921 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 1922 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 1923 } 1924 1925 /// This transforms the control flow intrinsics to get the branch destination as 1926 /// last parameter, also switches branch target with BR if the need arise 1927 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 1928 SelectionDAG &DAG) const { 1929 1930 SDLoc DL(BRCOND); 1931 1932 SDNode *Intr = BRCOND.getOperand(1).getNode(); 1933 SDValue Target = BRCOND.getOperand(2); 1934 SDNode *BR = nullptr; 1935 SDNode *SetCC = nullptr; 1936 1937 if (Intr->getOpcode() == ISD::SETCC) { 1938 // As long as we negate the condition everything is fine 1939 SetCC = Intr; 1940 Intr = SetCC->getOperand(0).getNode(); 1941 1942 } else { 1943 // Get the target from BR if we don't negate the condition 1944 BR = findUser(BRCOND, ISD::BR); 1945 Target = BR->getOperand(1); 1946 } 1947 1948 // FIXME: This changes the types of the intrinsics instead of introducing new 1949 // nodes with the correct types. 1950 // e.g. llvm.amdgcn.loop 1951 1952 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 1953 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 1954 1955 if (!isCFIntrinsic(Intr)) { 1956 // This is a uniform branch so we don't need to legalize. 1957 return BRCOND; 1958 } 1959 1960 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 1961 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 1962 1963 assert(!SetCC || 1964 (SetCC->getConstantOperandVal(1) == 1 && 1965 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 1966 ISD::SETNE)); 1967 1968 // operands of the new intrinsic call 1969 SmallVector<SDValue, 4> Ops; 1970 if (HaveChain) 1971 Ops.push_back(BRCOND.getOperand(0)); 1972 1973 Ops.append(Intr->op_begin() + (HaveChain ? 1 : 0), Intr->op_end()); 1974 Ops.push_back(Target); 1975 1976 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 1977 1978 // build the new intrinsic call 1979 SDNode *Result = DAG.getNode( 1980 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL, 1981 DAG.getVTList(Res), Ops).getNode(); 1982 1983 if (!HaveChain) { 1984 SDValue Ops[] = { 1985 SDValue(Result, 0), 1986 BRCOND.getOperand(0) 1987 }; 1988 1989 Result = DAG.getMergeValues(Ops, DL).getNode(); 1990 } 1991 1992 if (BR) { 1993 // Give the branch instruction our target 1994 SDValue Ops[] = { 1995 BR->getOperand(0), 1996 BRCOND.getOperand(2) 1997 }; 1998 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 1999 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 2000 BR = NewBR.getNode(); 2001 } 2002 2003 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 2004 2005 // Copy the intrinsic results to registers 2006 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 2007 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 2008 if (!CopyToReg) 2009 continue; 2010 2011 Chain = DAG.getCopyToReg( 2012 Chain, DL, 2013 CopyToReg->getOperand(1), 2014 SDValue(Result, i - 1), 2015 SDValue()); 2016 2017 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 2018 } 2019 2020 // Remove the old intrinsic from the chain 2021 DAG.ReplaceAllUsesOfValueWith( 2022 SDValue(Intr, Intr->getNumValues() - 1), 2023 Intr->getOperand(0)); 2024 2025 return Chain; 2026 } 2027 2028 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 2029 SDValue Op, 2030 const SDLoc &DL, 2031 EVT VT) const { 2032 return Op.getValueType().bitsLE(VT) ? 2033 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 2034 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 2035 } 2036 2037 SDValue SITargetLowering::lowerConstantFP(SDValue Op, SelectionDAG &DAG) const { 2038 if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(Op)) { 2039 return DAG.getConstant(FP->getValueAPF().bitcastToAPInt().getZExtValue(), 2040 SDLoc(Op), MVT::i32); 2041 } 2042 2043 return SDValue(); 2044 } 2045 2046 SDValue SITargetLowering::lowerFpToInt(SDValue Op, SelectionDAG &DAG) const { 2047 EVT DstVT = Op.getValueType(); 2048 EVT SrcVT = Op.getOperand(0).getValueType(); 2049 if (DstVT == MVT::i64) { 2050 return Op.getOpcode() == ISD::FP_TO_SINT ? 2051 AMDGPUTargetLowering::LowerFP_TO_SINT(Op, DAG) : 2052 AMDGPUTargetLowering::LowerFP_TO_UINT(Op, DAG); 2053 } 2054 2055 if (SrcVT == MVT::f16) 2056 return Op; 2057 2058 SDLoc DL(Op); 2059 SDValue OrigSrc = Op.getOperand(0); 2060 SDValue FPRoundFlag = DAG.getIntPtrConstant(0, DL); 2061 SDValue FPRoundSrc = 2062 DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, OrigSrc, FPRoundFlag); 2063 2064 return DAG.getNode(Op.getOpcode(), DL, DstVT, FPRoundSrc); 2065 } 2066 2067 SDValue SITargetLowering::lowerIntToFp(SDValue Op, SelectionDAG &DAG) const { 2068 EVT DstVT = Op.getValueType(); 2069 EVT SrcVT = Op.getOperand(0).getValueType(); 2070 if (SrcVT == MVT::i64) { 2071 return Op.getOpcode() == ISD::SINT_TO_FP ? 2072 AMDGPUTargetLowering::LowerSINT_TO_FP(Op, DAG) : 2073 AMDGPUTargetLowering::LowerUINT_TO_FP(Op, DAG); 2074 } 2075 2076 if (DstVT == MVT::f16) 2077 return Op; 2078 2079 SDLoc DL(Op); 2080 SDValue OrigSrc = Op.getOperand(0); 2081 SDValue SExtOrZExtOrTruncSrc = Op.getOpcode() == ISD::SINT_TO_FP ? 2082 DAG.getSExtOrTrunc(OrigSrc, DL, MVT::i32) : 2083 DAG.getZExtOrTrunc(OrigSrc, DL, MVT::i32); 2084 2085 return DAG.getNode(Op.getOpcode(), DL, DstVT, SExtOrZExtOrTruncSrc); 2086 } 2087 2088 SDValue SITargetLowering::getSegmentAperture(unsigned AS, 2089 SelectionDAG &DAG) const { 2090 SDLoc SL; 2091 MachineFunction &MF = DAG.getMachineFunction(); 2092 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2093 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 2094 assert(UserSGPR != AMDGPU::NoRegister); 2095 2096 SDValue QueuePtr = CreateLiveInRegister( 2097 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 2098 2099 // Offset into amd_queue_t for group_segment_aperture_base_hi / 2100 // private_segment_aperture_base_hi. 2101 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 2102 2103 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr, 2104 DAG.getConstant(StructOffset, SL, MVT::i64)); 2105 2106 // TODO: Use custom target PseudoSourceValue. 2107 // TODO: We should use the value from the IR intrinsic call, but it might not 2108 // be available and how do we get it? 2109 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 2110 AMDGPUAS::CONSTANT_ADDRESS)); 2111 2112 MachinePointerInfo PtrInfo(V, StructOffset); 2113 return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, PtrInfo, 2114 MinAlign(64, StructOffset), 2115 MachineMemOperand::MODereferenceable | 2116 MachineMemOperand::MOInvariant); 2117 } 2118 2119 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 2120 SelectionDAG &DAG) const { 2121 SDLoc SL(Op); 2122 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 2123 2124 SDValue Src = ASC->getOperand(0); 2125 2126 // FIXME: Really support non-0 null pointers. 2127 SDValue SegmentNullPtr = DAG.getConstant(-1, SL, MVT::i32); 2128 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 2129 2130 // flat -> local/private 2131 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 2132 if (ASC->getDestAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2133 ASC->getDestAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 2134 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 2135 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 2136 2137 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 2138 NonNull, Ptr, SegmentNullPtr); 2139 } 2140 } 2141 2142 // local/private -> flat 2143 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 2144 if (ASC->getSrcAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2145 ASC->getSrcAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 2146 SDValue NonNull 2147 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 2148 2149 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG); 2150 SDValue CvtPtr 2151 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 2152 2153 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 2154 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 2155 FlatNullPtr); 2156 } 2157 } 2158 2159 // global <-> flat are no-ops and never emitted. 2160 2161 const MachineFunction &MF = DAG.getMachineFunction(); 2162 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 2163 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 2164 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 2165 2166 return DAG.getUNDEF(ASC->getValueType(0)); 2167 } 2168 2169 bool 2170 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 2171 // We can fold offsets for anything that doesn't require a GOT relocation. 2172 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 2173 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) && 2174 !shouldEmitGOTReloc(GA->getGlobal()); 2175 } 2176 2177 static SDValue buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 2178 SDLoc DL, unsigned Offset, EVT PtrVT, 2179 unsigned GAFlags = SIInstrInfo::MO_NONE) { 2180 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 2181 // lowered to the following code sequence: 2182 // 2183 // For constant address space: 2184 // s_getpc_b64 s[0:1] 2185 // s_add_u32 s0, s0, $symbol 2186 // s_addc_u32 s1, s1, 0 2187 // 2188 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 2189 // a fixup or relocation is emitted to replace $symbol with a literal 2190 // constant, which is a pc-relative offset from the encoding of the $symbol 2191 // operand to the global variable. 2192 // 2193 // For global address space: 2194 // s_getpc_b64 s[0:1] 2195 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 2196 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 2197 // 2198 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 2199 // fixups or relocations are emitted to replace $symbol@*@lo and 2200 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 2201 // which is a 64-bit pc-relative offset from the encoding of the $symbol 2202 // operand to the global variable. 2203 // 2204 // What we want here is an offset from the value returned by s_getpc 2205 // (which is the address of the s_add_u32 instruction) to the global 2206 // variable, but since the encoding of $symbol starts 4 bytes after the start 2207 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 2208 // small. This requires us to add 4 to the global variable offset in order to 2209 // compute the correct address. 2210 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 2211 GAFlags); 2212 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 2213 GAFlags == SIInstrInfo::MO_NONE ? 2214 GAFlags : GAFlags + 1); 2215 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 2216 } 2217 2218 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 2219 SDValue Op, 2220 SelectionDAG &DAG) const { 2221 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 2222 2223 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS && 2224 GSD->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS) 2225 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 2226 2227 SDLoc DL(GSD); 2228 const GlobalValue *GV = GSD->getGlobal(); 2229 EVT PtrVT = Op.getValueType(); 2230 2231 if (shouldEmitFixup(GV)) 2232 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 2233 else if (shouldEmitPCReloc(GV)) 2234 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 2235 SIInstrInfo::MO_REL32); 2236 2237 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 2238 SIInstrInfo::MO_GOTPCREL32); 2239 2240 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 2241 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 2242 const DataLayout &DataLayout = DAG.getDataLayout(); 2243 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 2244 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 2245 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 2246 2247 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 2248 MachineMemOperand::MODereferenceable | 2249 MachineMemOperand::MOInvariant); 2250 } 2251 2252 SDValue SITargetLowering::lowerTRAP(SDValue Op, 2253 SelectionDAG &DAG) const { 2254 const MachineFunction &MF = DAG.getMachineFunction(); 2255 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(), 2256 "trap handler not supported", 2257 Op.getDebugLoc(), 2258 DS_Warning); 2259 DAG.getContext()->diagnose(NoTrap); 2260 2261 // Emit s_endpgm. 2262 2263 // FIXME: This should really be selected to s_trap, but that requires 2264 // setting up the trap handler for it o do anything. 2265 return DAG.getNode(AMDGPUISD::ENDPGM, SDLoc(Op), MVT::Other, 2266 Op.getOperand(0)); 2267 } 2268 2269 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 2270 const SDLoc &DL, SDValue V) const { 2271 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 2272 // the destination register. 2273 // 2274 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 2275 // so we will end up with redundant moves to m0. 2276 // 2277 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 2278 2279 // A Null SDValue creates a glue result. 2280 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 2281 V, Chain); 2282 return SDValue(M0, 0); 2283 } 2284 2285 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 2286 SDValue Op, 2287 MVT VT, 2288 unsigned Offset) const { 2289 SDLoc SL(Op); 2290 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL, 2291 DAG.getEntryNode(), Offset, false); 2292 // The local size values will have the hi 16-bits as zero. 2293 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 2294 DAG.getValueType(VT)); 2295 } 2296 2297 static SDValue emitNonHSAIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) { 2298 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 2299 "non-hsa intrinsic with hsa target", 2300 DL.getDebugLoc()); 2301 DAG.getContext()->diagnose(BadIntrin); 2302 return DAG.getUNDEF(VT); 2303 } 2304 2305 static SDValue emitRemovedIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) { 2306 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 2307 "intrinsic not supported on subtarget", 2308 DL.getDebugLoc()); 2309 DAG.getContext()->diagnose(BadIntrin); 2310 return DAG.getUNDEF(VT); 2311 } 2312 2313 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2314 SelectionDAG &DAG) const { 2315 MachineFunction &MF = DAG.getMachineFunction(); 2316 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 2317 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2318 2319 EVT VT = Op.getValueType(); 2320 SDLoc DL(Op); 2321 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2322 2323 // TODO: Should this propagate fast-math-flags? 2324 2325 switch (IntrinsicID) { 2326 case Intrinsic::amdgcn_dispatch_ptr: 2327 case Intrinsic::amdgcn_queue_ptr: { 2328 if (!Subtarget->isAmdCodeObjectV2()) { 2329 DiagnosticInfoUnsupported BadIntrin( 2330 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 2331 DL.getDebugLoc()); 2332 DAG.getContext()->diagnose(BadIntrin); 2333 return DAG.getUNDEF(VT); 2334 } 2335 2336 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 2337 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR; 2338 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, 2339 TRI->getPreloadedValue(MF, Reg), VT); 2340 } 2341 case Intrinsic::amdgcn_implicitarg_ptr: { 2342 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT); 2343 return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset); 2344 } 2345 case Intrinsic::amdgcn_kernarg_segment_ptr: { 2346 unsigned Reg 2347 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 2348 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 2349 } 2350 case Intrinsic::amdgcn_dispatch_id: { 2351 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID); 2352 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 2353 } 2354 case Intrinsic::amdgcn_rcp: 2355 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 2356 case Intrinsic::amdgcn_rsq: 2357 case AMDGPUIntrinsic::AMDGPU_rsq: // Legacy name 2358 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 2359 case Intrinsic::amdgcn_rsq_legacy: { 2360 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 2361 return emitRemovedIntrinsicError(DAG, DL, VT); 2362 2363 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 2364 } 2365 case Intrinsic::amdgcn_rcp_legacy: { 2366 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 2367 return emitRemovedIntrinsicError(DAG, DL, VT); 2368 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 2369 } 2370 case Intrinsic::amdgcn_rsq_clamp: { 2371 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 2372 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 2373 2374 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 2375 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 2376 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 2377 2378 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 2379 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 2380 DAG.getConstantFP(Max, DL, VT)); 2381 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 2382 DAG.getConstantFP(Min, DL, VT)); 2383 } 2384 case Intrinsic::r600_read_ngroups_x: 2385 if (Subtarget->isAmdHsaOS()) 2386 return emitNonHSAIntrinsicError(DAG, DL, VT); 2387 2388 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2389 SI::KernelInputOffsets::NGROUPS_X, false); 2390 case Intrinsic::r600_read_ngroups_y: 2391 if (Subtarget->isAmdHsaOS()) 2392 return emitNonHSAIntrinsicError(DAG, DL, VT); 2393 2394 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2395 SI::KernelInputOffsets::NGROUPS_Y, false); 2396 case Intrinsic::r600_read_ngroups_z: 2397 if (Subtarget->isAmdHsaOS()) 2398 return emitNonHSAIntrinsicError(DAG, DL, VT); 2399 2400 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2401 SI::KernelInputOffsets::NGROUPS_Z, false); 2402 case Intrinsic::r600_read_global_size_x: 2403 if (Subtarget->isAmdHsaOS()) 2404 return emitNonHSAIntrinsicError(DAG, DL, VT); 2405 2406 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2407 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 2408 case Intrinsic::r600_read_global_size_y: 2409 if (Subtarget->isAmdHsaOS()) 2410 return emitNonHSAIntrinsicError(DAG, DL, VT); 2411 2412 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2413 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 2414 case Intrinsic::r600_read_global_size_z: 2415 if (Subtarget->isAmdHsaOS()) 2416 return emitNonHSAIntrinsicError(DAG, DL, VT); 2417 2418 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2419 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 2420 case Intrinsic::r600_read_local_size_x: 2421 if (Subtarget->isAmdHsaOS()) 2422 return emitNonHSAIntrinsicError(DAG, DL, VT); 2423 2424 return lowerImplicitZextParam(DAG, Op, MVT::i16, 2425 SI::KernelInputOffsets::LOCAL_SIZE_X); 2426 case Intrinsic::r600_read_local_size_y: 2427 if (Subtarget->isAmdHsaOS()) 2428 return emitNonHSAIntrinsicError(DAG, DL, VT); 2429 2430 return lowerImplicitZextParam(DAG, Op, MVT::i16, 2431 SI::KernelInputOffsets::LOCAL_SIZE_Y); 2432 case Intrinsic::r600_read_local_size_z: 2433 if (Subtarget->isAmdHsaOS()) 2434 return emitNonHSAIntrinsicError(DAG, DL, VT); 2435 2436 return lowerImplicitZextParam(DAG, Op, MVT::i16, 2437 SI::KernelInputOffsets::LOCAL_SIZE_Z); 2438 case Intrinsic::amdgcn_workgroup_id_x: 2439 case Intrinsic::r600_read_tgid_x: 2440 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 2441 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT); 2442 case Intrinsic::amdgcn_workgroup_id_y: 2443 case Intrinsic::r600_read_tgid_y: 2444 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 2445 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT); 2446 case Intrinsic::amdgcn_workgroup_id_z: 2447 case Intrinsic::r600_read_tgid_z: 2448 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, 2449 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT); 2450 case Intrinsic::amdgcn_workitem_id_x: 2451 case Intrinsic::r600_read_tidig_x: 2452 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 2453 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT); 2454 case Intrinsic::amdgcn_workitem_id_y: 2455 case Intrinsic::r600_read_tidig_y: 2456 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 2457 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT); 2458 case Intrinsic::amdgcn_workitem_id_z: 2459 case Intrinsic::r600_read_tidig_z: 2460 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 2461 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT); 2462 case AMDGPUIntrinsic::SI_load_const: { 2463 SDValue Ops[] = { 2464 Op.getOperand(1), 2465 Op.getOperand(2) 2466 }; 2467 2468 MachineMemOperand *MMO = MF.getMachineMemOperand( 2469 MachinePointerInfo(), 2470 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 2471 MachineMemOperand::MOInvariant, 2472 VT.getStoreSize(), 4); 2473 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 2474 Op->getVTList(), Ops, VT, MMO); 2475 } 2476 case AMDGPUIntrinsic::amdgcn_fdiv_fast: { 2477 return lowerFDIV_FAST(Op, DAG); 2478 } 2479 case AMDGPUIntrinsic::SI_vs_load_input: 2480 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT, 2481 Op.getOperand(1), 2482 Op.getOperand(2), 2483 Op.getOperand(3)); 2484 2485 case AMDGPUIntrinsic::SI_fs_constant: { 2486 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3)); 2487 SDValue Glue = M0.getValue(1); 2488 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 2489 DAG.getConstant(2, DL, MVT::i32), // P0 2490 Op.getOperand(1), Op.getOperand(2), Glue); 2491 } 2492 case AMDGPUIntrinsic::SI_packf16: 2493 if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef()) 2494 return DAG.getUNDEF(MVT::i32); 2495 return Op; 2496 case AMDGPUIntrinsic::SI_fs_interp: { 2497 SDValue IJ = Op.getOperand(4); 2498 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ, 2499 DAG.getConstant(0, DL, MVT::i32)); 2500 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ, 2501 DAG.getConstant(1, DL, MVT::i32)); 2502 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3)); 2503 SDValue Glue = M0.getValue(1); 2504 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL, 2505 DAG.getVTList(MVT::f32, MVT::Glue), 2506 I, Op.getOperand(1), Op.getOperand(2), Glue); 2507 Glue = SDValue(P1.getNode(), 1); 2508 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J, 2509 Op.getOperand(1), Op.getOperand(2), Glue); 2510 } 2511 case Intrinsic::amdgcn_interp_p1: { 2512 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 2513 SDValue Glue = M0.getValue(1); 2514 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 2515 Op.getOperand(2), Op.getOperand(3), Glue); 2516 } 2517 case Intrinsic::amdgcn_interp_p2: { 2518 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 2519 SDValue Glue = SDValue(M0.getNode(), 1); 2520 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 2521 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 2522 Glue); 2523 } 2524 case Intrinsic::amdgcn_sin: 2525 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 2526 2527 case Intrinsic::amdgcn_cos: 2528 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 2529 2530 case Intrinsic::amdgcn_log_clamp: { 2531 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 2532 return SDValue(); 2533 2534 DiagnosticInfoUnsupported BadIntrin( 2535 *MF.getFunction(), "intrinsic not supported on subtarget", 2536 DL.getDebugLoc()); 2537 DAG.getContext()->diagnose(BadIntrin); 2538 return DAG.getUNDEF(VT); 2539 } 2540 case Intrinsic::amdgcn_ldexp: 2541 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 2542 Op.getOperand(1), Op.getOperand(2)); 2543 2544 case Intrinsic::amdgcn_fract: 2545 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 2546 2547 case Intrinsic::amdgcn_class: 2548 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 2549 Op.getOperand(1), Op.getOperand(2)); 2550 case Intrinsic::amdgcn_div_fmas: 2551 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 2552 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 2553 Op.getOperand(4)); 2554 2555 case Intrinsic::amdgcn_div_fixup: 2556 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 2557 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 2558 2559 case Intrinsic::amdgcn_trig_preop: 2560 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 2561 Op.getOperand(1), Op.getOperand(2)); 2562 case Intrinsic::amdgcn_div_scale: { 2563 // 3rd parameter required to be a constant. 2564 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 2565 if (!Param) 2566 return DAG.getUNDEF(VT); 2567 2568 // Translate to the operands expected by the machine instruction. The 2569 // first parameter must be the same as the first instruction. 2570 SDValue Numerator = Op.getOperand(1); 2571 SDValue Denominator = Op.getOperand(2); 2572 2573 // Note this order is opposite of the machine instruction's operations, 2574 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 2575 // intrinsic has the numerator as the first operand to match a normal 2576 // division operation. 2577 2578 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 2579 2580 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 2581 Denominator, Numerator); 2582 } 2583 case Intrinsic::amdgcn_icmp: { 2584 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 2585 int CondCode = CD->getSExtValue(); 2586 2587 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 2588 CondCode >= ICmpInst::Predicate::BAD_ICMP_PREDICATE) 2589 return DAG.getUNDEF(VT); 2590 2591 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 2592 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 2593 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 2594 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 2595 } 2596 case Intrinsic::amdgcn_fcmp: { 2597 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 2598 int CondCode = CD->getSExtValue(); 2599 2600 if (CondCode <= FCmpInst::Predicate::FCMP_FALSE || 2601 CondCode >= FCmpInst::Predicate::FCMP_TRUE) 2602 return DAG.getUNDEF(VT); 2603 2604 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 2605 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 2606 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 2607 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 2608 } 2609 case Intrinsic::amdgcn_fmul_legacy: 2610 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 2611 Op.getOperand(1), Op.getOperand(2)); 2612 case Intrinsic::amdgcn_sffbh: 2613 case AMDGPUIntrinsic::AMDGPU_flbit_i32: // Legacy name. 2614 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 2615 default: 2616 return AMDGPUTargetLowering::LowerOperation(Op, DAG); 2617 } 2618 } 2619 2620 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 2621 SelectionDAG &DAG) const { 2622 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2623 switch (IntrID) { 2624 case Intrinsic::amdgcn_atomic_inc: 2625 case Intrinsic::amdgcn_atomic_dec: { 2626 MemSDNode *M = cast<MemSDNode>(Op); 2627 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ? 2628 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC; 2629 SDValue Ops[] = { 2630 M->getOperand(0), // Chain 2631 M->getOperand(2), // Ptr 2632 M->getOperand(3) // Value 2633 }; 2634 2635 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 2636 M->getMemoryVT(), M->getMemOperand()); 2637 } 2638 default: 2639 return SDValue(); 2640 } 2641 } 2642 2643 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 2644 SelectionDAG &DAG) const { 2645 MachineFunction &MF = DAG.getMachineFunction(); 2646 SDLoc DL(Op); 2647 SDValue Chain = Op.getOperand(0); 2648 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2649 2650 switch (IntrinsicID) { 2651 case AMDGPUIntrinsic::SI_sendmsg: { 2652 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 2653 SDValue Glue = Chain.getValue(1); 2654 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain, 2655 Op.getOperand(2), Glue); 2656 } 2657 case AMDGPUIntrinsic::SI_tbuffer_store: { 2658 SDValue Ops[] = { 2659 Chain, 2660 Op.getOperand(2), 2661 Op.getOperand(3), 2662 Op.getOperand(4), 2663 Op.getOperand(5), 2664 Op.getOperand(6), 2665 Op.getOperand(7), 2666 Op.getOperand(8), 2667 Op.getOperand(9), 2668 Op.getOperand(10), 2669 Op.getOperand(11), 2670 Op.getOperand(12), 2671 Op.getOperand(13), 2672 Op.getOperand(14) 2673 }; 2674 2675 EVT VT = Op.getOperand(3).getValueType(); 2676 2677 MachineMemOperand *MMO = MF.getMachineMemOperand( 2678 MachinePointerInfo(), 2679 MachineMemOperand::MOStore, 2680 VT.getStoreSize(), 4); 2681 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 2682 Op->getVTList(), Ops, VT, MMO); 2683 } 2684 case AMDGPUIntrinsic::AMDGPU_kill: { 2685 SDValue Src = Op.getOperand(2); 2686 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 2687 if (!K->isNegative()) 2688 return Chain; 2689 2690 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 2691 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 2692 } 2693 2694 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 2695 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 2696 } 2697 default: 2698 return SDValue(); 2699 } 2700 } 2701 2702 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 2703 SDLoc DL(Op); 2704 LoadSDNode *Load = cast<LoadSDNode>(Op); 2705 ISD::LoadExtType ExtType = Load->getExtensionType(); 2706 EVT MemVT = Load->getMemoryVT(); 2707 2708 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 2709 // FIXME: Copied from PPC 2710 // First, load into 32 bits, then truncate to 1 bit. 2711 2712 SDValue Chain = Load->getChain(); 2713 SDValue BasePtr = Load->getBasePtr(); 2714 MachineMemOperand *MMO = Load->getMemOperand(); 2715 2716 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 2717 2718 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 2719 BasePtr, RealMemVT, MMO); 2720 2721 SDValue Ops[] = { 2722 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 2723 NewLD.getValue(1) 2724 }; 2725 2726 return DAG.getMergeValues(Ops, DL); 2727 } 2728 2729 if (!MemVT.isVector()) 2730 return SDValue(); 2731 2732 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 2733 "Custom lowering for non-i32 vectors hasn't been implemented."); 2734 2735 unsigned AS = Load->getAddressSpace(); 2736 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 2737 AS, Load->getAlignment())) { 2738 SDValue Ops[2]; 2739 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 2740 return DAG.getMergeValues(Ops, DL); 2741 } 2742 2743 MachineFunction &MF = DAG.getMachineFunction(); 2744 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 2745 // If there is a possibilty that flat instruction access scratch memory 2746 // then we need to use the same legalization rules we use for private. 2747 if (AS == AMDGPUAS::FLAT_ADDRESS) 2748 AS = MFI->hasFlatScratchInit() ? 2749 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 2750 2751 unsigned NumElements = MemVT.getVectorNumElements(); 2752 switch (AS) { 2753 case AMDGPUAS::CONSTANT_ADDRESS: 2754 if (isMemOpUniform(Load)) 2755 return SDValue(); 2756 // Non-uniform loads will be selected to MUBUF instructions, so they 2757 // have the same legalization requires ments as global and private 2758 // loads. 2759 // 2760 LLVM_FALLTHROUGH; 2761 case AMDGPUAS::GLOBAL_ADDRESS: 2762 case AMDGPUAS::FLAT_ADDRESS: 2763 if (NumElements > 4) 2764 return SplitVectorLoad(Op, DAG); 2765 // v4 loads are supported for private and global memory. 2766 return SDValue(); 2767 case AMDGPUAS::PRIVATE_ADDRESS: { 2768 // Depending on the setting of the private_element_size field in the 2769 // resource descriptor, we can only make private accesses up to a certain 2770 // size. 2771 switch (Subtarget->getMaxPrivateElementSize()) { 2772 case 4: 2773 return scalarizeVectorLoad(Load, DAG); 2774 case 8: 2775 if (NumElements > 2) 2776 return SplitVectorLoad(Op, DAG); 2777 return SDValue(); 2778 case 16: 2779 // Same as global/flat 2780 if (NumElements > 4) 2781 return SplitVectorLoad(Op, DAG); 2782 return SDValue(); 2783 default: 2784 llvm_unreachable("unsupported private_element_size"); 2785 } 2786 } 2787 case AMDGPUAS::LOCAL_ADDRESS: { 2788 if (NumElements > 2) 2789 return SplitVectorLoad(Op, DAG); 2790 2791 if (NumElements == 2) 2792 return SDValue(); 2793 2794 // If properly aligned, if we split we might be able to use ds_read_b64. 2795 return SplitVectorLoad(Op, DAG); 2796 } 2797 default: 2798 return SDValue(); 2799 } 2800 } 2801 2802 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 2803 if (Op.getValueType() != MVT::i64) 2804 return SDValue(); 2805 2806 SDLoc DL(Op); 2807 SDValue Cond = Op.getOperand(0); 2808 2809 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 2810 SDValue One = DAG.getConstant(1, DL, MVT::i32); 2811 2812 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 2813 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 2814 2815 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 2816 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 2817 2818 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 2819 2820 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 2821 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 2822 2823 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 2824 2825 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 2826 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 2827 } 2828 2829 // Catch division cases where we can use shortcuts with rcp and rsq 2830 // instructions. 2831 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 2832 SelectionDAG &DAG) const { 2833 SDLoc SL(Op); 2834 SDValue LHS = Op.getOperand(0); 2835 SDValue RHS = Op.getOperand(1); 2836 EVT VT = Op.getValueType(); 2837 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath; 2838 2839 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 2840 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()))) { 2841 2842 if (CLHS->isExactlyValue(1.0)) { 2843 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 2844 // the CI documentation has a worst case error of 1 ulp. 2845 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 2846 // use it as long as we aren't trying to use denormals. 2847 2848 // 1.0 / sqrt(x) -> rsq(x) 2849 // 2850 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 2851 // error seems really high at 2^29 ULP. 2852 if (RHS.getOpcode() == ISD::FSQRT) 2853 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 2854 2855 // 1.0 / x -> rcp(x) 2856 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 2857 } 2858 2859 // Same as for 1.0, but expand the sign out of the constant. 2860 if (CLHS->isExactlyValue(-1.0)) { 2861 // -1.0 / x -> rcp (fneg x) 2862 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 2863 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 2864 } 2865 } 2866 } 2867 2868 const SDNodeFlags *Flags = Op->getFlags(); 2869 2870 if (Unsafe || Flags->hasAllowReciprocal()) { 2871 // Turn into multiply by the reciprocal. 2872 // x / y -> x * (1.0 / y) 2873 SDNodeFlags Flags; 2874 Flags.setUnsafeAlgebra(true); 2875 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 2876 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags); 2877 } 2878 2879 return SDValue(); 2880 } 2881 2882 // Faster 2.5 ULP division that does not support denormals. 2883 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 2884 SDLoc SL(Op); 2885 SDValue LHS = Op.getOperand(1); 2886 SDValue RHS = Op.getOperand(2); 2887 2888 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 2889 2890 const APFloat K0Val(BitsToFloat(0x6f800000)); 2891 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 2892 2893 const APFloat K1Val(BitsToFloat(0x2f800000)); 2894 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 2895 2896 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 2897 2898 EVT SetCCVT = 2899 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 2900 2901 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 2902 2903 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 2904 2905 // TODO: Should this propagate fast-math-flags? 2906 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 2907 2908 // rcp does not support denormals. 2909 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 2910 2911 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 2912 2913 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 2914 } 2915 2916 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 2917 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 2918 return FastLowered; 2919 2920 SDLoc SL(Op); 2921 SDValue LHS = Op.getOperand(0); 2922 SDValue RHS = Op.getOperand(1); 2923 2924 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 2925 2926 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 2927 2928 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, RHS, RHS, LHS); 2929 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, LHS, RHS, LHS); 2930 2931 // Denominator is scaled to not be denormal, so using rcp is ok. 2932 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, DenominatorScaled); 2933 2934 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, DenominatorScaled); 2935 2936 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, ApproxRcp, One); 2937 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, ApproxRcp); 2938 2939 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, NumeratorScaled, Fma1); 2940 2941 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, NumeratorScaled); 2942 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul); 2943 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, NumeratorScaled); 2944 2945 SDValue Scale = NumeratorScaled.getValue(1); 2946 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, Fma4, Fma1, Fma3, Scale); 2947 2948 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 2949 } 2950 2951 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 2952 if (DAG.getTarget().Options.UnsafeFPMath) 2953 return lowerFastUnsafeFDIV(Op, DAG); 2954 2955 SDLoc SL(Op); 2956 SDValue X = Op.getOperand(0); 2957 SDValue Y = Op.getOperand(1); 2958 2959 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 2960 2961 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 2962 2963 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 2964 2965 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 2966 2967 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 2968 2969 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 2970 2971 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 2972 2973 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 2974 2975 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 2976 2977 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 2978 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 2979 2980 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 2981 NegDivScale0, Mul, DivScale1); 2982 2983 SDValue Scale; 2984 2985 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 2986 // Workaround a hardware bug on SI where the condition output from div_scale 2987 // is not usable. 2988 2989 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 2990 2991 // Figure out if the scale to use for div_fmas. 2992 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 2993 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 2994 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 2995 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 2996 2997 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 2998 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 2999 3000 SDValue Scale0Hi 3001 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 3002 SDValue Scale1Hi 3003 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 3004 3005 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 3006 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 3007 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 3008 } else { 3009 Scale = DivScale1.getValue(1); 3010 } 3011 3012 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 3013 Fma4, Fma3, Mul, Scale); 3014 3015 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 3016 } 3017 3018 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 3019 EVT VT = Op.getValueType(); 3020 3021 if (VT == MVT::f32) 3022 return LowerFDIV32(Op, DAG); 3023 3024 if (VT == MVT::f64) 3025 return LowerFDIV64(Op, DAG); 3026 3027 llvm_unreachable("Unexpected type for fdiv"); 3028 } 3029 3030 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 3031 SDLoc DL(Op); 3032 StoreSDNode *Store = cast<StoreSDNode>(Op); 3033 EVT VT = Store->getMemoryVT(); 3034 3035 if (VT == MVT::i1) { 3036 return DAG.getTruncStore(Store->getChain(), DL, 3037 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 3038 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 3039 } 3040 3041 assert(VT.isVector() && 3042 Store->getValue().getValueType().getScalarType() == MVT::i32); 3043 3044 unsigned AS = Store->getAddressSpace(); 3045 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 3046 AS, Store->getAlignment())) { 3047 return expandUnalignedStore(Store, DAG); 3048 } 3049 3050 MachineFunction &MF = DAG.getMachineFunction(); 3051 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3052 // If there is a possibilty that flat instruction access scratch memory 3053 // then we need to use the same legalization rules we use for private. 3054 if (AS == AMDGPUAS::FLAT_ADDRESS) 3055 AS = MFI->hasFlatScratchInit() ? 3056 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 3057 3058 unsigned NumElements = VT.getVectorNumElements(); 3059 switch (AS) { 3060 case AMDGPUAS::GLOBAL_ADDRESS: 3061 case AMDGPUAS::FLAT_ADDRESS: 3062 if (NumElements > 4) 3063 return SplitVectorStore(Op, DAG); 3064 return SDValue(); 3065 case AMDGPUAS::PRIVATE_ADDRESS: { 3066 switch (Subtarget->getMaxPrivateElementSize()) { 3067 case 4: 3068 return scalarizeVectorStore(Store, DAG); 3069 case 8: 3070 if (NumElements > 2) 3071 return SplitVectorStore(Op, DAG); 3072 return SDValue(); 3073 case 16: 3074 if (NumElements > 4) 3075 return SplitVectorStore(Op, DAG); 3076 return SDValue(); 3077 default: 3078 llvm_unreachable("unsupported private_element_size"); 3079 } 3080 } 3081 case AMDGPUAS::LOCAL_ADDRESS: { 3082 if (NumElements > 2) 3083 return SplitVectorStore(Op, DAG); 3084 3085 if (NumElements == 2) 3086 return Op; 3087 3088 // If properly aligned, if we split we might be able to use ds_write_b64. 3089 return SplitVectorStore(Op, DAG); 3090 } 3091 default: 3092 llvm_unreachable("unhandled address space"); 3093 } 3094 } 3095 3096 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 3097 SDLoc DL(Op); 3098 EVT VT = Op.getValueType(); 3099 SDValue Arg = Op.getOperand(0); 3100 // TODO: Should this propagate fast-math-flags? 3101 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 3102 DAG.getNode(ISD::FMUL, DL, VT, Arg, 3103 DAG.getConstantFP(0.5/M_PI, DL, 3104 VT))); 3105 3106 switch (Op.getOpcode()) { 3107 case ISD::FCOS: 3108 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 3109 case ISD::FSIN: 3110 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 3111 default: 3112 llvm_unreachable("Wrong trig opcode"); 3113 } 3114 } 3115 3116 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 3117 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 3118 assert(AtomicNode->isCompareAndSwap()); 3119 unsigned AS = AtomicNode->getAddressSpace(); 3120 3121 // No custom lowering required for local address space 3122 if (!isFlatGlobalAddrSpace(AS)) 3123 return Op; 3124 3125 // Non-local address space requires custom lowering for atomic compare 3126 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 3127 SDLoc DL(Op); 3128 SDValue ChainIn = Op.getOperand(0); 3129 SDValue Addr = Op.getOperand(1); 3130 SDValue Old = Op.getOperand(2); 3131 SDValue New = Op.getOperand(3); 3132 EVT VT = Op.getValueType(); 3133 MVT SimpleVT = VT.getSimpleVT(); 3134 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 3135 3136 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 3137 SDValue Ops[] = { ChainIn, Addr, NewOld }; 3138 3139 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 3140 Ops, VT, AtomicNode->getMemOperand()); 3141 } 3142 3143 //===----------------------------------------------------------------------===// 3144 // Custom DAG optimizations 3145 //===----------------------------------------------------------------------===// 3146 3147 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 3148 DAGCombinerInfo &DCI) const { 3149 EVT VT = N->getValueType(0); 3150 EVT ScalarVT = VT.getScalarType(); 3151 if (ScalarVT != MVT::f32) 3152 return SDValue(); 3153 3154 SelectionDAG &DAG = DCI.DAG; 3155 SDLoc DL(N); 3156 3157 SDValue Src = N->getOperand(0); 3158 EVT SrcVT = Src.getValueType(); 3159 3160 // TODO: We could try to match extracting the higher bytes, which would be 3161 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 3162 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 3163 // about in practice. 3164 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 3165 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 3166 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 3167 DCI.AddToWorklist(Cvt.getNode()); 3168 return Cvt; 3169 } 3170 } 3171 3172 return SDValue(); 3173 } 3174 3175 /// \brief Return true if the given offset Size in bytes can be folded into 3176 /// the immediate offsets of a memory instruction for the given address space. 3177 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 3178 const SISubtarget &STI) { 3179 switch (AS) { 3180 case AMDGPUAS::GLOBAL_ADDRESS: { 3181 // MUBUF instructions a 12-bit offset in bytes. 3182 return isUInt<12>(OffsetSize); 3183 } 3184 case AMDGPUAS::CONSTANT_ADDRESS: { 3185 // SMRD instructions have an 8-bit offset in dwords on SI and 3186 // a 20-bit offset in bytes on VI. 3187 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3188 return isUInt<20>(OffsetSize); 3189 else 3190 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 3191 } 3192 case AMDGPUAS::LOCAL_ADDRESS: 3193 case AMDGPUAS::REGION_ADDRESS: { 3194 // The single offset versions have a 16-bit offset in bytes. 3195 return isUInt<16>(OffsetSize); 3196 } 3197 case AMDGPUAS::PRIVATE_ADDRESS: 3198 // Indirect register addressing does not use any offsets. 3199 default: 3200 return 0; 3201 } 3202 } 3203 3204 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 3205 3206 // This is a variant of 3207 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 3208 // 3209 // The normal DAG combiner will do this, but only if the add has one use since 3210 // that would increase the number of instructions. 3211 // 3212 // This prevents us from seeing a constant offset that can be folded into a 3213 // memory instruction's addressing mode. If we know the resulting add offset of 3214 // a pointer can be folded into an addressing offset, we can replace the pointer 3215 // operand with the add of new constant offset. This eliminates one of the uses, 3216 // and may allow the remaining use to also be simplified. 3217 // 3218 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 3219 unsigned AddrSpace, 3220 DAGCombinerInfo &DCI) const { 3221 SDValue N0 = N->getOperand(0); 3222 SDValue N1 = N->getOperand(1); 3223 3224 if (N0.getOpcode() != ISD::ADD) 3225 return SDValue(); 3226 3227 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 3228 if (!CN1) 3229 return SDValue(); 3230 3231 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3232 if (!CAdd) 3233 return SDValue(); 3234 3235 // If the resulting offset is too large, we can't fold it into the addressing 3236 // mode offset. 3237 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 3238 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget())) 3239 return SDValue(); 3240 3241 SelectionDAG &DAG = DCI.DAG; 3242 SDLoc SL(N); 3243 EVT VT = N->getValueType(0); 3244 3245 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 3246 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 3247 3248 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 3249 } 3250 3251 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 3252 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 3253 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 3254 (Opc == ISD::XOR && Val == 0); 3255 } 3256 3257 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 3258 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 3259 // integer combine opportunities since most 64-bit operations are decomposed 3260 // this way. TODO: We won't want this for SALU especially if it is an inline 3261 // immediate. 3262 SDValue SITargetLowering::splitBinaryBitConstantOp( 3263 DAGCombinerInfo &DCI, 3264 const SDLoc &SL, 3265 unsigned Opc, SDValue LHS, 3266 const ConstantSDNode *CRHS) const { 3267 uint64_t Val = CRHS->getZExtValue(); 3268 uint32_t ValLo = Lo_32(Val); 3269 uint32_t ValHi = Hi_32(Val); 3270 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3271 3272 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 3273 bitOpWithConstantIsReducible(Opc, ValHi)) || 3274 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 3275 // If we need to materialize a 64-bit immediate, it will be split up later 3276 // anyway. Avoid creating the harder to understand 64-bit immediate 3277 // materialization. 3278 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 3279 } 3280 3281 return SDValue(); 3282 } 3283 3284 SDValue SITargetLowering::performAndCombine(SDNode *N, 3285 DAGCombinerInfo &DCI) const { 3286 if (DCI.isBeforeLegalize()) 3287 return SDValue(); 3288 3289 SelectionDAG &DAG = DCI.DAG; 3290 EVT VT = N->getValueType(0); 3291 SDValue LHS = N->getOperand(0); 3292 SDValue RHS = N->getOperand(1); 3293 3294 3295 if (VT == MVT::i64) { 3296 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 3297 if (CRHS) { 3298 if (SDValue Split 3299 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 3300 return Split; 3301 } 3302 } 3303 3304 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 3305 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 3306 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 3307 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 3308 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 3309 3310 SDValue X = LHS.getOperand(0); 3311 SDValue Y = RHS.getOperand(0); 3312 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 3313 return SDValue(); 3314 3315 if (LCC == ISD::SETO) { 3316 if (X != LHS.getOperand(1)) 3317 return SDValue(); 3318 3319 if (RCC == ISD::SETUNE) { 3320 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 3321 if (!C1 || !C1->isInfinity() || C1->isNegative()) 3322 return SDValue(); 3323 3324 const uint32_t Mask = SIInstrFlags::N_NORMAL | 3325 SIInstrFlags::N_SUBNORMAL | 3326 SIInstrFlags::N_ZERO | 3327 SIInstrFlags::P_ZERO | 3328 SIInstrFlags::P_SUBNORMAL | 3329 SIInstrFlags::P_NORMAL; 3330 3331 static_assert(((~(SIInstrFlags::S_NAN | 3332 SIInstrFlags::Q_NAN | 3333 SIInstrFlags::N_INFINITY | 3334 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 3335 "mask not equal"); 3336 3337 SDLoc DL(N); 3338 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 3339 X, DAG.getConstant(Mask, DL, MVT::i32)); 3340 } 3341 } 3342 } 3343 3344 return SDValue(); 3345 } 3346 3347 SDValue SITargetLowering::performOrCombine(SDNode *N, 3348 DAGCombinerInfo &DCI) const { 3349 SelectionDAG &DAG = DCI.DAG; 3350 SDValue LHS = N->getOperand(0); 3351 SDValue RHS = N->getOperand(1); 3352 3353 EVT VT = N->getValueType(0); 3354 if (VT == MVT::i1) { 3355 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 3356 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 3357 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 3358 SDValue Src = LHS.getOperand(0); 3359 if (Src != RHS.getOperand(0)) 3360 return SDValue(); 3361 3362 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 3363 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 3364 if (!CLHS || !CRHS) 3365 return SDValue(); 3366 3367 // Only 10 bits are used. 3368 static const uint32_t MaxMask = 0x3ff; 3369 3370 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 3371 SDLoc DL(N); 3372 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 3373 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 3374 } 3375 3376 return SDValue(); 3377 } 3378 3379 if (VT != MVT::i64) 3380 return SDValue(); 3381 3382 // TODO: This could be a generic combine with a predicate for extracting the 3383 // high half of an integer being free. 3384 3385 // (or i64:x, (zero_extend i32:y)) -> 3386 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 3387 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 3388 RHS.getOpcode() != ISD::ZERO_EXTEND) 3389 std::swap(LHS, RHS); 3390 3391 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 3392 SDValue ExtSrc = RHS.getOperand(0); 3393 EVT SrcVT = ExtSrc.getValueType(); 3394 if (SrcVT == MVT::i32) { 3395 SDLoc SL(N); 3396 SDValue LowLHS, HiBits; 3397 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 3398 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 3399 3400 DCI.AddToWorklist(LowOr.getNode()); 3401 DCI.AddToWorklist(HiBits.getNode()); 3402 3403 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 3404 LowOr, HiBits); 3405 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 3406 } 3407 } 3408 3409 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 3410 if (CRHS) { 3411 if (SDValue Split 3412 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 3413 return Split; 3414 } 3415 3416 return SDValue(); 3417 } 3418 3419 SDValue SITargetLowering::performXorCombine(SDNode *N, 3420 DAGCombinerInfo &DCI) const { 3421 EVT VT = N->getValueType(0); 3422 if (VT != MVT::i64) 3423 return SDValue(); 3424 3425 SDValue LHS = N->getOperand(0); 3426 SDValue RHS = N->getOperand(1); 3427 3428 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 3429 if (CRHS) { 3430 if (SDValue Split 3431 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 3432 return Split; 3433 } 3434 3435 return SDValue(); 3436 } 3437 3438 SDValue SITargetLowering::performClassCombine(SDNode *N, 3439 DAGCombinerInfo &DCI) const { 3440 SelectionDAG &DAG = DCI.DAG; 3441 SDValue Mask = N->getOperand(1); 3442 3443 // fp_class x, 0 -> false 3444 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 3445 if (CMask->isNullValue()) 3446 return DAG.getConstant(0, SDLoc(N), MVT::i1); 3447 } 3448 3449 if (N->getOperand(0).isUndef()) 3450 return DAG.getUNDEF(MVT::i1); 3451 3452 return SDValue(); 3453 } 3454 3455 // Constant fold canonicalize. 3456 SDValue SITargetLowering::performFCanonicalizeCombine( 3457 SDNode *N, 3458 DAGCombinerInfo &DCI) const { 3459 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 3460 if (!CFP) 3461 return SDValue(); 3462 3463 SelectionDAG &DAG = DCI.DAG; 3464 const APFloat &C = CFP->getValueAPF(); 3465 3466 // Flush denormals to 0 if not enabled. 3467 if (C.isDenormal()) { 3468 EVT VT = N->getValueType(0); 3469 if (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) 3470 return DAG.getConstantFP(0.0, SDLoc(N), VT); 3471 3472 if (VT == MVT::f64 && !Subtarget->hasFP64Denormals()) 3473 return DAG.getConstantFP(0.0, SDLoc(N), VT); 3474 } 3475 3476 if (C.isNaN()) { 3477 EVT VT = N->getValueType(0); 3478 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 3479 if (C.isSignaling()) { 3480 // Quiet a signaling NaN. 3481 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 3482 } 3483 3484 // Make sure it is the canonical NaN bitpattern. 3485 // 3486 // TODO: Can we use -1 as the canonical NaN value since it's an inline 3487 // immediate? 3488 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 3489 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 3490 } 3491 3492 return SDValue(CFP, 0); 3493 } 3494 3495 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 3496 switch (Opc) { 3497 case ISD::FMAXNUM: 3498 return AMDGPUISD::FMAX3; 3499 case ISD::SMAX: 3500 return AMDGPUISD::SMAX3; 3501 case ISD::UMAX: 3502 return AMDGPUISD::UMAX3; 3503 case ISD::FMINNUM: 3504 return AMDGPUISD::FMIN3; 3505 case ISD::SMIN: 3506 return AMDGPUISD::SMIN3; 3507 case ISD::UMIN: 3508 return AMDGPUISD::UMIN3; 3509 default: 3510 llvm_unreachable("Not a min/max opcode"); 3511 } 3512 } 3513 3514 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL, 3515 SDValue Op0, SDValue Op1, bool Signed) { 3516 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 3517 if (!K1) 3518 return SDValue(); 3519 3520 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 3521 if (!K0) 3522 return SDValue(); 3523 3524 if (Signed) { 3525 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 3526 return SDValue(); 3527 } else { 3528 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 3529 return SDValue(); 3530 } 3531 3532 EVT VT = K0->getValueType(0); 3533 3534 MVT NVT = MVT::i32; 3535 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3536 3537 SDValue Tmp1, Tmp2, Tmp3; 3538 Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 3539 Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 3540 Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 3541 3542 if (VT == MVT::i16) { 3543 Tmp1 = DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, NVT, 3544 Tmp1, Tmp2, Tmp3); 3545 3546 return DAG.getNode(ISD::TRUNCATE, SL, VT, Tmp1); 3547 } else 3548 return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT, 3549 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 3550 } 3551 3552 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 3553 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 3554 return true; 3555 3556 return DAG.isKnownNeverNaN(Op); 3557 } 3558 3559 static SDValue performFPMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL, 3560 SDValue Op0, SDValue Op1) { 3561 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1); 3562 if (!K1) 3563 return SDValue(); 3564 3565 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1)); 3566 if (!K0) 3567 return SDValue(); 3568 3569 // Ordered >= (although NaN inputs should have folded away by now). 3570 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 3571 if (Cmp == APFloat::cmpGreaterThan) 3572 return SDValue(); 3573 3574 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 3575 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then 3576 // give the other result, which is different from med3 with a NaN input. 3577 SDValue Var = Op0.getOperand(0); 3578 if (!isKnownNeverSNan(DAG, Var)) 3579 return SDValue(); 3580 3581 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 3582 Var, SDValue(K0, 0), SDValue(K1, 0)); 3583 } 3584 3585 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 3586 DAGCombinerInfo &DCI) const { 3587 SelectionDAG &DAG = DCI.DAG; 3588 3589 unsigned Opc = N->getOpcode(); 3590 SDValue Op0 = N->getOperand(0); 3591 SDValue Op1 = N->getOperand(1); 3592 3593 // Only do this if the inner op has one use since this will just increases 3594 // register pressure for no benefit. 3595 3596 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY) { 3597 // max(max(a, b), c) -> max3(a, b, c) 3598 // min(min(a, b), c) -> min3(a, b, c) 3599 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 3600 SDLoc DL(N); 3601 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 3602 DL, 3603 N->getValueType(0), 3604 Op0.getOperand(0), 3605 Op0.getOperand(1), 3606 Op1); 3607 } 3608 3609 // Try commuted. 3610 // max(a, max(b, c)) -> max3(a, b, c) 3611 // min(a, min(b, c)) -> min3(a, b, c) 3612 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 3613 SDLoc DL(N); 3614 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 3615 DL, 3616 N->getValueType(0), 3617 Op0, 3618 Op1.getOperand(0), 3619 Op1.getOperand(1)); 3620 } 3621 } 3622 3623 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 3624 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 3625 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 3626 return Med3; 3627 } 3628 3629 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 3630 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 3631 return Med3; 3632 } 3633 3634 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 3635 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 3636 (Opc == AMDGPUISD::FMIN_LEGACY && 3637 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 3638 N->getValueType(0) == MVT::f32 && Op0.hasOneUse()) { 3639 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 3640 return Res; 3641 } 3642 3643 return SDValue(); 3644 } 3645 3646 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 3647 DAGCombinerInfo &DCI) const { 3648 SelectionDAG &DAG = DCI.DAG; 3649 SDLoc SL(N); 3650 3651 SDValue LHS = N->getOperand(0); 3652 SDValue RHS = N->getOperand(1); 3653 EVT VT = LHS.getValueType(); 3654 3655 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 3656 VT != MVT::f16)) 3657 return SDValue(); 3658 3659 // Match isinf pattern 3660 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 3661 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 3662 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 3663 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 3664 if (!CRHS) 3665 return SDValue(); 3666 3667 const APFloat &APF = CRHS->getValueAPF(); 3668 if (APF.isInfinity() && !APF.isNegative()) { 3669 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 3670 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 3671 DAG.getConstant(Mask, SL, MVT::i32)); 3672 } 3673 } 3674 3675 return SDValue(); 3676 } 3677 3678 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 3679 DAGCombinerInfo &DCI) const { 3680 SelectionDAG &DAG = DCI.DAG; 3681 SDLoc DL(N); 3682 3683 switch (N->getOpcode()) { 3684 default: 3685 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 3686 case ISD::SETCC: 3687 return performSetCCCombine(N, DCI); 3688 case ISD::FMAXNUM: 3689 case ISD::FMINNUM: 3690 case ISD::SMAX: 3691 case ISD::SMIN: 3692 case ISD::UMAX: 3693 case ISD::UMIN: 3694 case AMDGPUISD::FMIN_LEGACY: 3695 case AMDGPUISD::FMAX_LEGACY: { 3696 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 3697 N->getValueType(0) != MVT::f64 && 3698 getTargetMachine().getOptLevel() > CodeGenOpt::None) 3699 return performMinMaxCombine(N, DCI); 3700 break; 3701 } 3702 3703 case AMDGPUISD::CVT_F32_UBYTE0: 3704 case AMDGPUISD::CVT_F32_UBYTE1: 3705 case AMDGPUISD::CVT_F32_UBYTE2: 3706 case AMDGPUISD::CVT_F32_UBYTE3: { 3707 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 3708 3709 SDValue Src = N->getOperand(0); 3710 SDValue Srl = N->getOperand(0); 3711 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 3712 Srl = Srl.getOperand(0); 3713 3714 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 3715 if (Srl.getOpcode() == ISD::SRL) { 3716 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 3717 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 3718 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 3719 3720 if (const ConstantSDNode *C = 3721 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 3722 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 3723 EVT(MVT::i32)); 3724 3725 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 3726 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 3727 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, DL, 3728 MVT::f32, Srl); 3729 } 3730 } 3731 } 3732 3733 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 3734 3735 APInt KnownZero, KnownOne; 3736 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 3737 !DCI.isBeforeLegalizeOps()); 3738 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3739 if (TLO.ShrinkDemandedConstant(Src, Demanded) || 3740 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) { 3741 DCI.CommitTargetLoweringOpt(TLO); 3742 } 3743 3744 break; 3745 } 3746 case ISD::SINT_TO_FP: 3747 case ISD::UINT_TO_FP: { 3748 return performUCharToFloatCombine(N, DCI); 3749 } 3750 case ISD::FADD: { 3751 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 3752 break; 3753 3754 EVT VT = N->getValueType(0); 3755 if (VT != MVT::f32) 3756 break; 3757 3758 // Only do this if we are not trying to support denormals. v_mad_f32 does 3759 // not support denormals ever. 3760 if (Subtarget->hasFP32Denormals()) 3761 break; 3762 3763 SDValue LHS = N->getOperand(0); 3764 SDValue RHS = N->getOperand(1); 3765 3766 // These should really be instruction patterns, but writing patterns with 3767 // source modiifiers is a pain. 3768 3769 // fadd (fadd (a, a), b) -> mad 2.0, a, b 3770 if (LHS.getOpcode() == ISD::FADD) { 3771 SDValue A = LHS.getOperand(0); 3772 if (A == LHS.getOperand(1)) { 3773 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 3774 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS); 3775 } 3776 } 3777 3778 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 3779 if (RHS.getOpcode() == ISD::FADD) { 3780 SDValue A = RHS.getOperand(0); 3781 if (A == RHS.getOperand(1)) { 3782 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 3783 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS); 3784 } 3785 } 3786 3787 return SDValue(); 3788 } 3789 case ISD::FSUB: { 3790 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 3791 break; 3792 3793 EVT VT = N->getValueType(0); 3794 3795 // Try to get the fneg to fold into the source modifier. This undoes generic 3796 // DAG combines and folds them into the mad. 3797 // 3798 // Only do this if we are not trying to support denormals. v_mad_f32 does 3799 // not support denormals ever. 3800 if (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) { 3801 SDValue LHS = N->getOperand(0); 3802 SDValue RHS = N->getOperand(1); 3803 if (LHS.getOpcode() == ISD::FADD) { 3804 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 3805 3806 SDValue A = LHS.getOperand(0); 3807 if (A == LHS.getOperand(1)) { 3808 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32); 3809 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS); 3810 3811 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS); 3812 } 3813 } 3814 3815 if (RHS.getOpcode() == ISD::FADD) { 3816 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 3817 3818 SDValue A = RHS.getOperand(0); 3819 if (A == RHS.getOperand(1)) { 3820 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32); 3821 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS); 3822 } 3823 } 3824 3825 return SDValue(); 3826 } 3827 3828 break; 3829 } 3830 case ISD::LOAD: 3831 case ISD::STORE: 3832 case ISD::ATOMIC_LOAD: 3833 case ISD::ATOMIC_STORE: 3834 case ISD::ATOMIC_CMP_SWAP: 3835 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3836 case ISD::ATOMIC_SWAP: 3837 case ISD::ATOMIC_LOAD_ADD: 3838 case ISD::ATOMIC_LOAD_SUB: 3839 case ISD::ATOMIC_LOAD_AND: 3840 case ISD::ATOMIC_LOAD_OR: 3841 case ISD::ATOMIC_LOAD_XOR: 3842 case ISD::ATOMIC_LOAD_NAND: 3843 case ISD::ATOMIC_LOAD_MIN: 3844 case ISD::ATOMIC_LOAD_MAX: 3845 case ISD::ATOMIC_LOAD_UMIN: 3846 case ISD::ATOMIC_LOAD_UMAX: 3847 case AMDGPUISD::ATOMIC_INC: 3848 case AMDGPUISD::ATOMIC_DEC: { // TODO: Target mem intrinsics. 3849 if (DCI.isBeforeLegalize()) 3850 break; 3851 3852 MemSDNode *MemNode = cast<MemSDNode>(N); 3853 SDValue Ptr = MemNode->getBasePtr(); 3854 3855 // TODO: We could also do this for multiplies. 3856 unsigned AS = MemNode->getAddressSpace(); 3857 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) { 3858 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 3859 if (NewPtr) { 3860 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end()); 3861 3862 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 3863 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0); 3864 } 3865 } 3866 break; 3867 } 3868 case ISD::AND: 3869 return performAndCombine(N, DCI); 3870 case ISD::OR: 3871 return performOrCombine(N, DCI); 3872 case ISD::XOR: 3873 return performXorCombine(N, DCI); 3874 case AMDGPUISD::FP_CLASS: 3875 return performClassCombine(N, DCI); 3876 case ISD::FCANONICALIZE: 3877 return performFCanonicalizeCombine(N, DCI); 3878 case AMDGPUISD::FRACT: 3879 case AMDGPUISD::RCP: 3880 case AMDGPUISD::RSQ: 3881 case AMDGPUISD::RCP_LEGACY: 3882 case AMDGPUISD::RSQ_LEGACY: 3883 case AMDGPUISD::RSQ_CLAMP: 3884 case AMDGPUISD::LDEXP: { 3885 SDValue Src = N->getOperand(0); 3886 if (Src.isUndef()) 3887 return Src; 3888 break; 3889 } 3890 } 3891 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 3892 } 3893 3894 /// \brief Helper function for adjustWritemask 3895 static unsigned SubIdx2Lane(unsigned Idx) { 3896 switch (Idx) { 3897 default: return 0; 3898 case AMDGPU::sub0: return 0; 3899 case AMDGPU::sub1: return 1; 3900 case AMDGPU::sub2: return 2; 3901 case AMDGPU::sub3: return 3; 3902 } 3903 } 3904 3905 /// \brief Adjust the writemask of MIMG instructions 3906 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 3907 SelectionDAG &DAG) const { 3908 SDNode *Users[4] = { }; 3909 unsigned Lane = 0; 3910 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 3911 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 3912 unsigned NewDmask = 0; 3913 3914 // Try to figure out the used register components 3915 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 3916 I != E; ++I) { 3917 3918 // Abort if we can't understand the usage 3919 if (!I->isMachineOpcode() || 3920 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 3921 return; 3922 3923 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 3924 // Note that subregs are packed, i.e. Lane==0 is the first bit set 3925 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 3926 // set, etc. 3927 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 3928 3929 // Set which texture component corresponds to the lane. 3930 unsigned Comp; 3931 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 3932 assert(Dmask); 3933 Comp = countTrailingZeros(Dmask); 3934 Dmask &= ~(1 << Comp); 3935 } 3936 3937 // Abort if we have more than one user per component 3938 if (Users[Lane]) 3939 return; 3940 3941 Users[Lane] = *I; 3942 NewDmask |= 1 << Comp; 3943 } 3944 3945 // Abort if there's no change 3946 if (NewDmask == OldDmask) 3947 return; 3948 3949 // Adjust the writemask in the node 3950 std::vector<SDValue> Ops; 3951 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 3952 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 3953 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 3954 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 3955 3956 // If we only got one lane, replace it with a copy 3957 // (if NewDmask has only one bit set...) 3958 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 3959 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 3960 MVT::i32); 3961 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 3962 SDLoc(), Users[Lane]->getValueType(0), 3963 SDValue(Node, 0), RC); 3964 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 3965 return; 3966 } 3967 3968 // Update the users of the node with the new indices 3969 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 3970 3971 SDNode *User = Users[i]; 3972 if (!User) 3973 continue; 3974 3975 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 3976 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 3977 3978 switch (Idx) { 3979 default: break; 3980 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 3981 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 3982 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 3983 } 3984 } 3985 } 3986 3987 static bool isFrameIndexOp(SDValue Op) { 3988 if (Op.getOpcode() == ISD::AssertZext) 3989 Op = Op.getOperand(0); 3990 3991 return isa<FrameIndexSDNode>(Op); 3992 } 3993 3994 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 3995 /// with frame index operands. 3996 /// LLVM assumes that inputs are to these instructions are registers. 3997 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 3998 SelectionDAG &DAG) const { 3999 4000 SmallVector<SDValue, 8> Ops; 4001 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 4002 if (!isFrameIndexOp(Node->getOperand(i))) { 4003 Ops.push_back(Node->getOperand(i)); 4004 continue; 4005 } 4006 4007 SDLoc DL(Node); 4008 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 4009 Node->getOperand(i).getValueType(), 4010 Node->getOperand(i)), 0)); 4011 } 4012 4013 DAG.UpdateNodeOperands(Node, Ops); 4014 } 4015 4016 /// \brief Fold the instructions after selecting them. 4017 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 4018 SelectionDAG &DAG) const { 4019 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4020 unsigned Opcode = Node->getMachineOpcode(); 4021 4022 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 4023 !TII->isGather4(Opcode)) 4024 adjustWritemask(Node, DAG); 4025 4026 if (Opcode == AMDGPU::INSERT_SUBREG || 4027 Opcode == AMDGPU::REG_SEQUENCE) { 4028 legalizeTargetIndependentNode(Node, DAG); 4029 return Node; 4030 } 4031 return Node; 4032 } 4033 4034 /// \brief Assign the register class depending on the number of 4035 /// bits set in the writemask 4036 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 4037 SDNode *Node) const { 4038 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4039 4040 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 4041 4042 if (TII->isVOP3(MI.getOpcode())) { 4043 // Make sure constant bus requirements are respected. 4044 TII->legalizeOperandsVOP3(MRI, MI); 4045 return; 4046 } 4047 4048 if (TII->isMIMG(MI)) { 4049 unsigned VReg = MI.getOperand(0).getReg(); 4050 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4; 4051 unsigned Writemask = MI.getOperand(DmaskIdx).getImm(); 4052 unsigned BitsSet = 0; 4053 for (unsigned i = 0; i < 4; ++i) 4054 BitsSet += Writemask & (1 << i) ? 1 : 0; 4055 4056 const TargetRegisterClass *RC; 4057 switch (BitsSet) { 4058 default: return; 4059 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 4060 case 2: RC = &AMDGPU::VReg_64RegClass; break; 4061 case 3: RC = &AMDGPU::VReg_96RegClass; break; 4062 } 4063 4064 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet); 4065 MI.setDesc(TII->get(NewOpcode)); 4066 MRI.setRegClass(VReg, RC); 4067 return; 4068 } 4069 4070 // Replace unused atomics with the no return version. 4071 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 4072 if (NoRetAtomicOp != -1) { 4073 if (!Node->hasAnyUseOfValue(0)) { 4074 MI.setDesc(TII->get(NoRetAtomicOp)); 4075 MI.RemoveOperand(0); 4076 return; 4077 } 4078 4079 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 4080 // instruction, because the return type of these instructions is a vec2 of 4081 // the memory type, so it can be tied to the input operand. 4082 // This means these instructions always have a use, so we need to add a 4083 // special case to check if the atomic has only one extract_subreg use, 4084 // which itself has no uses. 4085 if ((Node->hasNUsesOfValue(1, 0) && 4086 Node->use_begin()->isMachineOpcode() && 4087 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 4088 !Node->use_begin()->hasAnyUseOfValue(0))) { 4089 unsigned Def = MI.getOperand(0).getReg(); 4090 4091 // Change this into a noret atomic. 4092 MI.setDesc(TII->get(NoRetAtomicOp)); 4093 MI.RemoveOperand(0); 4094 4095 // If we only remove the def operand from the atomic instruction, the 4096 // extract_subreg will be left with a use of a vreg without a def. 4097 // So we need to insert an implicit_def to avoid machine verifier 4098 // errors. 4099 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 4100 TII->get(AMDGPU::IMPLICIT_DEF), Def); 4101 } 4102 return; 4103 } 4104 } 4105 4106 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 4107 uint64_t Val) { 4108 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 4109 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 4110 } 4111 4112 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 4113 const SDLoc &DL, 4114 SDValue Ptr) const { 4115 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4116 4117 // Build the half of the subregister with the constants before building the 4118 // full 128-bit register. If we are building multiple resource descriptors, 4119 // this will allow CSEing of the 2-component register. 4120 const SDValue Ops0[] = { 4121 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 4122 buildSMovImm32(DAG, DL, 0), 4123 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 4124 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 4125 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 4126 }; 4127 4128 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 4129 MVT::v2i32, Ops0), 0); 4130 4131 // Combine the constants and the pointer. 4132 const SDValue Ops1[] = { 4133 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 4134 Ptr, 4135 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 4136 SubRegHi, 4137 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 4138 }; 4139 4140 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 4141 } 4142 4143 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 4144 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 4145 /// of the resource descriptor) to create an offset, which is added to 4146 /// the resource pointer. 4147 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 4148 SDValue Ptr, uint32_t RsrcDword1, 4149 uint64_t RsrcDword2And3) const { 4150 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 4151 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 4152 if (RsrcDword1) { 4153 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 4154 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 4155 0); 4156 } 4157 4158 SDValue DataLo = buildSMovImm32(DAG, DL, 4159 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 4160 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 4161 4162 const SDValue Ops[] = { 4163 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 4164 PtrLo, 4165 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 4166 PtrHi, 4167 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 4168 DataLo, 4169 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 4170 DataHi, 4171 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 4172 }; 4173 4174 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 4175 } 4176 4177 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG, 4178 const TargetRegisterClass *RC, 4179 unsigned Reg, EVT VT) const { 4180 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT); 4181 4182 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()), 4183 cast<RegisterSDNode>(VReg)->getReg(), VT); 4184 } 4185 4186 //===----------------------------------------------------------------------===// 4187 // SI Inline Assembly Support 4188 //===----------------------------------------------------------------------===// 4189 4190 std::pair<unsigned, const TargetRegisterClass *> 4191 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 4192 StringRef Constraint, 4193 MVT VT) const { 4194 4195 if (Constraint.size() == 1) { 4196 switch (Constraint[0]) { 4197 case 's': 4198 case 'r': 4199 switch (VT.getSizeInBits()) { 4200 default: 4201 return std::make_pair(0U, nullptr); 4202 case 32: 4203 return std::make_pair(0U, &AMDGPU::SReg_32RegClass); 4204 case 64: 4205 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 4206 case 128: 4207 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 4208 case 256: 4209 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 4210 } 4211 4212 case 'v': 4213 switch (VT.getSizeInBits()) { 4214 default: 4215 return std::make_pair(0U, nullptr); 4216 case 32: 4217 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 4218 case 64: 4219 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 4220 case 96: 4221 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 4222 case 128: 4223 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 4224 case 256: 4225 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 4226 case 512: 4227 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 4228 } 4229 } 4230 } 4231 4232 if (Constraint.size() > 1) { 4233 const TargetRegisterClass *RC = nullptr; 4234 if (Constraint[1] == 'v') { 4235 RC = &AMDGPU::VGPR_32RegClass; 4236 } else if (Constraint[1] == 's') { 4237 RC = &AMDGPU::SGPR_32RegClass; 4238 } 4239 4240 if (RC) { 4241 uint32_t Idx; 4242 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 4243 if (!Failed && Idx < RC->getNumRegs()) 4244 return std::make_pair(RC->getRegister(Idx), RC); 4245 } 4246 } 4247 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4248 } 4249 4250 SITargetLowering::ConstraintType 4251 SITargetLowering::getConstraintType(StringRef Constraint) const { 4252 if (Constraint.size() == 1) { 4253 switch (Constraint[0]) { 4254 default: break; 4255 case 's': 4256 case 'v': 4257 return C_RegisterClass; 4258 } 4259 } 4260 return TargetLowering::getConstraintType(Constraint); 4261 } 4262