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