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